diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 185e61fcb..27ad5b536 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -5667,6 +5667,20 @@ impl Host { let first_heaps = (late && heaps_mark == 0 && heap_sync_first()).then(crate::descriptor::begin_sync_heaps); let ahead = Split::begin(); SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed); + let mut batch = Batch::reused(); + // `VICTORY_ASK_FIRST`: the submission's one asking begun now, on a + // thread of its own, beside the planning and the look at flights + // below; it is waited for where it was made before. + let asked_first = (late && crate::watch::first() && !upcheck::on()).then(|| { + batch.copy_spans(runs); + let ranges: Vec<(usize, usize)> = batch.spans.iter().filter(|s| s.0.asked_ahead()).map(|s| (s.1, s.2)).collect(); + SPLIT[8].fetch_add(ahead.so_far(), Ordering::Relaxed); + let first = crate::watch::ask_first(ranges); + ahead.part(0); + first + }); + // Whether flights were settled for the sweep meanwhile. + let mut settled_for_sweep = false; stage.next("submit: steps given to the card"); // Flights in the air ([`late`]): a submission that is waited for // settles them first, one sent ahead only if preparing it reads @@ -5746,6 +5760,7 @@ impl Host { // With the present sent ahead nothing else brings a moment // with nothing in the air: one is made for the sweep. self.settle(&mut submitted, WHY_SYNC); + settled_for_sweep = true; if upcheck::on() { upcheck::at_rest(self); } @@ -5766,7 +5781,6 @@ 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::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 @@ -5781,7 +5795,24 @@ impl Host { 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(&batch.ranges); + match asked_first { + // Begun beside the first steps: waited for here. Made again, + // whole, if flights were waited for or settled since (what + // they landed is title memory written); else only what it + // does not hold is asked: the ranges of the list of steps + // done on the card, which was made after it. + Some(first) => { + first.wait(); + ASKED_FIRST[0].fetch_add(1, Ordering::Relaxed); + if waited_for_flights || settled_for_sweep { + ASKED_FIRST[1].fetch_add(1, Ordering::Relaxed); + crate::watch::ask_once(&batch.ranges); + } else if crate::watch::ask_more(&batch.ranges) { + ASKED_FIRST[2].fetch_add(1, Ordering::Relaxed); + } + } + None => 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 @@ -7943,6 +7974,12 @@ fn heap_sync_first() -> bool { /// another after a wait for flights. static HEAP_SYNC_FIRST: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// Since the last frame line, with `VICTORY_ASK_FIRST` (`crate::watch::first`): +/// submissions whose asking was begun beside their first steps; those that +/// made it again after flights were waited for or settled; and those that +/// asked for more where it was made before. +static ASKED_FIRST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + /// Counts into [`SPLIT`]. struct Split(std::cell::Cell); @@ -8006,6 +8043,13 @@ fn submit_split_line(frames: f64) { ms[14], ms[15], ); + let [begun, made_again, more] = [0, 1, 2].map(|i| ASKED_FIRST[i].swap(0, Ordering::Relaxed) as f64 / frames); + if begun > 0.0 { + tracing::info!( + "the submissions' asking begun beside their first steps, per frame (VICTORY_ASK_FIRST=1): {begun:.1}, {made_again:.1} \ + made again after flights were waited for, {more:.1} asked for more where it was made before" + ); + } 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!( diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 151de0903..c52145d21 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -549,6 +549,114 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { ask_rest(ranges); } +/// `VICTORY_ASK_FIRST=1` (off by default; with [`once`]): a submission's one +/// asking is begun as soon as the submission has the lock, on a thread kept +/// for it ([`ask_first`]), beside the planning of the steps done on the card +/// and the look at the flights in the air; the submission waits for it where +/// it asked before, and asks for more there if it has to ([`ask_more`]). +/// +/// Why: the asking is the kernel resetting the pages found written, 4 to 5 +/// ms a frame on the thread a frame waits for, and it reads nothing the +/// steps before it make (session 2026-11-28 00:45: 4.3 to 5.4 ms of asking, +/// 5.8 to 18.5 ms of planning ahead of it, a frame). +/// +/// What changes: the asking is made a few hundred microseconds earlier in +/// the submission. Memory the title's other threads write in that time is +/// seen by the next submission's asking, as what they write while the +/// refreshes run is today ([`once`]); what this submission's lists read was +/// written before they were submitted. What does not change: after a wait +/// for flights (what they landed is title memory written) the asking is made +/// again, whole, where it was made before; and the ranges of the list of +/// steps done on the card, which is made after the asking was begun, are +/// asked there. +pub(crate) fn first() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| once() && std::env::var_os("VICTORY_ASK_FIRST").is_some_and(|v| v == "1")) +} + +/// A submission's one asking, begun by [`ask_first`]: whether it is made. +pub(crate) struct AskedFirst(std::sync::Arc<(Mutex, Condvar)>); + +impl AskedFirst { + /// Until that asking is made (or has given up: [`ask_more`] finds out). + pub(crate) fn wait(self) { + let done = &*self.0; + let mut made = done.0.lock().unwrap_or_else(|e| e.into_inner()); + while !*made { + made = done.1.wait(made).unwrap_or_else(|e| e.into_inner()); + } + } +} + +/// [`ask_once`] of `ranges`, begun on the thread kept for it ([`first`]); +/// here and now if there is no such thread. +pub(crate) fn ask_first(ranges: Vec<(usize, usize)>) -> AskedFirst { + type Job = Box; + static THREAD: std::sync::OnceLock>>> = std::sync::OnceLock::new(); + let done = std::sync::Arc::new((Mutex::new(false), Condvar::new())); + let told = done.clone(); + let job: Job = Box::new(move || { + // (However it ends, the submission that waits goes on: where no + // asking stands it makes its own.) + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ask_once(&ranges))); + *told.0.lock().unwrap_or_else(|e| e.into_inner()) = true; + told.1.notify_all(); + }); + let thread = THREAD.get_or_init(|| { + let (send, jobs) = std::sync::mpsc::channel::(); + std::thread::Builder::new() + .name("victory-ask".into()) + .spawn(move || { + crate::cores::keep_on_fast_cores("victory-ask"); + // (The submitting thread waits for it.) + let mut priority = crate::cores::Priority::new(); + jobs.into_iter().for_each(|job| { + priority.keep(); + job() + }) + }) + .ok() + .map(|_| Mutex::new(send)) + }); + match thread { + Some(send) => { + if let Err(job) = send.lock().unwrap_or_else(|e| e.into_inner()).send(job) { + (job.0)(); + } + } + None => job(), + } + AskedFirst(done) +} + +/// After [`ask_first`] was waited for: asks about what of `ranges` the +/// asking that stands does not hold, and it stands on; all of them, as +/// [`ask_once`] does, if none stands (the first found nothing to hold, or +/// gave up). Whether anything was asked. +pub(crate) fn ask_more(ranges: &[(usize, usize)]) -> bool { + if !once() { + return false; + } + let held = { + let j = journal(); + j.kept.then(|| j.ahead.clone()) + }; + let Some(held) = held else { + ask_once(ranges); + return true; + }; + // (Outside the journal's lock: `published` has locks of its own.) + let all_held = ranges.iter().all(|&(start, end)| { + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + start >= end || published(start, end) || held.iter().any(|&(a, b)| a <= first && last <= b) + }); + if all_held { + return false; + } + ask_rest(ranges); + true +} + /// [`ask_once`] after its [`ask_ahead`]: what that left to `writes`, and the /// asking stands. fn ask_rest(ranges: &[(usize, usize)]) { @@ -3668,6 +3776,40 @@ mod tests { unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; } + /// An asking begun on the thread kept for it is made when it has been + /// waited for, and a range it did not hold is asked for afterwards. + /// (Other tests end the asking that stands at any time: what is looked at + /// here is what the askings noted, which stays.) + #[test] + fn an_asking_begun_first_is_made_and_more_is_asked_for() { + let fresh = || { + // SAFETY: a fresh write-watched allocation, freed at the end. + let p = unsafe { + VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + } as usize; + assert_ne!(p, 0); + p + }; + let (p, q) = (fresh(), fresh()); + // SAFETY: committed pages of ours. + unsafe { ((p + PAGE) as *mut u8).write_volatile(1) }; + ask_first(vec![(p, p + 4 * PAGE)]).wait(); + assert!(journal().written.contains_key(&(p / PAGE + 1)), "the first asking did not note the page written"); + // SAFETY: committed pages of ours. + unsafe { ((q + 2 * PAGE) as *mut u8).write_volatile(1) }; + assert!(ask_more(&[(p, p + 4 * PAGE), (q, q + 4 * PAGE)]), "a range nobody held was not asked about"); + assert!(journal().written.contains_key(&(q / PAGE + 2)), "the asking for more did not note the page written"); + ask_once_end(); + // An empty asking is waited for like any other. + ask_first(Vec::new()).wait(); + ask_once_end(); + // SAFETY: our allocations. + unsafe { + VirtualFree(p as *mut _, 0, MEM_RELEASE); + VirtualFree(q as *mut _, 0, MEM_RELEASE); + } + } + /// The runtime maps a view and then tells us; a copy's refresh on another /// thread can guard it in between. Told, it is the title's to write: a /// block left read-only and forgotten would be an access violation in