diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index e0b190e..140a0cf 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -323,6 +323,79 @@ pub(crate) fn begin_sync_heaps() -> SyncedHeaps { SyncedHeaps(Some(mine)) } +/// [`begin_sync_heaps`] for a submission that needs round `mark` (one that +/// began after what it reads was written, `crate::heap_marks`): asked for if +/// it has not been. 0: as [`begin_sync_heaps`]. Ported from +/// Belobug/VIctory-Belobug-AMD 673be0e and a609a2f. +#[cfg(windows)] +pub(crate) fn begin_sync_heaps_after(mark: u64) -> SyncedHeaps { + if mark == 0 || !sync_aside() { + return begin_sync_heaps(); + } + // (The thread is started by the first `begin_sync_heaps`.) + let mut rounds = SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner()); + if rounds.1 == 0 && rounds.0 == 0 { + drop(rounds); + return begin_sync_heaps(); + } + let asked = rounds.0 < mark; + rounds.0 = rounds.0.max(mark); + drop(rounds); + use crate::heap_marks::{EARLY_ROUNDS, LATE_ROUNDS, STATS}; + if asked { + SYNC_ROUNDS.1.notify_all(); + STATS[LATE_ROUNDS].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } else { + STATS[EARLY_ROUNDS].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + SyncedHeaps(Some(mark)) +} + +/// The number of a round of the heaps' records that begins after this call, +/// asked for if none is waiting to begin (at the title's submit: the round +/// runs while the submission waits in the line). 0 if the records are not +/// synced by a thread of their own (or it has not started yet). +#[cfg(windows)] +pub(crate) fn round_after_now() -> u64 { + if !sync_aside() { + return 0; + } + let mut rounds = SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner()); + if rounds.1 == 0 && rounds.0 == 0 { + return 0; + } + let (round, ask) = crate::heap_marks::round_after(rounds.0, rounds.1); + if ask { + rounds.0 = round; + drop(rounds); + SYNC_ROUNDS.1.notify_all(); + crate::heap_marks::STATS[crate::heap_marks::ROUNDS_ASKED].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + round +} + +/// The number of the first round that begins after this call, not asked for +/// ([`begin_sync_heaps_after`] asks for it if nobody did). +#[cfg(windows)] +pub(crate) fn round_mark() -> u64 { + if !sync_aside() { + return 0; + } + let rounds = SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner()); + if rounds.1 == 0 && rounds.0 == 0 { + return 0; + } + rounds.0 + 1 +} + +/// Whether `[at, at + len)` touches the title memory of a placed +/// shader-visible heap of descriptors. +#[cfg(windows)] +pub(crate) fn in_shader_heap(at: usize, len: usize) -> bool { + let (from, to) = (at as u64, at as u64 + len as u64); + SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()).iter().any(|&(start, end, _)| from < end && start < to) +} + #[cfg(windows)] impl Drop for SyncedHeaps { fn drop(&mut self) { @@ -360,8 +433,10 @@ pub(crate) fn sync_heaps() { let mut spent = [0u64; 3]; let since = |at: std::time::Instant| at.elapsed().as_nanos() as u64; let mut kinds = [0u64; 5]; + let mut short = 0u64; let mut wait: Vec = Vec::new(); let frame = crate::frame::current(); + let (pages_a_job, records_a_job) = sync_jobs(); let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); for &(start, end, at) in heaps.iter() { // SAFETY: registered heaps are live (removed when dropped). @@ -379,8 +454,8 @@ pub(crate) fn sync_heaps() { // since: a shader may pick them by index. let before = host.copied_before(frame); let of_tables = std::sync::atomic::AtomicU64::new(0); - crate::land::each_view(true, before.len().div_ceil(SYNC_AT_A_TIME), &|n| { - for &index in before.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() { + crate::land::each_view(true, before.len().div_ceil(records_a_job), &|n| { + for &index in before.chunks(records_a_job).nth(n).unwrap_or_default() { if host.copied_tabled(index, frame) { of_tables.fetch_add(1, Relaxed); } else { @@ -411,37 +486,62 @@ pub(crate) fn sync_heaps() { let began = std::time::Instant::now(); let copied = host.copied_begin(step as usize); let samplers = heap.samplers(); - let found: Vec> = parts.chunks(SYNC_PAGES).map(|_| Default::default()).collect(); + let in_place = sync_in_place() && step == 32 && crate::safecopy::on(); + let found: Vec> = parts.chunks(pages_a_job).map(|_| Default::default()).collect(); crate::land::each_view(true, found.len(), &|n| { let mut out = SyncPart::default(); let mut page_bytes: Vec = Vec::new(); let mut changed: Vec = Vec::new(); - for &(from, to) in parts.chunks(SYNC_PAGES).nth(n).unwrap_or_default() { - // The page's records are read through the kernel, into a - // copy: a page the title unmaps meanwhile fails the read - // where 2,048 reads in place would fault. - page_bytes.resize(to - from, 0); - if !crate::host::read_into(from as *const u8, &mut page_bytes) { - continue; - } - out.pages += 1; - out.views += u64::from(crate::watch::guarded(from, to)); - out.bytes += (to - from) as u64; + let mut bits: Vec = Vec::new(); + for &(from, to) in parts.chunks(pages_a_job).nth(n).unwrap_or_default() { let slots = changed_slots(from, to, start as usize, step, mirrored_count); // A record that straddles the range's ends is left // to the range that holds its first byte. let first = ((from - start as usize) as u64).div_ceil(step).max(slots.start); - let Some(records) = page_bytes.get((start + first * step) as usize - from..) else { - continue; + let lead = (start + first * step) as usize; + let records: &[u8] = if in_place { + // Read where they are, each record once, and compared + // as it is read (`host::Copied::changes_in_place`). + let count = (to.saturating_sub(lead) as u64 / step).min(slots.end.saturating_sub(first)); + changed.clear(); + // SAFETY: as below; title memory is read by a copy that + // fails where a page is not there. + let whole = + unsafe { copied.changes_in_place(first as u32, lead as *const u8, count as usize, &mut bits, &mut changed) }; + out.pages += 1; + out.views += u64::from(crate::watch::guarded(from, to)); + out.bytes += (to - from) as u64; + out.looked += count; + out.short += u64::from(!whole); + // What was read of the changed records is in the records + // last seen now. + // SAFETY: this part's records alone, which nothing else + // writes meanwhile. + unsafe { copied.seen(first as u32, count as usize) } + } else { + // The page's records are read through the kernel, into a + // copy: a page the title unmaps meanwhile fails the read + // where 2,048 reads in place would fault. + page_bytes.resize(to - from, 0); + if !crate::host::read_into(from as *const u8, &mut page_bytes) { + continue; + } + out.pages += 1; + out.views += u64::from(crate::watch::guarded(from, to)); + out.bytes += (to - from) as u64; + let Some(records) = page_bytes.get(lead.wrapping_sub(from)..) else { + continue; + }; + let count = (records.len() as u64 / step).min(slots.end.saturating_sub(first)); + out.looked += count; + // Only the records that are not the ones last seen + // there (`host::Copied::changes`). + changed.clear(); + // SAFETY: the parts are ranges of the heap apart from one + // another, and only records that lie whole in one are its. + unsafe { copied.changes(first as u32, &records[..(count * step) as usize], &mut changed) }; + records }; - let count = (records.len() as u64 / step).min(slots.end.saturating_sub(first)); - out.looked += count; - // Only the records that are not the ones last seen - // there (`host::Copied::changes`). - changed.clear(); - // SAFETY: the parts are ranges of the heap apart from one - // another, and only records that lie whole in one are its. - unsafe { copied.changes(first as u32, &records[..(count * step) as usize], &mut changed) }; for &index in &changed { let at = (u64::from(index) - first) as usize * step as usize; let word = |n: usize| { @@ -494,6 +594,7 @@ pub(crate) fn sync_heaps() { views += part.views; bytes += part.bytes; looked += part.looked; + short += part.short; tabled += part.tabled; kinds[0] += part.nothing; later += part.wait.len() as u64; @@ -506,8 +607,8 @@ pub(crate) fn sync_heaps() { } spent[1] += since(began); let began = std::time::Instant::now(); - crate::land::each_view(true, make.len().div_ceil(SYNC_AT_A_TIME), &|n| { - for &index in make.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() { + crate::land::each_view(true, make.len().div_ceil(records_a_job), &|n| { + for &index in make.chunks(records_a_job).nth(n).unwrap_or_default() { host.mirror(index, start + u64::from(index) * step, false); } }); @@ -528,6 +629,34 @@ pub(crate) fn sync_heaps() { for (count, n) in SYNCED_KINDS.iter().zip(kinds) { count.fetch_add(n, Relaxed); } + SYNC_SHORT.fetch_add(short, Relaxed); +} + +/// Pages [`sync_heaps`] read in place of which a part could not be read +/// ([`sync_in_place`]), since the last frame line. +#[cfg(windows)] +static SYNC_SHORT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether [`sync_heaps`] reads a changed page's records where they are, each +/// once, and compares each with the one last seen as it reads it, 32 bytes at +/// a time (`VICTORY_SYNC_IN_PLACE=1`; off by default: into a copy of the page +/// first, through the kernel, then compared, as before). +/// +/// Ported from Belobug/VIctory-Belobug-AMD 15ab94e (measured there: the copy +/// and the compare were each a pass over all of the page, 7.4 and 5.3 ms a +/// frame of the six threads for 35 MB, run heapsync-ab1; on by default there +/// since 8822ed4). Here the round's "reading and comparing" was 2.6-3.1 ms a +/// frame (release run 233354), and the submitting thread waits for the +/// round. A page the title unmaps meanwhile fails where the copy failed; the +/// records before the place are taken as they were read. +#[cfg(windows)] +fn sync_in_place() -> bool { + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("VICTORY_SYNC_IN_PLACE") { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SYNC_IN_PLACE").is_some_and(|v| v != "0")) } /// Of those mirrored, since the last frame line: no view, a view of an object, @@ -548,6 +677,8 @@ struct SyncPart { make: Vec, wait: Vec, kinds: [u64; 5], + /// Pages read in place not all there ([`SYNC_SHORT`]). + short: u64, } /// Pages [`sync_heaps`] gives a thread at a time. @@ -558,6 +689,35 @@ const SYNC_PAGES: usize = 8; #[cfg(windows)] const SYNC_AT_A_TIME: usize = 256; +/// With `VICTORY_SYNC_FINE=1`: pages and records [`sync_heaps`] gives a thread +/// at a time. +#[cfg(windows)] +const SYNC_PAGES_FINE: usize = 2; +#[cfg(windows)] +const SYNC_AT_A_TIME_FINE: usize = 64; + +/// Pages and records [`sync_heaps`] gives a thread at a time +/// (`VICTORY_SYNC_FINE=1`: [`SYNC_PAGES_FINE`] and [`SYNC_AT_A_TIME_FINE`]; +/// off by default: [`SYNC_PAGES`] and [`SYNC_AT_A_TIME`], as before). +/// +/// Ported from Belobug/VIctory-Belobug-AMD a284ca7: a round for a submission +/// finds a dozen pages or so; by eight a job that was two jobs, on two of the +/// six threads, while the submission waited for the round (2 to 3.4 ms at a +/// time, their run city4). +#[cfg(windows)] +fn sync_jobs() -> (usize, usize) { + #[cfg(feature = "diagnostics")] + if let Some(fine) = crate::ab::pick("VICTORY_SYNC_FINE") { + return if fine { (SYNC_PAGES_FINE, SYNC_AT_A_TIME_FINE) } else { (SYNC_PAGES, SYNC_AT_A_TIME) }; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if *ON.get_or_init(|| std::env::var_os("VICTORY_SYNC_FINE").is_some_and(|v| v != "0")) { + (SYNC_PAGES_FINE, SYNC_AT_A_TIME_FINE) + } else { + (SYNC_PAGES, SYNC_AT_A_TIME) + } +} + /// Since the last frame line, of [`sync_heaps`]: changed pages of placed /// shader-visible heaps looked at, slots on them, slots whose record was /// not the one last seen and was mirrored, the microseconds it took; then @@ -589,9 +749,27 @@ pub(crate) fn sync_line(frames: f64) { let [pages, looked, mirrored, micros, tabled, later, waited] = [0, 1, 2, 3, 4, 5, 6].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); let split = [0, 1, 2, 3, 4].map(|i| SYNC_SPLIT[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64); let kinds = [0, 1, 2, 3, 4].map(|i| SYNCED_KINDS[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames); + let short = SYNC_SHORT.swap(0, std::sync::atomic::Ordering::Relaxed); + let quick = [0, 1].map(|i| host::SPANS_QUICK[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames); + if quick[0] > 0.0 || sync_jobs().0 == SYNC_PAGES_FINE { + tracing::info!( + "writes of view slots per frame (VICTORY_SPANS_QUICK=1): {:.0} leaving the placed views' spans alone, {:.0} under \ + their lock; the heaps' records in jobs of {} pages (VICTORY_SYNC_FINE)", + quick[0], + quick[1], + sync_jobs().0 + ); + } if pages == 0 { return; } + if sync_in_place() { + tracing::info!( + "the heaps' records read where they are (VICTORY_SYNC_IN_PLACE=1): {:.1} pages per frame, {short} of them not all \ + there since the last line", + pages as f64 / frames + ); + } tracing::info!( "descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \ {:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.1} new ones of \ diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 88bc419..9045bb0 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -214,6 +214,35 @@ pub(crate) struct HostHeap { /// other memory there makes stale, and which to look at again when the /// runtime maps, unmaps or writes memory ([`remapped`]). placed: std::sync::Arc>, + /// The slots that may be in `placed` (a slot noted there is put here + /// under its lock, and taken out when it is forgotten there; a slot + /// another's view made stale stays, which says only "may"): a write of + /// any other view needs nothing of `placed` ([`spans_quick`]). + spanned: Slots, +} + +/// Since the last frame line: writes that left `placed` alone +/// ([`spans_quick`]), writes that took its lock. +pub(crate) static SPANS_QUICK: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether a slot's write of no placed texture view leaves `placed` alone +/// when the slot is not in it ([`HostHeap::spanned`]; `VICTORY_SPANS_QUICK=1`; +/// off by default: its lock is taken for every write, as before). +/// +/// Ported from Belobug/VIctory-Belobug-AMD a284ca7 (on by default there). +/// Every record the pass over records copied as bytes mirrors went by that +/// one lock of the heap, from six threads, with the title's own threads and +/// the texture passes: 4 of the 16 ms a frame the submitting thread waited +/// for that pass were its threads waiting there (their run city4, timeline +/// 113). What is done is the same: forgetting a slot that is not there does +/// nothing. +fn spans_quick() -> bool { + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("VICTORY_SPANS_QUICK") { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SPANS_QUICK").is_some_and(|v| v != "0")) } /// The spans of every view heap made ([`HostHeap::placed`]), for the @@ -1963,6 +1992,7 @@ impl HostHeap { } spans }, + spanned: Slots::new((count + extra) as usize), }; // A slot never written is undefined: shaders reading one (a slot // the title wrote in a way we do not know, or a table entry no @@ -3214,8 +3244,18 @@ impl HostHeap { } _ => None, }; - let stale = { + // (Under the slot's lock, as every write of it: whether it is in + // `spanned` changes only here.) + let in_spans = |index: u32| { + let bit = 1u64 << (index % 64); + self.spanned.0.get(index as usize / 64).is_none_or(|w| w.load(std::sync::atomic::Ordering::Acquire) & bit != 0) + }; + let stale = if placed_view.is_none() && !in_spans(index) && spans_quick() { + SPANS_QUICK[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Vec::new() + } else { use std::sync::atomic::Ordering::Relaxed; + SPANS_QUICK[1].fetch_add(1, Relaxed); let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); let span = placed_view.and_then(|(resource, start, first, held)| { Some((start, start.saturating_add(placed.bytes(resource)?), first, held)) @@ -3225,6 +3265,7 @@ impl HostHeap { SPANNED[0].fetch_min(start, Relaxed); SPANNED[1].fetch_max(end, Relaxed); placed.rule = stale_rule(); + self.spanned.put(index); let stale = placed.note(index, start, end, !seen); placed.shows(index, first, held); // (Under the lock of `placed`: a later write of one of @@ -3233,6 +3274,7 @@ impl HostHeap { } None => { placed.forget(index); + self.spanned.remove(index); Vec::new() } } @@ -5153,6 +5195,48 @@ impl Copied<'_> { let last = unsafe { std::slice::from_raw_parts_mut(self.at.add(at), end - at) }; changed_records(last, &records[..end - at], self.step, first, out); } + + /// As [`Copied::changes`] for the `count` records of title memory at + /// `title` (slot `first` on), 32 bytes each, read where they are, each + /// once ([`crate::safecopy::changed`]); `bits` is room. False when a page + /// of them could not be read: those before it are done, the others + /// stay as last seen. + /// + /// # Safety + /// As [`Copied::changes`]; `title` is title memory (read by a copy that + /// fails where a page is not there). + pub(crate) unsafe fn changes_in_place(&self, first: u32, title: *const u8, count: usize, bits: &mut Vec, out: &mut Vec) -> bool { + let at = first as usize * self.step; + let count = count.min(self.len.saturating_sub(at) / 32); + if self.step != 32 || count == 0 { + return true; + } + bits.clear(); + bits.resize(count.div_ceil(64), 0); + // SAFETY: within the records held; the caller's slots alone. + let whole = unsafe { crate::safecopy::changed(title, self.at.add(at), count, bits) }; + for (n, &word) in bits.iter().enumerate() { + let mut word = word; + while word != 0 { + out.push(first + (n * 64) as u32 + word.trailing_zeros()); + word &= word - 1; + } + } + whole + } + + /// The `count` records last seen from slot `first` on (fewer where the + /// heap ends). + /// + /// # Safety + /// As [`Copied::changes`]: no other call beside this one has any of + /// these slots. + pub(crate) unsafe fn seen(&self, first: u32, count: usize) -> &[u8] { + let at = (first as usize * self.step).min(self.len); + let len = (count * self.step).min(self.len - at); + // SAFETY: within the records held; the caller's slots alone. + unsafe { std::slice::from_raw_parts(self.at.add(at), len) } + } } /// The records (`step` bytes each, the first is slot `first`) that differ @@ -6188,6 +6272,38 @@ mod tests { assert_eq!(slots(u64::MAX), [2]); } + /// A write of no placed texture view forgets the slot in the spans + /// whether it goes by their lock or not (`spans_quick`): slots that are + /// in them stay marked, also one another's view made stale. + #[test] + fn writes_of_other_views_leave_the_spans_as_under_their_lock() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let marked = |slot: u32| heap.spanned.all(|_| true).contains(&slot); + let at = 0x7fed_0000_0000u64; + let view = |address: u64, width: u32| { + let mut desc = [0u32; 16]; + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + View::Placed(false, [3, 0, 0, 0, width, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc) + }; + assert!(heap.note_buffer(1, Some(&view(at, 64)), false).is_empty()); + assert!(marked(1) && !marked(2)); + // Slot 1 made stale by slot 2: out of `by_slot`, still in `first`. + assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [(1, 0)]); + assert!(marked(1) && marked(2)); + assert!(heap.placed.lock().unwrap().first.contains_key(&1)); + // Written with no view: forgotten, under the lock, and unmarked. + assert!(heap.note_buffer(1, None, false).is_empty()); + assert!(!marked(1) && !heap.placed.lock().unwrap().first.contains_key(&1)); + // A slot never in the spans: nothing there to change. + assert!(heap.note_buffer(3, None, false).is_empty()); + assert!(heap.note_buffer(2, None, false).is_empty()); + let spans = heap.placed.lock().unwrap(); + assert!(spans.by_slot.is_empty() && spans.by_start.is_empty() && spans.first.is_empty()); + assert!(heap.spanned.all(|_| true).is_empty()); + } + #[test] fn a_set_of_slots_holds_what_was_put_in() { let set = Slots::new(200); diff --git a/crates/victory-gpu/src/heap_marks.rs b/crates/victory-gpu/src/heap_marks.rs new file mode 100644 index 0000000..0bd6e62 --- /dev/null +++ b/crates/victory-gpu/src/heap_marks.rs @@ -0,0 +1,190 @@ +//! The heaps' records asked for at the title's submit +//! (`VICTORY_HEAP_SYNC_AT_SUBMIT=1`, off by default). +//! +//! Ported from Belobug/VIctory-Belobug-AMD 673be0e and a609a2f (renderer +//! port 7, its heaps' records part; there under `VICTORY_PORT_JOURNAL` with +//! the journal in parts, which is not taken here). There the submitting lane +//! waited 4.5-5.2 ms a frame for the heaps' records, and port 7 took 2.4 ms +//! off the lane. Here it waited 2.7-5.8 ms a frame (release run 233354). +//! +//! A round of the heap-sync thread (`crate::descriptor::sync_heaps`) is asked +//! for when the title submits ([`round_after`]), so it runs while the +//! submission waits in the line (12-15 submissions a frame are in it when one +//! is added), and the submitting thread waits for that round, or for a later +//! one if (a) a wait of its queue that was met in memory went since (the +//! queue's floor, `queue/behind.rs` `State::floors`) or (b) a step of ours +//! wrote, or may have written, a heap's title memory while preparing an +//! earlier submission ([`prep_wrote`]). A submission that waited for flights +//! to land begins a round of its own after the wait (`crate::host`). +//! +//! Why a submission's records are what they were: a round reads the title's +//! records as they are when it runs. The records a submission's lists use are +//! written by the title before its submit call, or, for a part behind a wait +//! for a memory value or a fence, before that wait is met. A round asked for +//! at the submit call (or, behind a wait, the first round to begin after the +//! line saw the wait met) begins after those writes: it sees all of them, as +//! the round begun at the preparing did. What changes: a record the title +//! writes for a submission after submitting it is left to a later round (the +//! console's card could miss it as well). + +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +/// Whether the switch is on. +pub(crate) fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_HEAP_SYNC_AT_SUBMIT")) +} + +/// With rounds `asked` asked for and `done` done (one runs at a time, in +/// order; round `k` begins only once `k - 1` is done and `k` has been asked +/// for): the number of a round that begins after now, and whether it has to +/// be asked for (it is `asked + 1` then). A round asked for and not begun +/// yet (`asked >= done + 2`: the one before it is not done) begins after +/// now; with `asked == done + 1` round `asked` may be running already. +pub(crate) fn round_after(asked: u64, done: u64) -> (u64, bool) { + if asked >= done + 2 { (asked, false) } else { (asked + 1, true) } +} + +thread_local! { + /// On the submitting thread: the round of the heaps' records the + /// submission being prepared needs (0: none known, a round is asked for + /// at the preparing, as without the switch). + static MARK: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The line is about to do a submission that needs round `mark`. +pub(crate) fn set_mark(mark: u64) { + MARK.set(mark); +} + +/// The round every submission prepared from now on needs at least: one that +/// began after a step of a submission being prepared wrote, or may have +/// written, title memory of a heap of descriptors ([`prep_wrote`]). +static PREP_FLOOR: AtomicU64 = AtomicU64::new(0); + +/// A step of the submission being prepared wrote, or may have written, title +/// memory of a heap of descriptors: every submission prepared after it waits +/// for a round begun after now. +pub(crate) fn prep_wrote() { + PREP_FLOOR.fetch_max(crate::descriptor::round_mark(), Relaxed); + STATS[PREP_WRITES].fetch_add(1, Relaxed); +} + +/// The round the submission about to be prepared needs (its mark, at least +/// [`PREP_FLOOR`]); 0 if none is known (or the switch is off). +pub(crate) fn needed() -> u64 { + if !on() { + return 0; + } + match MARK.get() { + 0 => { + STATS[NO_MARK].fetch_add(1, Relaxed); + 0 + } + m => m.max(PREP_FLOOR.load(Relaxed)), + } +} + +/// Since the last frame line: rounds asked for at a submit; submissions +/// that found their round asked earlier; preparings that wrote a heap's +/// memory (or may have); nanoseconds the submitting thread waited for the +/// heaps' records, and how many times; preparings with no mark; those whose +/// round had to be asked for at the preparing. +pub(crate) static STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; +pub(crate) const ROUNDS_ASKED: usize = 0; +pub(crate) const EARLY_ROUNDS: usize = 1; +const PREP_WRITES: usize = 2; +const HEAPS_NS: usize = 3; +const HEAPS: usize = 4; +const NO_MARK: usize = 5; +pub(crate) const LATE_ROUNDS: usize = 6; + +/// The submitting thread waited `ns` for the heaps' records. +pub(crate) fn heaps_waited(ns: u64) { + STATS[HEAPS_NS].fetch_add(ns, Relaxed); + STATS[HEAPS].fetch_add(1, Relaxed); +} + +/// The frame line's, per frame. +pub(crate) fn line(frames: f64) { + let s: [f64; 7] = std::array::from_fn(|i| STATS[i].swap(0, Relaxed) as f64); + if !on() { + return; + } + let f = frames.max(1.0); + tracing::info!( + "the heaps' records asked for at the title's submit, per frame (VICTORY_HEAP_SYNC_AT_SUBMIT=1): the submitting thread \ + waited {:.2} ms in {:.1} preparings; {:.1} rounds asked for at a submit, {:.1} preparings found theirs asked earlier, \ + {:.1} asked it at the preparing, {:.1} had no mark; {:.1} preparings wrote a heap's memory", + s[HEAPS_NS] / 1e6 / f, + s[HEAPS] / f, + s[ROUNDS_ASKED] / f, + s[EARLY_ROUNDS] / f, + s[LATE_ROUNDS] / f, + s[NO_MARK] / f, + s[PREP_WRITES] / f, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A round asked for and not begun is one that begins after now; one + /// that may be running is not. + #[test] + fn a_round_is_one_that_begins_after_now() { + // Nothing asked: ask for round 1. + assert_eq!(round_after(0, 0), (1, true)); + // Round 3 asked for, 2 done: 3 may be running, ask for 4. + assert_eq!(round_after(3, 2), (4, true)); + // Rounds up to 5 asked for, 2 done: 3 runs or waits, 5 cannot have + // begun. + assert_eq!(round_after(5, 2), (5, false)); + assert_eq!(round_after(4, 2), (4, false)); + // Everything done: ask anew. + assert_eq!(round_after(7, 7), (8, true)); + } + + /// A simulation of the rounds' thread: whatever the times of asking, + /// the round a caller is given begins after its call. + #[test] + fn the_round_given_begins_after_the_call() { + let (mut asked, mut done) = (0u64, 0u64); + // When each round began (in calls), and each caller's (call, round). + let mut began: std::collections::HashMap = Default::default(); + let mut given: Vec<(u64, u64)> = Vec::new(); + let mut running: Option = None; + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + for call in 1..5000u64 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + match seed % 3 { + 0 => { + let (round, ask) = round_after(asked, done); + if ask { + asked += 1; + } + given.push((call, round)); + } + 1 => { + if let Some(r) = running.take() { + done = r; + } + } + _ => { + if running.is_none() && asked > done { + running = Some(done + 1); + began.insert(done + 1, call); + } + } + } + } + for (call, round) in given { + if let Some(&at) = began.get(&round) { + assert!(at > call, "round {round} began at {at}, before the call at {call}"); + } + } + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 3a87b53..90590dc 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1282,6 +1282,10 @@ pub(crate) struct HostList { /// The copy of the colour without the interface (`crate::streamline`) /// recorded in the list, noted likewise; 0 for none. hudless: std::sync::atomic::AtomicU64, + /// Left open and empty, as made or reset, for the title's next reset + /// ([`HostList::leave_open`]): that reset finds nothing to undo. The + /// list's title calls and epoch then, each plus one (0: not left open). + left_open: [std::sync::atomic::AtomicU64; 2], /// Counts the list in [`ALIVE`] while it lives. _alive: Counted, /// The texts of the markers `note_op` set, in order (for device-removed @@ -1297,6 +1301,31 @@ pub(crate) struct HostList { /// A list's prelude: an allocator and a closed list. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList); +/// Whether the new host list each of the title's lists gets when it is +/// submitted is left open for the title's next reset ([`HostList::leave_open`]; +/// `VICTORY_FRESH_OPEN=0`: closed at once and reset again, as before). What +/// runs on the card is the same: those lists are empty either way. +fn fresh_open() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FRESH_OPEN").is_none_or(|v| v != "0")) +} + +/// Since the last frame line: host lists left open ([`fresh_open`]), the +/// title's resets that found one so and did nothing to it, and those closed +/// after all (submitted again without a reset, or recorded into before it). +static FRESH_OPEN: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// [`FRESH_OPEN`], for the frame-rate line. +fn fresh_open_line(frames: f64) { + let [open, kept, closed] = [0, 1, 2].map(|i| FRESH_OPEN[i].swap(0, Ordering::Relaxed) as f64 / frames); + if open + kept + closed > 0.0 { + tracing::info!( + "new host lists for the title's lists left open per frame (VICTORY_FRESH_OPEN=0: closed at once): {open:.1}, \ + {kept:.1} resets of the title found them so and had nothing to undo, {closed:.2} closed after all" + ); + } +} + /// Whether a host list's prelude is made when the list first needs one. A /// prelude runs the texture transitions and twin copies a list needs before /// it; lists that name no texture never have one, and every host list was @@ -3141,6 +3170,14 @@ fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc, usize, usize)>, +) -> Vec<(std::sync::Arc, usize, usize)> { if late_exact() { // The title's bytes are put in beside the flights' writes; a // settle is still due where that could not be done. At most this @@ -4231,6 +4268,7 @@ impl Host { holding: std::sync::atomic::AtomicBool::new(false), upscale: std::sync::atomic::AtomicU64::new(0), hudless: std::sync::atomic::AtomicU64::new(0), + left_open: [const { std::sync::atomic::AtomicU64::new(0) }; 2], _alive: Counted::new(), #[cfg(feature = "diagnostics")] notes, @@ -5306,6 +5344,7 @@ impl Host { crate::list::recycle(lists, &order); return; }; + let after = std::time::Instant::now(); let told = !sent.writes.is_empty(); let sizes = crate::memory::asked_sizes(order.iter().map(|&i| lists[i].host())); let most = { @@ -5350,6 +5389,7 @@ impl Host { drop(submitted); let _landing = crate::timeline::span("landed lists reset and given back"); land(); + AFTER_SEND.fetch_add(after.elapsed().as_nanos() as u64, Ordering::Relaxed); } /// Sends `list`, a closed list of ours (the present's copy), as a @@ -5596,7 +5636,6 @@ impl Host { /// ([`joins`]): those go to the queue in calls of their own, one after the /// other, as they would have. fn submit<'a>(&'a self, runs: &[&HostList], parts: &[usize], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> { - #[cfg(feature = "diagnostics")] let called = std::time::Instant::now(); #[cfg(feature = "diagnostics")] crate::copystat::submission_begins(); @@ -5618,9 +5657,13 @@ impl Host { } let was_working = working(true); submitting(1, runs.len()); - #[cfg(feature = "diagnostics")] + // The round of the heaps' records asked for when the title submitted + // these lists, if that is known (`crate::heap_marks`, 0: not). + let heaps_mark = if late { crate::heap_marks::needed() } else { 0 }; + // Else with [`heap_sync_first`]: the heaps' records begun now, beside + // the planning of steps done on the card and the look at flights. + let first_heaps = (late && heaps_mark == 0 && heap_sync_first()).then(crate::descriptor::begin_sync_heaps); let ahead = Split::begin(); - #[cfg(feature = "diagnostics")] SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed); stage.next("submit: steps given to the card"); // Flights in the air ([`late`]): a submission that is waited for @@ -5628,14 +5671,15 @@ impl Host { // what they write. // Or the reads are done on the card, behind the flights. let own = if late { self.card_steps(runs) } else { None }; - #[cfg(feature = "diagnostics")] ahead.part(12); stage.next("submit: waiting for flights it reads from"); + let mut waited_for_flights = false; if !late { self.settle(&mut submitted, WHY_SYNC); } else if own.is_none() && let Some(why) = late_blocked(runs) { + waited_for_flights = true; if relay_exact() && why == WHY_READ { // Only until the flights that may write what is read have // landed: their copy-back's end, not the card's other work. @@ -5646,11 +5690,30 @@ impl Host { self.settle(&mut submitted, why); } } - #[cfg(feature = "diagnostics")] ahead.part(13); // Descriptors the title copied into placed heaps directly, before - // command lists that index those slots are submitted. - let heaps_synced = crate::descriptor::begin_sync_heaps(); + // command lists that index those slots are submitted. (Begun first: + // again after a wait for flights, whose landings wrote title memory, + // as the round began here saw them; the first is not waited for.) + // With a mark (`crate::heap_marks`): that round, unless the + // submission waited for flights, whose landings came after it. + let heaps_synced = match first_heaps { + Some(first) if !waited_for_flights => { + HEAP_SYNC_FIRST[0].fetch_add(1, Ordering::Relaxed); + first + } + first => { + if let Some(first) = first { + HEAP_SYNC_FIRST[1].fetch_add(1, Ordering::Relaxed); + std::mem::forget(first); + } + if heaps_mark != 0 && !waited_for_flights { + crate::descriptor::begin_sync_heaps_after(heaps_mark) + } else { + crate::descriptor::begin_sync_heaps() + } + } + }; // That list runs first, and is one of the submission's from here on. let with: Vec<&HostList>; let runs = match &own { @@ -5693,7 +5756,6 @@ impl Host { // The ranges shaders write are counted for it (with the relay). crate::shadow::preparing(this_submission); let started = std::time::Instant::now(); - #[cfg(feature = "diagnostics")] ahead.part(14); #[cfg(feature = "diagnostics")] let lock = (started - called).as_micros() as u64; @@ -5702,8 +5764,7 @@ impl Host { let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); // Where each run's lists start in `lists`. let mut firsts = Vec::with_capacity(runs.len()); - let mut batch = Batch::default(); - #[cfg(feature = "diagnostics")] + let mut batch = Batch::reused(); let split = Split::begin(); // The time a settle of flights takes inside this preparing: the // wait for the card and the copy-back have their own places on the @@ -5712,25 +5773,13 @@ impl Host { // One write-watch asking for everything the submission refreshes // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges. if crate::watch::once() { - let mut spans: ByCopy<(usize, usize)> = ByCopy::default(); - for list in runs { - for step in &list.deferred().copies { - if let Step::Refresh(shadow, address, len) = step - && shadow.asked_ahead() - { - let span = spans - .entry(std::sync::Arc::as_ptr(shadow) as usize) - .or_insert((*address, *address + *len)); - *span = (span.0.min(*address), span.1.max(*address + *len)); - } - } - } - let ranges: Vec<(usize, usize)> = spans.into_values().collect(); - #[cfg(feature = "diagnostics")] + batch.copy_spans(runs); + let Batch { spans, ranges, .. } = &mut batch; + ranges.clear(); + ranges.extend(spans.iter().filter(|s| s.0.asked_ahead()).map(|s| (s.1, s.2))); SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed); stage.next("submit: asking the write watch"); - crate::watch::ask_once(&ranges); - #[cfg(feature = "diagnostics")] + crate::watch::ask_once(&batch.ranges); split.part(0); stage.next("submit: title bytes under flights' writes"); // Behind flights: the title wrote memory that a flight's shaders @@ -5743,10 +5792,10 @@ impl Host { upcheck::reads(runs); } } - let stale = if behind { stale_under_flights(runs) } else { Vec::new() }; + let stale = if behind { batch.stale_under_flights() } else { Vec::new() }; if !stale.is_empty() { let settling = std::time::Instant::now(); - self.settle_stale(&mut submitted, runs, stale, &ranges); + self.settle_stale(&mut submitted, runs, stale, &batch.ranges); settled += settling.elapsed(); } } else if behind && !stale_under_flights(runs).is_empty() { @@ -5754,7 +5803,6 @@ impl Host { self.settle(&mut submitted, WHY_STALE); settled += settling.elapsed(); } - #[cfg(feature = "diagnostics")] split.part(1); // What flights in the air may write. let air = line().written.clone(); @@ -5779,7 +5827,6 @@ impl Host { stage.next("submit: the last refreshes"); batch.flush(); crate::watch::ask_once_end(); - #[cfg(feature = "diagnostics")] split.part(2); stage.next("submit: snapshots"); // The snapshots of the ranges shaders may write, if they were left @@ -5792,7 +5839,6 @@ impl Host { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64); } - #[cfg(feature = "diagnostics")] split.part(3); stage.next("submit: copies in the card's memory"); // Copies in the card's memory: what changed on their CPU side goes @@ -5824,14 +5870,16 @@ impl Host { if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) { lists.push(Some(check)); } - #[cfg(feature = "diagnostics")] split.part(4); stage.next("submit: waiting for the heaps' records"); + let heaps_began = std::time::Instant::now(); drop(heaps_synced); + if crate::heap_marks::on() { + crate::heap_marks::heaps_waited(heaps_began.elapsed().as_nanos() as u64); + } // The slots that waited for a texture's host copy, before the // lists that may read them run. crate::descriptor::make_waiting(); - #[cfg(feature = "diagnostics")] split.part(15); let prepared = std::time::Instant::now(); stage.next("submit: sending"); @@ -5872,7 +5920,6 @@ impl Host { if let Err(e) = signalled { fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); } - #[cfg(feature = "diagnostics")] split.part(5); let back = crate::picked::with(declared, &picked.written); let mut texture_back_ranges = Vec::new(); @@ -5892,6 +5939,7 @@ impl Host { texture_back_ranges, writes, }; + batch.give_back(); working(was_working); return Some((submitted, sent)); } @@ -6041,6 +6089,7 @@ impl Host { if relay() { crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); } + batch.give_back(); working(was_working); None } @@ -6413,6 +6462,7 @@ impl HostList { pub(crate) fn close(&self) { let _closing = crate::timeline::span("closing a host list"); + self.left_open[0].store(0, Ordering::Release); self.flush_indirect(); self.twins_to_depth(); self.textures_back(); @@ -6462,9 +6512,61 @@ impl HostList { .splice(at..at, found.into_iter().map(|(shadow, from, to)| Step::Refresh(shadow, from as usize, (to - from) as usize))); } + /// A new host list for one of the title's lists (`crate::list::detach`), + /// open and empty as it was made or reset: left so, for the title's next + /// call on its list, a reset, which then has nothing to undo + /// ([`fresh_open`]); or closed now, as before. + /// + /// Each of the title's lists got a new host list at every submission, + /// closed at once on the submitting thread (an empty list's close, some + /// 5 us in the driver, 200 a frame) and reset again by the title's reset + /// (allocator and list) after the reset that made it ready for reuse. + pub(crate) fn leave_open(&self) { + if !fresh_open() { + self.close(); + return; + } + // (The marks first: a reset that sees the list left open sees them.) + self.left_open[1].store(self.epoch() + 1, Ordering::Relaxed); + self.left_open[0].store(self.title_calls() + 1, Ordering::Release); + FRESH_OPEN[0].fetch_add(1, Ordering::Relaxed); + } + + /// A host list taken from one of the title's lists to run + /// (`crate::list::detach`): closed first if it was left open + /// ([`HostList::leave_open`]), as it is when the title submits its list + /// again without a reset. + pub(crate) fn close_if_left_open(&self) { + if self.left_open[0].load(Ordering::Acquire) != 0 { + FRESH_OPEN[2].fetch_add(1, Ordering::Relaxed); + self.close(); + } + } + + /// Whether the list is as [`HostList::leave_open`] left it: nothing was + /// recorded into it since, as far as its title calls and its epoch say. + /// It is no longer marked so; one left open that something was recorded + /// into is closed here, for the reset that follows. + fn still_left_open(&self) -> bool { + let calls = self.left_open[0].swap(0, Ordering::AcqRel); + let epoch = self.left_open[1].swap(0, Ordering::Relaxed); + if calls == 0 { + return false; + } + if calls == self.title_calls() + 1 && epoch == self.epoch() + 1 { + return true; + } + FRESH_OPEN[2].fetch_add(1, Ordering::Relaxed); + // SAFETY: our list, open; what went into it goes with the reset. + let _ = unsafe { self.list.Close() }; + false + } + /// Only after the list's last submission finished (every one is waited /// for). pub(crate) fn reset(&self) { + // Before the epoch moves on below. + let left_open = self.still_left_open(); self.changed_something(); self.holding.store(false, Ordering::Relaxed); *self.indirect_run.lock().unwrap_or_else(|e| e.into_inner()) = None; @@ -6492,14 +6594,20 @@ impl HostList { give_chunks(std::mem::take(&mut scratch.chunks)); } } - // SAFETY: the list is not executing. - let reset = unsafe { - self.allocator - .Reset() - .and_then(|()| self.list.Reset(&self.allocator, None)) - }; - if let Err(e) = reset { - fail(format_args!("a host command list did not reset ({e})")); + // Open and empty since it was made or last reset: the allocator holds + // nothing, the list nothing recorded (`HostList::leave_open`). + if left_open { + FRESH_OPEN[1].fetch_add(1, Ordering::Relaxed); + } else { + // SAFETY: the list is not executing. + let reset = unsafe { + self.allocator + .Reset() + .and_then(|()| self.list.Reset(&self.allocator, None)) + }; + if let Err(e) = reset { + fail(format_args!("a host command list did not reset ({e})")); + } } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64); @@ -7617,6 +7725,11 @@ impl HostList { } batch.fill(); batch.title_written(); + // Into a heap's records: the rounds asked for earlier + // did not see it (`crate::heap_marks`). + if crate::heap_marks::on() && crate::descriptor::in_shader_heap(dst, len) { + crate::heap_marks::prep_wrote(); + } copy_mapped(dst as *mut u8, src as *const u8, len, true); // With the submission's one asking: the journal learns it. crate::watch::wrote(dst, len); @@ -7643,6 +7756,9 @@ impl HostList { } Step::Placed(p) => { let started = std::time::Instant::now(); + if crate::heap_marks::on() && crate::descriptor::in_shader_heap(p.dst, p.len) { + crate::heap_marks::prep_wrote(); + } let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len); batch.fill(); if free { @@ -7668,6 +7784,10 @@ impl HostList { let started = std::time::Instant::now(); if matches!(step, Step::Run(_)) { batch.title_written(); + // (It may write anywhere, a heap's records too.) + if crate::heap_marks::on() { + crate::heap_marks::prep_wrote(); + } } let _step = crate::timeline::span("a step of ours"); work(); @@ -7722,13 +7842,13 @@ impl HostList { } PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed); PREPARING[1].fetch_add(bytes, Ordering::Relaxed); + SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed); #[cfg(feature = "diagnostics")] { add(C::Copies, copies); add(C::CopyBytes, bytes); add(C::Refreshes, refreshes); add(C::RefreshBytes, refreshed); - SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed); } } } @@ -7779,20 +7899,49 @@ impl std::hash::Hasher for AddressHash { /// copy at a time: nanoseconds, and how many. Ahead of all that: the wait for /// the submission lock, the steps done on the card planned ([`card_steps`]), /// the flights waited for, the heaps' records and what is swept; and, at the -/// end, the wait for the heaps' records. -#[cfg(feature = "diagnostics")] +/// end, the wait for the heaps' records. In every build: some forty clock +/// reads a submission, for the frame line's split of the submitting thread +/// ([`submit_split_line`]). static SPLIT: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::AtomicU64::new(0) }; 16]; /// Since the last frame-rate line: flushes of refreshes, their refreshes, /// those known to copy nothing, and those done on several threads. -#[cfg(feature = "diagnostics")] static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; +/// Since the last frame-rate line, nanoseconds of the submitting thread +/// around its submissions ([`Host::send_late`]): after one is sent, its +/// flight noted in the line, what settled meanwhile and the landed lists +/// reset and given back. +static AFTER_SEND: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether a submission sent ahead begins the round of the heaps' records +/// (`crate::descriptor::begin_sync_heaps`) as soon as it holds the +/// submission lock, before the steps done on the card are planned and +/// flights are looked at (`VICTORY_HEAP_SYNC_FIRST=1`; off by default: after +/// them, as before). +/// +/// The submitting thread waited for those rounds at the end of its +/// preparing, 2.7-5.8 ms a frame in the release run 233354 ("ms waited for" +/// on the heaps' records line, 5% of its samples in profile-y-prof60), while +/// the planning ahead of the round's start took 2-4 ms a frame. What +/// changes: the round reads the heaps' pages earlier, by that planning's +/// time. A record the title writes for this submission after submitting it +/// (which the console's card could miss as well) is left to the next round; +/// a submission that waited for flights to land begins another round after +/// the wait, as the round began there saw what they landed. +fn heap_sync_first() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_HEAP_SYNC_FIRST")) +} + +/// Since the last frame line, with [`heap_sync_first`]: submissions whose +/// round of the heaps' records was begun first, and those that began +/// another after a wait for flights. +static HEAP_SYNC_FIRST: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + /// Counts into [`SPLIT`]. -#[cfg(feature = "diagnostics")] struct Split(std::cell::Cell); -#[cfg(feature = "diagnostics")] impl Split { fn begin() -> Split { Split(std::cell::Cell::new(std::time::Instant::now())) @@ -7810,22 +7959,27 @@ impl Split { } } -/// The split of the preparing, per frame, for the frame-rate line. -#[cfg(feature = "diagnostics")] -fn split_line(frames: f64) { - let ms: Vec = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); - let f: Vec = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); - let e: Vec = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect(); - let a: Vec = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect(); - let h: Vec = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); - let s: Vec = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect(); +/// The split of the submitting thread's work, per frame, for the frame-rate +/// line, in every build: what its submissions spent where (the parts add up +/// to the first number; refreshes and copies are inside the lists' steps), +/// and its time after each sending. +fn submit_split_line(frames: f64) { + let ms: [f64; 16] = std::array::from_fn(|i| SPLIT[i].swap(0, Ordering::Relaxed) as f64 / 1e6 / frames); + let f: [f64; 4] = std::array::from_fn(|i| FLUSHES[i].swap(0, Ordering::Relaxed) as f64 / frames); + let after = AFTER_SEND.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames; + let all: f64 = [0, 1, 2, 3, 4, 5, 11, 12, 13, 14, 15].iter().map(|&i| ms[i]).sum(); + if all + after <= 0.0 { + return; + } tracing::info!( - "preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \ - writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \ - several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \ - card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {}); ahead of these {:.1} waiting for the submission lock, {:.1} \ - planning steps done on the card, {:.1} waiting for flights, {:.1} the heaps' records and what is swept; at the end {:.1} waiting \ - for the heaps' records; asked early by a thread of its own {:.0} pieces of 2 MiB, {:.1} ms (VICTORY_ASK_EARLY)", + "preparing per frame, the submitting thread: {all:.1} ms in its submissions: {:.1} asking the write watch ({:.1} of them \ + finding what to ask), {:.1} putting the title's bytes under flights' writes, {:.1} in the lists' steps (refreshes {:.1} \ + in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on several threads, {:.1} one at a time in {:.0} \ + before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies \ + in the card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {}); ahead of these {:.1} waiting for the \ + submission lock, {:.1} planning steps done on the card, {:.1} waiting for flights, {:.1} the heaps' records and what is \ + swept; at the end {:.1} waiting for the heaps' records; after the sending {after:.1} (the flight noted, landed lists \ + reset and given back)", ms[0], ms[8], ms[1], @@ -7847,9 +8001,30 @@ fn split_line(frames: f64) { ms[13], ms[14], ms[15], - e[0], - e[1] / 1e3, ); + let [first, again] = [0, 1].map(|i| HEAP_SYNC_FIRST[i].swap(0, Ordering::Relaxed) as f64 / frames); + if first + again > 0.0 { + tracing::info!( + "the heaps' records begun as a submission took the lock, per frame (VICTORY_HEAP_SYNC_FIRST=1): {first:.1}, and \ + {again:.1} begun again after a wait for flights" + ); + } +} + +/// More of the preparing, per frame, for the frame-rate line (diagnostics). +#[cfg(feature = "diagnostics")] +fn split_line(frames: f64) { + let e: Vec = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect(); + let a: Vec = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect(); + let h: Vec = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); + let s: Vec = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect(); + if e[0] > 0.0 { + tracing::info!( + "asked early by a thread of its own per frame: {:.0} pieces of 2 MiB, {:.1} ms (VICTORY_ASK_EARLY)", + e[0], + e[1] / 1e3 + ); + } tracing::info!( "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \ written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \ @@ -7948,7 +8123,7 @@ struct Batch { index: ByCopy, /// Staging buffers (by address) refreshed since the last title write, /// or due to be. - textures: std::collections::HashSet, + textures: std::collections::HashSet>, /// Those due ([`Batch::refresh_textures`]). due: Vec>, /// What copies at their place in the submission's lists put into title @@ -7962,6 +8137,23 @@ struct Batch { /// `ahead` holds everything the submission refreshes /// ([`Batch::refresh_front`]). front: bool, + /// Per copy the submission refreshes, the span of all its refreshes, in + /// the order the copies first come ([`Batch::copy_spans`]); where each + /// copy (by address) is in it. + spans: Vec<(std::sync::Arc, usize, usize)>, + spans_at: ByCopy, + /// Room for the submission's one asking's ranges, and for + /// [`Batch::refresh_front`]'s walk over the steps. + ranges: Vec<(usize, usize)>, + touches: Vec, +} + +thread_local! { + /// The last submission's [`Batch`] on this thread, emptied, with the + /// room its tables and lists grew to: some 28 submissions a frame + /// each made them anew, grown from nothing (hash tables rehashed as + /// they grew, about 2% of the submitting thread in profile-y-prof60). + static SPARE_BATCH: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// Whether the copies that a submission's shaders write are brought up to @@ -8183,6 +8375,72 @@ fn wide_textures() -> bool { } impl Batch { + /// This thread's last one, emptied ([`SPARE_BATCH`]), or a new one. + fn reused() -> Batch { + SPARE_BATCH.take().unwrap_or_default() + } + + /// Emptied (the room kept) for the thread's next submission. + fn give_back(mut self) { + self.refreshes.clear(); + self.index.clear(); + self.textures.clear(); + self.due.clear(); + self.placed.clear(); + self.fills.clear(); + self.ahead.clear(); + self.front = false; + self.spans.clear(); + self.spans_at.clear(); + self.ranges.clear(); + self.touches.clear(); + SPARE_BATCH.set(Some(self)); + } + + /// Per copy that `runs` refresh, the span of all its refreshes, into + /// [`Batch::spans`]: the submission's one asking asks about those + /// ([`crate::watch::ask_once`]), and behind flights those of copies + /// shaders may be writing are looked at ([`Batch::stale_under_flights`]). + /// One walk over the steps for both, where there were two, each with a + /// table of its own. + fn copy_spans(&mut self, runs: &[&HostList]) { + self.spans.clear(); + self.spans_at.clear(); + // (Most come several times on end.) + let mut last = (0, 0); + for list in runs { + for step in &list.deferred().copies { + let Step::Refresh(shadow, address, len) = step else { + continue; + }; + let (from, to) = (*address, *address + *len); + let key = std::sync::Arc::as_ptr(shadow) as usize; + let at = if last.0 == key && key != 0 { + last.1 + } else { + match self.spans_at.entry(key) { + std::collections::hash_map::Entry::Occupied(at) => *at.get(), + std::collections::hash_map::Entry::Vacant(place) => { + place.insert(self.spans.len()); + self.spans.push((shadow.clone(), from, to)); + self.spans.len() - 1 + } + } + }; + last = (key, at); + let span = &mut self.spans[at]; + (span.1, span.2) = (span.1.min(from), span.2.max(to)); + } + } + } + + /// [`stale_under_flights`] of the submission's refreshes, from + /// [`Batch::copy_spans`]: the copies shaders may be writing now, in the + /// order they first come, with the span of all their refreshes. + fn stale_under_flights(&self) -> Vec<(std::sync::Arc, usize, usize)> { + stale_of(self.spans.iter().filter(|s| s.0.writes_pending()).cloned().collect()) + } + fn add(&mut self, shadow: &std::sync::Arc, address: usize, len: usize) { let end = address + len; let key = std::sync::Arc::as_ptr(shadow) as usize; @@ -8217,18 +8475,14 @@ impl Batch { if let Some(moved) = self.refreshes.get(at) { self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at); } - #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); if !(crate::watch::light() && shadow.nothing_new(from, to - from)) { Self::update(&shadow, from, to); } - #[cfg(feature = "diagnostics")] - { - let ns = started.elapsed().as_nanos() as u64; - SPLIT[6].fetch_add(ns, Ordering::Relaxed); - SPLIT[9].fetch_add(ns, Ordering::Relaxed); - SPLIT[10].fetch_add(1, Ordering::Relaxed); - } + let ns = started.elapsed().as_nanos() as u64; + SPLIT[6].fetch_add(ns, Ordering::Relaxed); + SPLIT[9].fetch_add(ns, Ordering::Relaxed); + SPLIT[10].fetch_add(1, Ordering::Relaxed); } /// Brings `[from, to)` of a copy up to date, timed. @@ -8260,25 +8514,23 @@ impl Batch { /// Before the steps of `runs` ([`refresh_front`]), a new part of the /// submission beginning at each of `parts`. fn refresh_front(&mut self, runs: &[&HostList], parts: &[usize]) { - let mut copies: ByCopy> = ByCopy::default(); + // The copies refreshed, by address: as the submission's one asking + // found them, or found here. + if self.spans.is_empty() { + self.copy_spans(runs); + } let mut due = Vec::new(); - let mut touches = Vec::new(); + self.touches.clear(); for (n, list) in runs.iter().enumerate() { if parts.contains(&n) { - touches.push(Touch::Part); + self.touches.push(Touch::Part); } - let mut last = 0; for step in &list.deferred().copies { match step { Step::Refresh(shadow, at, len) => { - let key = std::sync::Arc::as_ptr(shadow) as usize; - if key != last { - copies.entry(key).or_insert_with(|| shadow.clone()); - last = key; - } - touches.push(Touch::Refresh(key, *at, *at + *len)); + self.touches.push(Touch::Refresh(std::sync::Arc::as_ptr(shadow) as usize, *at, *at + *len)); } - Step::GpuWrite(shadow, ..) => touches.push(Touch::Write(std::sync::Arc::as_ptr(shadow) as usize)), + Step::GpuWrite(shadow, ..) => self.touches.push(Touch::Write(std::sync::Arc::as_ptr(shadow) as usize)), Step::Texture(staging) if wide_textures() => { if self.texture_due(staging) { due.push(staging.clone()); @@ -8288,19 +8540,17 @@ impl Batch { } } } - let spans: Vec<_> = front_spans(touches.into_iter()) + let found = front_spans(self.touches.drain(..)); + let spans: Vec<_> = found .into_iter() - .filter_map(|(key, from, to)| Some((copies.remove(&key)?, from, to))) + .filter_map(|(key, from, to)| Some((self.spans.get(*self.spans_at.get(&key)?)?.0.clone(), from, to))) .collect(); self.front = true; for (shadow, from, to) in &spans { self.ahead.insert(std::sync::Arc::as_ptr(shadow) as usize, (*from, *to)); } - #[cfg(feature = "diagnostics")] - { - FLUSHES[0].fetch_add(1, Ordering::Relaxed); - FLUSHES[1].fetch_add(spans.len() as u64, Ordering::Relaxed); - } + FLUSHES[0].fetch_add(1, Ordering::Relaxed); + FLUSHES[1].fetch_add(spans.len() as u64, Ordering::Relaxed); let _flush = crate::timeline::span("refreshes of copies"); let started = std::time::Instant::now(); let before = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed)); @@ -8310,10 +8560,8 @@ impl Batch { let mut spans = spans; let many = spans.len() > FEW; if !many { - #[cfg(feature = "diagnostics")] let all = spans.len(); spans.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); - #[cfg(feature = "diagnostics")] FLUSHES[2].fetch_add((all - spans.len()) as u64, Ordering::Relaxed); } let ahead = spans.len() > 1; @@ -8321,7 +8569,6 @@ impl Batch { let ranges: Vec<(usize, usize)> = spans.iter().filter(|r| r.0.asked_ahead()).map(|r| (r.1, r.2)).collect(); crate::watch::ask_ahead(&ranges); } - #[cfg(feature = "diagnostics")] FLUSHES[3].fetch_add(spans.len() as u64, Ordering::Relaxed); crate::shadow::wide_each(spans.len() + due.len(), move |i| { // The textures first: they are the longer pieces. @@ -8331,7 +8578,6 @@ impl Batch { }; let (shadow, from, to) = &spans[i]; if many && shadow.nothing_new(*from, *to - *from) { - #[cfg(feature = "diagnostics")] FLUSHES[2].fetch_add(1, Ordering::Relaxed); return; } @@ -8346,7 +8592,6 @@ impl Batch { PREPARING[2].fetch_sub(summed[1], Ordering::Relaxed); PREPARING[0].fetch_sub(summed[0], Ordering::Relaxed); PREPARING[0].fetch_add(took, Ordering::Relaxed); - #[cfg(feature = "diagnostics")] SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); } @@ -8377,8 +8622,6 @@ impl Batch { for (shadow, from, to) in &due { self.ahead.insert(std::sync::Arc::as_ptr(shadow) as usize, (*from, *to)); } - #[cfg(feature = "diagnostics")] - let began = std::time::Instant::now(); let started = std::time::Instant::now(); let before = PREPARING[0].load(Ordering::Relaxed); crate::shadow::wide_each(due.len(), move |i| { @@ -8390,12 +8633,9 @@ impl Batch { // The time counted is the time it took, not the threads' sum. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before); PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed); - #[cfg(feature = "diagnostics")] - { - let ns = began.elapsed().as_nanos() as u64; - SPLIT[6].fetch_add(ns, Ordering::Relaxed); - SPLIT[9].fetch_add(ns, Ordering::Relaxed); - } + let ns = started.elapsed().as_nanos() as u64; + SPLIT[6].fetch_add(ns, Ordering::Relaxed); + SPLIT[9].fetch_add(ns, Ordering::Relaxed); } /// The fills noted are done. @@ -8421,7 +8661,6 @@ impl Batch { } let took = started.elapsed(); PREPARING[0].fetch_add(took.as_micros() as u64, Ordering::Relaxed); - #[cfg(feature = "diagnostics")] SPLIT[7].fetch_add(took.as_nanos() as u64, Ordering::Relaxed); } @@ -8447,16 +8686,12 @@ impl Batch { if self.refreshes.is_empty() { return; } - #[cfg(feature = "diagnostics")] let (began, all) = (std::time::Instant::now(), self.refreshes.len()); let _flush = crate::timeline::span("refreshes of copies"); self.flush_all(); - #[cfg(feature = "diagnostics")] - { - SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed); - FLUSHES[0].fetch_add(1, Ordering::Relaxed); - FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed); - } + SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed); + FLUSHES[0].fetch_add(1, Ordering::Relaxed); + FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed); } fn flush_all(&mut self) { @@ -8468,11 +8703,9 @@ impl Batch { let light = crate::watch::light(); if light && self.refreshes.len() <= FEW { let started = std::time::Instant::now(); - #[cfg(feature = "diagnostics")] let all = self.refreshes.len(); self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); - #[cfg(feature = "diagnostics")] FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed); } // One write-watch asking for the copies that lie close together, @@ -8495,7 +8728,6 @@ impl Batch { // The time counted is the time it took, not the threads' sum. let started = std::time::Instant::now(); let before = PREPARING[0].load(Ordering::Relaxed); - #[cfg(feature = "diagnostics")] FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed); if light { // A number to a free thread, not a job to each copy. @@ -8503,7 +8735,6 @@ impl Batch { crate::shadow::wide_each(refreshes.len(), move |i| { let (shadow, from, to) = &refreshes[i]; if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) { - #[cfg(feature = "diagnostics")] FLUSHES[2].fetch_add(1, Ordering::Relaxed); return; } @@ -9087,6 +9318,9 @@ impl Meter { #[cfg(feature = "diagnostics")] spans::line(frames); crate::shadow::back_line(frames); + submit_split_line(frames); + fresh_open_line(frames); + crate::heap_marks::line(frames); #[cfg(feature = "diagnostics")] split_line(frames); { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 9cc7cf1..e678935 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -40,6 +40,8 @@ pub mod frame; #[cfg(all(windows, feature = "diagnostics"))] mod book; #[cfg(windows)] +mod heap_marks; +#[cfg(windows)] mod host; #[cfg(windows)] mod indirect; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 698b8b7..1d3f364 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -476,14 +476,16 @@ pub(crate) fn detach_parts(lists: &[This]) -> Parts { continue; }; // A new host list is open; the title's next call on its list is a - // reset, which wants it closed. - fresh.close(); + // reset, which finds it so (or wants it closed). + fresh.leave_open(); // SAFETY: one of our lists, closed and submitted: nothing records // into it until the title resets it. let list = unsafe { &mut *this.cast_mut().cast::() }; let Some(host) = list.host.replace(fresh) else { continue; }; + // (Submitted again without a reset: it runs closed, empty.) + host.close_if_left_open(); let earlier = std::mem::take(&mut list.earlier); let gate = std::mem::take(&mut list.gate); let uploads = std::mem::take(&mut *list.uploads.lock().unwrap_or_else(|e| e.into_inner())); @@ -548,8 +550,8 @@ pub(crate) fn detach(lists: &[This]) -> (Vec, Vec) { continue; }; // A new host list is open; the title's next call on its list is a - // reset, which wants it closed. - fresh.close(); + // reset, which finds it so (or wants it closed). + fresh.leave_open(); let list = this.cast_mut().cast::(); // SAFETY: one of our lists, closed and submitted: nothing records // into it until the title resets it. @@ -557,6 +559,8 @@ pub(crate) fn detach(lists: &[This]) -> (Vec, Vec) { let Some(host) = (*list).host.replace(fresh) else { continue; }; + // (Submitted again without a reset: it runs closed, empty.) + host.close_if_left_open(); let uploads = std::mem::take(&mut *(*list).uploads.lock().unwrap_or_else(|e| e.into_inner())); let state = diff --git a/crates/victory-gpu/src/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs index c9869ed..0d43ef1 100644 --- a/crates/victory-gpu/src/queue/behind.rs +++ b/crates/victory-gpu/src/queue/behind.rs @@ -84,12 +84,36 @@ pub(super) trait Work: Send { } /// Does it. `forced`: its wait was not met. fn go(self, forced: bool); + /// A mark taken when an entry that runs is put in the line (by the thread + /// that puts it, before the line's lock): the round of the heaps' records + /// begun after that (`crate::heap_marks`). 0: none. + fn mark_now() -> u64 { + 0 + } + /// A mark taken when a wait goes or is taken along (on our thread): a + /// round that begins after. + fn mark_later() -> u64 { + 0 + } + /// Whether what its queue has behind this wait may have been written + /// only just before the wait was met (by the CPU, which writes, then + /// meets the wait): it was met in memory. A wait met by a bottom-of-pipe + /// write of a flight or of the submission it is taken along with is the + /// card's order, not the CPU's. + fn raises(&self) -> bool { + true + } + /// Told just before [`Work::go`] of a submission: the highest mark of + /// what it is made of and of the waits its queue went past. + fn marked(&mut self, _mark: u64) {} } struct Entry { number: u64, queue: usize, what: W, + /// [`Work::mark_now`] when it was put in the line. + mark: u64, } struct State { @@ -107,6 +131,23 @@ struct State { /// Presents and submissions in the line or being done. presents: usize, runs: usize, + /// Per queue, the highest [`Work::mark_later`] of the waits it went past: + /// what is behind a wait may have been written only before the wait was + /// met, not before it was put in the line. + floors: Vec<(usize, u64)>, +} + +impl State { + fn floor(&self, queue: usize) -> u64 { + self.floors.iter().find(|f| f.0 == queue).map_or(0, |f| f.1) + } + + fn raise(&mut self, queue: usize, mark: u64) { + match self.floors.iter_mut().find(|f| f.0 == queue) { + Some(f) => f.1 = f.1.max(mark), + None => self.floors.push((queue, mark)), + } + } } /// See the module's text. @@ -129,6 +170,7 @@ impl Lane { served: 0, presents: 0, runs: 0, + floors: Vec::new(), }), work: Condvar::new(), moved: Condvar::new(), @@ -139,19 +181,21 @@ impl Lane { self.state.lock().unwrap_or_else(|e| e.into_inner()) } - fn put(state: &mut State, queue: usize, what: W) { + fn put(state: &mut State, queue: usize, what: W, mark: u64) { state.presents += usize::from(what.shows()); state.runs += usize::from(what.runs()); let number = state.next; state.next += 1; - state.items.push_back(Entry { number, queue, what }); + state.items.push_back(Entry { number, queue, what, mark }); } /// Adds to the end of the line, and has it looked at. pub(super) fn push(&self, queue: usize, what: impl IntoIterator) { + let what: Vec = what.into_iter().collect(); + let mark = if what.iter().any(W::runs) { W::mark_now() } else { 0 }; let mut state = self.lock(); for what in what { - Self::put(&mut state, queue, what); + Self::put(&mut state, queue, what, mark); } state.asked += 1; drop(state); @@ -164,7 +208,7 @@ impl Lane { pub(super) fn push_behind(&self, queue: usize, always: bool, what: W, now: impl FnOnce()) { let mut state = self.lock(); if always || state.running == Some(queue) || state.items.iter().any(|e| e.queue == queue) { - Self::put(&mut state, queue, what); + Self::put(&mut state, queue, what, 0); } else { now(); } @@ -255,12 +299,14 @@ impl Lane { /// The parts of `entry`, which stands for them, in place `at`. fn unfold(state: &mut State, at: usize, entry: Entry) { - let (number, queue, runs) = (entry.number, entry.queue, usize::from(entry.what.runs())); + let began = Instant::now(); + let (number, queue, runs, mark) = (entry.number, entry.queue, usize::from(entry.what.runs()), entry.mark); let parts = entry.what.unfold(); + STATS[UNFOLDING].fetch_add(began.elapsed().as_micros() as u64, Relaxed); state.runs -= runs; state.runs += parts.iter().filter(|p| p.runs()).count(); for (i, what) in parts.into_iter().enumerate() { - state.items.insert(at + i, Entry { number, queue, what }); + state.items.insert(at + i, Entry { number, queue, what, mark }); } } @@ -317,6 +363,14 @@ impl Lane { entry }; let (shows, mut runs) = (entry.what.shows(), usize::from(entry.what.runs())); + // The highest mark of what it is made of (`crate::heap_marks`). + let mut mark = entry.mark; + if entry.what.ask().is_some() && !entry.what.folded() && entry.what.raises() { + // A wait that goes: what its queue has behind it was written + // before it was met, which is now at the latest. + let later = W::mark_later(); + self.lock().raise(entry.queue, later); + } if entry.what.folded() { // Its parts take its place: behind everything before it, before // everything after it (they share its number; the first of them @@ -351,15 +405,27 @@ impl Lane { state.items.insert(at, next); break; } - let Entry { number, queue, what } = next; + let Entry { number, queue, what, mark: theirs } = next; + let waits = what.ask().is_some() && what.raises(); match entry.what.take_along(what) { - Ok(run) => runs += usize::from(run), + Ok(run) => { + runs += usize::from(run); + mark = mark.max(theirs); + if waits { + let later = W::mark_later(); + self.lock().raise(queue, later); + } + } Err(what) => { - self.lock().items.insert(at, Entry { number, queue, what }); + self.lock().items.insert(at, Entry { number, queue, what, mark: theirs }); break; } } } + if runs > 0 { + let floor = self.lock().floor(entry.queue); + entry.what.marked(mark.max(floor)); + } entry.what.go(forced); { let mut state = self.lock(); @@ -447,6 +513,31 @@ impl Work for Job { } } + fn mark_now() -> u64 { + if crate::heap_marks::on() { crate::descriptor::round_after_now() } else { 0 } + } + + fn mark_later() -> u64 { + // (Asked for now: the round runs while the line does what is before + // the part behind the wait.) + if crate::heap_marks::on() { crate::descriptor::round_after_now() } else { 0 } + } + + fn raises(&self) -> bool { + // (Without the switch no mark is taken: the memory is not read.) + if !crate::heap_marks::on() { + return true; + } + match self { + Job::Value(_, wait) => wait.met(), + _ => true, + } + } + + fn marked(&mut self, mark: u64) { + crate::heap_marks::set_mark(mark); + } + fn met(ask: &Ask) -> bool { match ask { &Ask::Wait(fence, value) => crate::fence::completed(fence as This) >= value, @@ -597,6 +688,8 @@ impl Work for Job { QUEUED.fetch_sub(1, Relaxed); } } + // (The mark was this submission's alone.) + crate::heap_marks::set_mark(0); STATS[BUSY].fetch_add(began.elapsed().as_micros() as u64, Relaxed); } } @@ -611,8 +704,9 @@ static QUEUED: AtomicU64 = AtomicU64::new(0); /// times they found things in it (the sum of their numbers) and the most; what /// threads of the title waited, in microseconds, for room in the line, at a /// present, and for a drain, and the drains; what our thread worked; waits -/// not met at a present. -static STATS: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11]; +/// not met at a present; parts joined; what our thread spent taking the +/// lists of submissions whose translation was done out of the line. +static STATS: [AtomicU64; 12] = [const { AtomicU64::new(0) }; 12]; const RUNS: usize = 0; const PRESENTS: usize = 1; const DEPTH: usize = 2; @@ -625,6 +719,9 @@ const BUSY: usize = 8; const FORCED: usize = 9; /// Parts prepared together with the one before them. const JOINED: usize = 10; +/// Microseconds of [`Lane::unfold`] (the lists detached, new host lists +/// given to the title's lists), under the line's lock and not in [`BUSY`]. +const UNFOLDING: usize = 11; /// How many submissions may be in the line when a submit call returns /// (`VICTORY_SUBMIT_DEPTH`; 64: about two frames of the title's). @@ -850,7 +947,8 @@ pub(super) fn line(frames: f64) { let ms = |i: usize| s[i] / 1000.0 / frames; tracing::info!( "submissions prepared by a thread of ours, per frame (VICTORY_ASYNC_SUBMIT): {:.1} in {:.1} presents, {:.1} in the line \ - when one was added (at most {:.0}); that thread worked {:.1} ms; threads of the title waited {:.1} ms for room in the \ + when one was added (at most {:.0}); that thread worked {:.1} ms, and {:.2} ms more taking translated lists out of the \ + line (under its lock); threads of the title waited {:.1} ms for room in the \ line, {:.1} ms at presents, {:.1} ms in {:.1} drains; waits not met at a present {:.2}; {:.1} of the \ submissions were prepared together with the one before them (VICTORY_JOIN_PARTS)", s[RUNS] / frames, @@ -858,6 +956,7 @@ pub(super) fn line(frames: f64) { s[DEPTH] / s[RUNS].max(1.0), s[DEEPEST], ms(BUSY), + ms(UNFOLDING), ms(ROOM), ms(AT_PRESENT), ms(DRAINING), @@ -948,10 +1047,73 @@ mod tests { } } } + fn mark_now() -> u64 { + NOW.get() + } + fn mark_later() -> u64 { + LATER.get() + } + fn marked(&mut self, mark: u64) { + let name = match self { + T::Run(name, _) | T::Slow(name, ..) => name.to_string(), + T::Group(names, ..) => names.join("+"), + _ => "?".into(), + }; + MARKS.with(|m| m.borrow_mut().push((name, mark))); + } } thread_local! { static FORCED_HERE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// What [`Work::mark_now`] and [`Work::mark_later`] give in a test. + static NOW: std::cell::Cell = const { std::cell::Cell::new(0) }; + static LATER: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The marks submissions were done with, by name. + static MARKS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + /// (Ported from Belobug/VIctory-Belobug-AMD 673be0e.) A submission is + /// done with the mark taken when it was put in the line, or, behind a + /// wait of its queue, at least the one taken when that wait went (what + /// is behind a wait may be written only before it is met); one taken + /// along with others, the highest of all. + #[test] + fn a_submission_needs_what_was_written_before_it_and_its_queues_waits() { + let lane = Lane::new(); + let log: Log = Default::default(); + let f = fence(); + let run = |name| T::Run(name, log.clone()); + NOW.set(5); + lane.push(1, [run("a")]); + NOW.set(6); + lane.push(1, [T::Wait(f, 1), run("b")]); + look(&lane); + assert_eq!(MARKS.take(), [("a".to_string(), 5)], "b stands at its wait"); + // The wait is met later; what b reads may have been written just + // before that. + LATER.set(9); + crate::fence::set(f as This, 1); + look(&lane); + assert_eq!(MARKS.take(), [("b".to_string(), 9)]); + // Another queue went past no wait; this one did, for good. + NOW.set(7); + lane.push(2, [run("c")]); + NOW.set(3); + lane.push(1, [run("d")]); + look(&lane); + assert_eq!(MARKS.take(), [("c".to_string(), 7), ("d".to_string(), 9)]); + // Taken along: a met wait between two parts raises them both. + let part = |name| T::Group(vec![name], log.clone(), Vec::new()); + NOW.set(10); + LATER.set(12); + lane.push(3, [part("x"), T::Wait(f, 1), part("y")]); + look(&lane); + assert_eq!(MARKS.take(), [("x+y".to_string(), 12)]); + // A present is no submission: it is told no mark. + lane.push(3, [T::Present("present", log.clone())]); + look(&lane); + assert!(MARKS.take().is_empty()); + assert_eq!(*log.lock().unwrap(), ["a", "b", "c", "d", "x+y", "present"]); } fn fence() -> usize { diff --git a/crates/victory-gpu/src/safecopy.rs b/crates/victory-gpu/src/safecopy.rs index 66bb68a..244e825 100644 --- a/crates/victory-gpu/src/safecopy.rs +++ b/crates/victory-gpu/src/safecopy.rs @@ -134,6 +134,43 @@ std::arch::global_asm!( "mov qword ptr [rax + 8], r11", "mov rax, r9", "ret", + ".globl victory_safe_changed", + ".globl victory_safe_changed_at", + ".globl victory_safe_changed_after", + ".globl victory_safe_changed_failed", + // rcx title memory, rdx what was last seen there, r8 records of 32 + // bytes, r9 a bit per record (zeroed by the caller): each record of + // title memory is read once; where it differs from the one last seen it + // goes over that one, and then its bit is set. eax: whether all could + // be read (where one could not, those before it are done). + "victory_safe_changed:", + "xor r10d, r10d", + "test r8, r8", + "jz 3f", + "2:", + "victory_safe_changed_at:", + "vmovdqu ymm0, ymmword ptr [rcx]", + "victory_safe_changed_after:", + "vpcmpeqb ymm1, ymm0, ymmword ptr [rdx]", + "vpmovmskb eax, ymm1", + "cmp eax, -1", + "je 4f", + "vmovdqu ymmword ptr [rdx], ymm0", + "bts qword ptr [r9], r10", + "4:", + "add rcx, 32", + "add rdx, 32", + "inc r10", + "cmp r10, r8", + "jb 2b", + "3:", + "vzeroupper", + "mov eax, 1", + "ret", + "victory_safe_changed_failed:", + "vzeroupper", + "xor eax, eax", + "ret", ); unsafe extern "system" { @@ -149,6 +186,27 @@ unsafe extern "system" { fn victory_safe_merge_at(); fn victory_safe_merge_after(); fn victory_safe_merge_failed(); + fn victory_safe_changed(title: *const u8, seen: *mut u8, records: usize, bits: *mut u64) -> u32; + fn victory_safe_changed_at(); + fn victory_safe_changed_after(); + fn victory_safe_changed_failed(); +} + +/// The records of 32 bytes at `title` (`records` of them) that differ from +/// those in `seen`: each is read once, goes over the one in `seen`, and gets +/// its bit in `bits` (record n: bit n % 64 of word n / 64). False if a page +/// of title memory could not be read: then the records before it are done, +/// and the others are as they were. +/// +/// # Safety +/// `seen` holds `records * 32` bytes of ours that nothing else reads or +/// writes meanwhile, and `bits` at least `records.div_ceil(64)` words, all +/// 0; `title` is as [`copy`]'s source. [`on`] must have been asked. +pub(crate) unsafe fn changed(title: *const u8, seen: *mut u8, records: usize, bits: &mut [u64]) -> bool { + assert!(bits.len() >= records.div_ceil(64)); + // SAFETY: a fault reading title memory leaves through the failing exit + // ([`failing_exit`]); the rest is the caller's. + unsafe { victory_safe_changed(title, seen, records, bits.as_mut_ptr()) != 0 } } /// What [`merge`] did. @@ -354,6 +412,10 @@ pub(crate) fn failing_exit(at: usize) -> Option { if (from..to).contains(&at) { return Some(victory_safe_put_failed as *const () as usize); } + let (from, to) = (victory_safe_changed_at as *const () as usize, victory_safe_changed_after as *const () as usize); + if (from..to).contains(&at) { + return Some(victory_safe_changed_failed as *const () as usize); + } let (from, to) = (victory_safe_merge_at as *const () as usize, victory_safe_merge_after as *const () as usize); (from..to).contains(&at).then_some(victory_safe_merge_failed as *const () as usize) } @@ -409,6 +471,47 @@ mod tests { } } + /// The records that differ get their bits and go over those last seen; + /// a page that is not there fails, with the records before it done. + #[test] + fn changed_records_are_found_and_taken() { + assert!(on()); + let pages = Pages::new(3 << 12); + pages.fill(); + let records: usize = (3 << 12) / 32; + // SAFETY: inside the allocation. + let title = unsafe { std::slice::from_raw_parts(pages.0, pages.1) }.to_vec(); + let mut seen = title.clone(); + let mut differ = Vec::new(); + for n in [0usize, 1, 63, 64, 65, 200, 383] { + seen[n * 32 + n % 32] ^= 0x11; + differ.push(n); + } + let mut bits = vec![0u64; records.div_ceil(64)]; + // SAFETY: inside the allocation; `seen` and `bits` are ours. + assert!(unsafe { changed(pages.0, seen.as_mut_ptr(), records, &mut bits) }); + let found: Vec = (0..records).filter(|n| bits[n / 64] >> (n % 64) & 1 != 0).collect(); + assert_eq!(found, differ); + assert_eq!(seen, title); + bits.fill(0); + // SAFETY: as above. + assert!(unsafe { changed(pages.0, seen.as_mut_ptr(), records, &mut bits) }); + assert!(bits.iter().all(|&b| b == 0)); + // The second page is not there: records 0 and 200 (on the third) differ. + for n in [0usize, 200] { + seen[n * 32] ^= 0x22; + } + // SAFETY: a page of our allocation. + unsafe { VirtualFree(pages.0.add(4096).cast(), 4096, MEM_DECOMMIT) }; + let mut bits = vec![0u64; records.div_ceil(64)]; + // SAFETY: as above; the page that is not there fails the call. + assert!(!unsafe { changed(pages.0, seen.as_mut_ptr(), records, &mut bits) }); + let found: Vec = (0..records).filter(|n| bits[n / 64] >> (n % 64) & 1 != 0).collect(); + assert_eq!(found, [0]); + assert_eq!(seen[..32], title[..32]); + assert_ne!(seen[200 * 32..201 * 32], title[200 * 32..201 * 32]); + } + /// The dwords that changed are stored, and no byte of any other, at /// every alignment and length; a page that is not there fails. #[test] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 5ba6ddd..cde6ec0 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1597,6 +1597,12 @@ fn wide(jobs: Vec) { } let workers = workers(); let _wide = crate::timeline::span("work spread over threads"); + // Helpers woken: one for each job beyond the one this thread takes + // first, at most all of them. All were woken for every call (4 for 2 + // jobs), and those that found nothing went back to sleep; a helper busy + // meanwhile looks at the queue before it sleeps again, and this thread + // takes what nobody took. + let wake = (jobs.len() - 1).min(wide_threads()); let left = Arc::new((Mutex::new(jobs.len()), std::sync::Condvar::new())); { let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); @@ -1613,7 +1619,11 @@ fn wide(jobs: Vec) { })); } } - workers.more.notify_all(); + if wake >= wide_threads() { + workers.more.notify_all(); + } else { + (0..wake).for_each(|_| workers.more.notify_one()); + } loop { let job = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()).pop_front(); match job {