diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 3228e15..213a11a 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1161,6 +1161,13 @@ impl HostHeap { buffers.iter().copied().collect() } + /// Of [`HostHeap::buffer_slots`], those of one of `parts` parts: every + /// slot is in the same part each time. + pub(crate) fn buffer_slots_of(&self, part: u32, parts: u32) -> Vec { + let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); + buffers.iter().copied().filter(|slot| slot % parts == part).collect() + } + /// The title slots whose buffer view was written, or went, since the /// last call. pub(crate) fn buffer_changes(&self) -> Vec { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c2f61ce..52bf2e4 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -429,6 +429,126 @@ pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0); /// index ([`State::heap_buffers`]), and the microseconds they took. pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0); pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0); +/// Of the passes, nanoseconds since the last frame line: looking at slots, +/// the spans and refreshes of their copies, the texture side. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_SPLIT: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// Passes after which every buffer slot of the heap was looked at again. +const HEAP_ROUND: u64 = 16; + +/// Whether the slots looked at again for no write are a part of them at +/// every pass, each slot at every sixteenth (`VICTORY_HEAP_SPREAD=0`: all of +/// them at every sixteenth pass, as before). +/// +/// All at once was some 115 ms on a thread that records the frame, every +/// sixteenth frame (72,000 slots; run record-1: 11 ms a pass in the lines +/// without such a pass, 22 in those of ten frames with one). A slot is +/// looked at as often as before. +fn heap_spread() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SPREAD").is_none_or(|v| v != "0")) +} + +/// The host copy and range the buffer view of each of a heap's slots reads +/// ([`State::heap_buffers`]), by slot. +#[derive(Default)] +struct HeapRanges(Vec>); + +impl HeapRanges { + fn set(&mut self, slot: u32, range: Option<(T, u64, u64)>) { + let slot = slot as usize; + if range.is_none() && slot >= self.0.len() { + return; + } + if slot >= self.0.len() { + self.0.resize_with(slot + 1, || None); + } + self.0[slot] = range; + } + + /// Forgets the slots of one of `parts` parts + /// (`HostHeap::buffer_slots_of`). + fn forget_part(&mut self, part: u32, parts: u32) { + self.0.iter_mut().skip(part as usize).step_by(parts as usize).for_each(|r| *r = None); + } + + fn ranges(&self) -> impl Iterator { + self.0.iter().flatten() + } +} + +#[cfg(test)] +mod heap_range_tests { + use super::{HEAP_ROUND, HeapRanges}; + + /// Round by round every slot is looked at again once, whatever was + /// written between, and what a slot holds is what was found last. + #[test] + fn every_slot_is_looked_at_again_in_a_round() { + const SLOTS: u32 = 1000; + let mut ranges = HeapRanges(Vec::new()); + ranges.set(7, None); + assert_eq!(ranges.ranges().count(), 0); + for slot in (0..SLOTS).step_by(3) { + ranges.set(slot, Some(((), 0, 1))); + } + let parts = HEAP_ROUND as u32; + for pass in 1..=HEAP_ROUND { + let part = (pass % HEAP_ROUND) as u32; + ranges.forget_part(part, parts); + for slot in (0..SLOTS).step_by(3).filter(|slot| slot % parts == part) { + assert!(ranges.0[slot as usize].is_none(), "slot {slot} not forgotten"); + ranges.set(slot, Some(((), pass, pass))); + } + assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize); + } + assert!(ranges.ranges().all(|r| r.1 != 0), "a slot not looked at in a round"); + ranges.set(3, None); + assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize - 1); + } + + /// The spans of 4,400 copies from the ranges of 72,000 slots, as a pass + /// makes them, by slot and from the table they were in. Run with + /// `--ignored --nocapture`. + #[test] + #[ignore] + fn spans_of_a_pass() { + use std::collections::HashMap; + use std::sync::Arc; + let copies: Vec> = (0..4400).map(Arc::new).collect(); + let (mut table, mut slots) = (HashMap::new(), HeapRanges(Vec::new())); + for slot in 0..72_000u32 { + let copy = &copies[slot as usize * 7919 % 4400]; + table.insert(slot, (copy.clone(), u64::from(slot), u64::from(slot) + 64)); + slots.set(slot, Some((copy.clone(), u64::from(slot), u64::from(slot) + 64))); + } + fn join(ranges: &mut dyn Iterator, u64, u64)>) -> usize { + let mut spans: HashMap, u64, u64), S> = HashMap::default(); + for (copy, from, to) in ranges { + let span = spans.entry(Arc::as_ptr(copy) as usize).or_insert_with(|| (copy.clone(), *from, *to)); + span.1 = span.1.min(*from); + span.2 = span.2.max(*to); + } + spans.len() + } + let best = |f: &mut dyn FnMut() -> usize| { + (0..30) + .map(|_| { + let t = std::time::Instant::now(); + assert_eq!(f(), 4400); + t.elapsed().as_secs_f64() * 1e3 + }) + .fold(f64::MAX, f64::min) + }; + println!( + "{:.2} ms from the table, {:.2} ms by slot", + best(&mut || join::(&mut table.values())), + best(&mut || join::>(&mut slots.ranges())), + ); + } +} + /// Textures brought up to date for shaders that pick them by index /// ([`State::heap_textures`]), the bytes of their memory, and the slots /// still waiting. @@ -1449,18 +1569,25 @@ impl State { // at best); all of them every 16 passes, because a view of a // released resource goes stale without a write, and a slot written // before its memory had a host copy is only made then. - type Ranges = std::collections::HashMap, u64, u64)>; + type Ranges = HeapRanges>; static RANGES: std::sync::Mutex>> = std::sync::Mutex::new(None); let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); let (passes, ranges) = kept .get_or_insert_with(Default::default) .entry(std::ptr::from_ref(host) as usize) - .or_insert_with(|| (0, Ranges::new())); + .or_insert_with(|| (0, HeapRanges(Vec::new()))); let changed = host.buffer_changes(); - let slots = if *passes % 16 == 0 { - ranges.clear(); + let slots = if *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()) { + ranges.0.clear(); host.buffer_slots() + } else if heap_spread() { + // The written ones, and this pass's part of the others. + let (part, parts) = ((*passes % HEAP_ROUND) as u32, HEAP_ROUND as u32); + ranges.forget_part(part, parts); + let mut slots = host.buffer_slots_of(part, parts); + slots.extend(changed); + slots } else { changed }; @@ -1470,7 +1597,7 @@ impl State { static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); for (n, &index) in slots.iter().enumerate() { - ranges.remove(&index); + ranges.set(index, None); let Some(handle) = heap.handle(index) else { continue; }; @@ -1501,13 +1628,15 @@ impl State { if host.shows(index, &shadow.buffer) == Some(false) { HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); } - ranges.insert(index, (shadow, address, address + len)); + ranges.set(index, Some((shadow, address, address + len))); } - let views = ranges.len() as u32; + #[cfg(feature = "diagnostics")] + let looked = std::time::Instant::now(); // Per host copy, the span its picked views cover. - let mut spans: std::collections::HashMap, u64, u64)> = - std::collections::HashMap::new(); - for (shadow, from, to) in ranges.values() { + let mut spans: crate::host::ByCopy<(std::sync::Arc, u64, u64)> = Default::default(); + let mut views = 0u32; + for (shadow, from, to) in ranges.ranges() { + views += 1; let key = std::sync::Arc::as_ptr(shadow) as usize; let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to)); span.1 = span.1.min(*from); @@ -1547,7 +1676,13 @@ impl State { } shadow.refresh(list, *from, to - from); } + #[cfg(feature = "diagnostics")] + let refreshed = std::time::Instant::now(); self.heap_textures(list, heap, host); + #[cfg(feature = "diagnostics")] + for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked, refreshed.elapsed()]) { + sum.fetch_add(time.as_nanos() as u64, Ordering::Relaxed); + } HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); static LOGGED: AtomicU64 = AtomicU64::new(0); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index c2f4faa..eeeae77 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4572,6 +4572,8 @@ impl Host { // 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 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 // frame line (run 92 showed them twice, "preparing" 250 ms for 135). @@ -4579,7 +4581,7 @@ 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: std::collections::HashMap = std::collections::HashMap::new(); + 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 @@ -4594,6 +4596,8 @@ impl Host { } let ranges: Vec<(usize, usize)> = spans.into_values().collect(); crate::watch::ask_once(&ranges); + #[cfg(feature = "diagnostics")] + split.part(0); // Behind flights: the title wrote memory that a flight's shaders // may write too, and this submission refreshes it. The flights // are settled, and the asking made again: the copy-back wrote @@ -4609,6 +4613,8 @@ impl Host { self.settle(&mut submitted, WHY_STALE); settled += settling.elapsed(); } + #[cfg(feature = "diagnostics")] + split.part(1); for list in runs { list.run_deferred(&mut batch, |i| own.as_ref().is_some_and(|own| own.takes(list, i))); firsts.push(lists.len()); @@ -4619,6 +4625,8 @@ impl Host { } batch.flush(); crate::watch::ask_once_end(); + #[cfg(feature = "diagnostics")] + split.part(2); // The snapshots of the ranges shaders may write, if they were left // for now (`crate::shadow::wide_back`): the refreshes are done, the // lists have not gone to the card. @@ -4629,6 +4637,8 @@ impl Host { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64); } + #[cfg(feature = "diagnostics")] + split.part(3); // Copies in the card's memory: what changed on their CPU side goes // up ahead of the lists, and a compare of what the shaders may // write follows them in the same submission. @@ -4642,6 +4652,8 @@ 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); let prepared = std::time::Instant::now(); if late { *submitted += 1; @@ -4654,6 +4666,8 @@ 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 = declared_writes(runs); let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed); @@ -5931,43 +5945,49 @@ impl HostList { fn run_deferred(&self, batch: &mut Batch, taken: impl Fn(usize) -> bool) { #[cfg(feature = "diagnostics")] use crate::copystat::{C, add}; + // The time and the bytes of the copies and fills, some 13,000 a + // frame between 20,000 refreshes: summed here and added once. + let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64); + #[cfg(feature = "diagnostics")] + let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64); for (i, step) in self.deferred().copies.iter().enumerate() { if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) { continue; } - let started = std::time::Instant::now(); - let copied = match step { + let (started, copied) = match step { &Step::Copy(dst, src, len) => { + let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] { - add(C::Copies, 1); - add(C::CopyBytes, len as u64); + copies += 1; } batch.title_written(); 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); - len + (started, len) } &Step::Fill(dst, src, len, _) => { + let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] { - add(C::Copies, 1); - add(C::CopyBytes, len as u64); + copies += 1; } copy_mapped(dst as *mut u8, src as *const u8, len, false); - len + (started, len) } Step::Refresh(shadow, address, len) => { #[cfg(feature = "diagnostics")] { - add(C::Refreshes, 1); - add(C::RefreshBytes, *len as u64); + refreshes += 1; + refreshed += *len as u64; } batch.add(shadow, *address, *len); continue; } Step::Run(work) | Step::Host(work, _) => { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); if matches!(step, Step::Run(_)) { batch.title_written(); } @@ -6008,12 +6028,130 @@ impl HostList { continue; } }; - PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); - PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + us += started.elapsed(); + bytes += copied as u64; + } + PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed); + PREPARING[1].fetch_add(bytes, 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); } } } +/// A table by a copy's address. +pub(crate) type ByCopy = std::collections::HashMap>; + +/// A hash for addresses of ours: the bits that tell them apart, spread. The +/// tables it serves are asked 40,000 times a frame, and hold no one's keys +/// but our own. +#[derive(Default)] +pub(crate) struct AddressHash(u64); + +impl std::hash::Hasher for AddressHash { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.write_usize(usize::from(b)); + } + } + fn write_usize(&mut self, n: usize) { + let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); + self.0 = h ^ (h >> 32); + } +} + +/// Since the last frame-rate line, nanoseconds of the submitting thread's +/// preparing: the write-watch asking for a submission; the title's bytes put +/// in under flights' writes; the lists' steps, the refreshes among them; the +/// snapshots; what goes to copies in the card's memory; the lists sent; and +/// of the steps: the refreshes, and the copies and fills (those with the +/// refreshes a copy of title memory flushes). +#[cfg(feature = "diagnostics")] +static SPLIT: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; + +/// 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]; + +/// 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())) + } + + /// What came since the last part was part `i`. + fn part(&self, i: usize) { + let now = std::time::Instant::now(); + SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed); + } +} + +/// 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 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 / (1 << 20) as f64 / frames).collect(); + tracing::info!( + "preparing per frame, the submitting thread: {:.1} ms asking the write watch, {:.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; 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 {})", + ms[0], + ms[1], + ms[2], + ms[6], + f[0], + f[1], + f[2], + f[3], + ms[7], + ms[3], + ms[4], + ms[5], + if crate::watch::light() { "on" } else { "off" }, + ); + tracing::info!( + "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB; view ranges: {:.0} answered by their \ + bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \ + waiting for the guards, {:.1} ms changing protections; pages taken again for the card: {:.1} MB compared, {:.1} MB of them \ + as they were, {:.1} MB to go up (VICTORY_SEND_CHANGED)", + a[0], + a[1] / 1024.0, + a[2], + a[3], + a[4], + a[5], + a[6], + a[7] / 1e6, + a[8] / 1e6, + s[0], + s[1], + s[2], + ); + tracing::info!( + "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures", + h[0], + h[1], + h[2], + ); +} + /// Whether a submission's refreshes of host copies run on several threads, /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it). /// @@ -6075,7 +6213,7 @@ struct Batch { /// the heap's buffers ready adds some 4,100 copies, and searching them /// for every refresh of a submission was tens of millions of /// comparisons a frame. - index: std::collections::HashMap, + index: ByCopy, /// Staging buffers (by address) refreshed since the last title write. textures: std::collections::HashSet, } @@ -6107,7 +6245,13 @@ impl Batch { if let Some(moved) = self.refreshes.get(at) { self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at); } - Self::update(&shadow, from, to); + #[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")] + SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); } /// Brings `[from, to)` of a copy up to date, timed. @@ -6136,6 +6280,36 @@ impl Batch { fn flush(&mut self) { self.index.clear(); + if self.refreshes.is_empty() { + return; + } + #[cfg(feature = "diagnostics")] + let (began, all) = (std::time::Instant::now(), self.refreshes.len()); + 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); + } + } + + fn flush_all(&mut self) { + // Most of a flush's copies are as they were: they are told so here, + // from what the submission's asking found, before anything is asked + // and any thread woken. (Thousands of them, the heap's buffer views + // once a frame: on the threads, below.) + const FEW: usize = 256; + 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, // not one per copy. let ahead = self.refreshes.len() > 1; @@ -6156,12 +6330,28 @@ 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); - let jobs: Vec> = self - .refreshes - .drain(..) - .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box) - .collect(); - crate::shadow::wide_run(jobs); + #[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. + let refreshes = std::mem::take(&mut self.refreshes); + 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; + } + Self::update(shadow, *from, *to); + }); + } else { + let jobs: Vec> = self + .refreshes + .drain(..) + .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box) + .collect(); + crate::shadow::wide_run(jobs); + } 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); } else { @@ -6579,6 +6769,8 @@ impl Meter { late_line(frames); card_clock_line(frames, ms); crate::shadow::back_line(frames); + #[cfg(feature = "diagnostics")] + split_line(frames); { let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); if passes + compares > 0.0 { @@ -7389,6 +7581,547 @@ mod spare { } } +#[cfg(test)] +mod refresh_tests { + use super::Batch; + use crate::shadow::Shadow; + use std::sync::Arc; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE, + VirtualAlloc, + }; + + const PAGE: usize = 64 << 10; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + /// Title memory for the tests (never given back: copies of it stay in + /// the guards): write-watched, or a view of a section. + fn title(len: usize, view: bool) -> usize { + // SAFETY: plain allocations. + let at = unsafe { + if view { + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null()); + let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize; + // As the runtime tells of it. + crate::title_memory_section(section as usize, len as u64, true); + crate::title_memory_remapped(at, len); + crate::title_memory_view(at, len, section as usize, 0); + at + } else { + VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize + } + }; + assert_ne!(at, 0); + at + } + + fn memory(len: usize) -> *mut u8 { + // SAFETY: a plain allocation. + unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() } + } + + struct Random(u64); + + impl Random { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 >> 11) as usize % n + } + } + + /// Prepares as a submission does: one asking for all the ranges, the + /// refreshes in several flushes, the asking's end. + fn submission(ranges: &[(Arc, usize, usize)], flushes: usize) { + // One at a time, as submissions are. + static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect(); + crate::watch::ask_once(&asked); + let mut batch = Batch::default(); + for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) { + for (shadow, at, len) in part { + batch.add(shadow, *at, *len); + } + batch.flush(); + } + crate::watch::ask_once_end(); + } + + /// Whatever is written where, by the title or by us, and whichever + /// copies (of both kinds of memory, over one another, none on a page + /// line) are refreshed in which ranges: a refreshed range holds what + /// title memory holds. + #[test] + fn refreshed_ranges_hold_title_memory() { + // SAFETY (all blocks): title memory and copies of the test's own, + // written by this thread and, in `Batch::flush`, by the threads that + // refresh, which are done when it returns. + let mut random = Random(0x1234_5678_9ABC_DEF1); + const LEN: usize = 24 * PAGE; + let regions = [title(LEN, false), title(LEN, true)]; + let mut copies = Vec::new(); + for ®ion in ®ions { + for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] { + let data = memory(to - from); + copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data)); + } + } + let byte = |at: usize| unsafe { (at as *const u8).read_volatile() }; + for round in 0..600 { + for _ in 0..random.below(4) { + let at = regions[random.below(2)] + random.below(LEN - 64); + let n = 1 + random.below(60); + if random.below(3) == 0 { + // What shaders wrote. + let was: Vec = (0..n).map(|i| byte(at + i)).collect(); + let now: Vec = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect(); + Shadow::put(at, &was, &now); + assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put"); + continue; + } + for i in 0..n { + unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) }; + } + } + let mut ranges = Vec::new(); + for (shadow, _) in &copies { + if random.below(3) == 0 { + continue; + } + let (start, len) = shadow.span(); + let (start, len) = (start as usize, len as usize); + // Often the range of the time before, as a list's is. + let from = if random.below(2) == 0 { 0 } else { random.below(len) }; + let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) }; + ranges.push((shadow.clone(), start + from, n)); + } + if ranges.is_empty() { + continue; + } + let flushes = 1 + random.below(3); + submission(&ranges, flushes); + for (shadow, at, n) in &ranges { + let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1; + let start = shadow.span().0 as usize; + let same = unsafe { + std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n) + }; + assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at)); + } + } + } + + /// A copy in the card's memory, with the card's side and the sends to it + /// played by the test. + struct Carded { + shadow: Arc, + data: usize, + start: usize, + len: usize, + /// The last send, the last send every fetch to come is behind, and + /// the card's bytes: the queue's order is the order it is locked in. + card: std::sync::Mutex<(u64, u64, Vec)>, + /// Whether a flight that writes it has not landed. + flying: std::sync::atomic::AtomicBool, + /// The dword of each eight its shaders write. + class: usize, + } + + impl Carded { + fn new(start: usize, len: usize, class: usize) -> Carded { + let data = memory(len); + Carded { + shadow: Shadow::unbacked(start as u64, data, len as u64, true), + data: data as usize, + start, + len, + card: std::sync::Mutex::new((0, 0, vec![0; len])), + flying: std::sync::atomic::AtomicBool::new(false), + class, + } + } + + /// What changed on the CPU's side goes up. + fn send(&self) { + let mut card = self.card.lock().unwrap(); + card.0 += 1; + let (number, merged) = (card.0, card.1); + for (a, b) in self.shadow.send_up(number, merged) { + // SAFETY: the copy's bytes; nothing writes those that are to + // go up. + unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) }; + } + } + } + + /// Everything at once: the title writes its memory on two threads, the + /// submitting thread puts its bytes in under shader writes + /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in + /// the card's memory, one not), sends up what changed and declares what + /// the next flight's shaders write, and what flights wrote is landed + /// meanwhile (`crate::land`, beside the guards). When all of it stands + /// still and the copies are refreshed once more, each of them, and the + /// card's side of those that have one, hold what title memory holds, and + /// title memory what was written last. + /// + /// (It fails in the first rounds if `landed_beside` notes nothing, or + /// only takes the block out of the guards' clean ones and leaves its bit, + /// or if a fault leaves the bit; in some thousand rounds, + /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.) + #[test] + fn landings_title_writes_and_light_refreshes_at_once() { + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + assert!(crate::safecopy::on()); + const LEN: usize = 24 * PAGE; + let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(400); + let region = title(LEN, true); + let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) }; + let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)]; + let plain = { + let (start, len) = (region + 700, LEN - 9000); + let data = memory(len); + (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize) + }; + let stop = AtomicBool::new(false); + // Also when an assertion fails on one of the threads. + struct Stop<'a>(&'a AtomicBool); + impl Drop for Stop<'_> { + fn drop(&mut self) { + self.0.store(true, Ordering::Relaxed); + } + } + // Held shared by who writes title memory, alone while it is looked at. + let still = std::sync::RwLock::new(()); + let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>(); + std::thread::scope(|s| { + for t in 0..2usize { + let (stop, still) = (&stop, &still); + s.spawn(move || { + let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111); + let mut value = 0u32; + while !stop.load(Ordering::Relaxed) { + { + let _moving = still.read().unwrap(); + for _ in 0..3 { + value += 1; + // Of each eight dwords, one a thread. + let at = random.below(LEN / 32) * 32 + 4 * (1 + t); + dword(at).store(value, Ordering::Relaxed); + } + } + std::thread::sleep(std::time::Duration::from_micros(20)); + } + }); + } + // Lands flights. + { + let (carded, stop) = (&carded, &stop); + s.spawn(move || { + let _stop = Stop(stop); + while let Ok((which, ranges, value)) = flights.recv() { + let c = &carded[which]; + // Fetched: the card's bytes, behind every send so far. + let (after, now) = { + let card = c.card.lock().unwrap(); + (card.0, card.2.clone()) + }; + // By piece: 64 KiB of title memory. + let mut pieces = Vec::new(); + for &(from, to) in &ranges { + let mut at = from; + while at < to { + let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to); + pieces.push((at, next, now.as_ptr() as usize + at)); + at = next; + } + } + let parts: Vec<_> = pieces.chunks(3).collect(); + crate::land::each(parts.len(), &|i| { + let mut notes = crate::land::Notes::default(); + // SAFETY: the bytes of `now`; each piece once. + unsafe { c.shadow.land_card(parts[i], after, &mut notes) }; + notes.flush(); + }); + for &(from, to) in &ranges { + for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) { + // (The next fetch may have brought more.) + assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed"); + } + } + let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect(); + c.shadow.copy_back_done(&done); + c.card.lock().unwrap().1 = after; + c.flying.store(false, Ordering::Release); + } + }); + } + let _stop = Stop(&stop); + let mut random = Random(0xABCD_EF01_2345_6789); + let check = |round: usize, random: &mut Random, quiet: bool| { + for c in &carded { + if c.shadow.writes_pending() { + let mut runs = usize::MAX; + assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}"); + } + } + let mut ranges = Vec::new(); + for (shadow, start, len) in + carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)]) + { + // All of it, or a part; often the same part. + let (from, n) = match random.below(3) { + _ if quiet => (0, len), + 0 => (0, len), + 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4), + _ => { + let from = random.below(len / 4) * 4; + (from, (4 + random.below((len - from) / 4) * 4).min(len - from)) + } + }; + ranges.push((shadow.clone(), start + from, n)); + } + submission(&ranges, 1 + random.below(3)); + carded.iter().for_each(Carded::send); + }; + let mut value = 1u32; + for round in 0..rounds { + check(round, &mut random, false); + // The flight of this submission: its shaders' writes. + for (which, c) in carded.iter().enumerate() { + if c.flying.swap(true, Ordering::Acquire) { + continue; + } + value += 1; + let mut ranges: Vec<(usize, usize)> = Vec::new(); + let first = random.below(6) * PAGE / 2; + for k in 0..2 { + let from = first + k * 9 * PAGE + 4 * random.below(9000); + let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len); + if from < to { + ranges.push((from, to)); + } + } + for &(from, to) in &ranges { + c.shadow.writing(c.start + from, to - from); + } + { + let mut card = c.card.lock().unwrap(); + for &(from, to) in &ranges { + for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) { + card.2[at..at + 4].copy_from_slice(&value.to_le_bytes()); + } + } + } + fly.send((which, ranges, value)).unwrap(); + } + if round % 20 != 19 { + continue; + } + // Still: no flight in the air, no title write. + let _still = still.write().unwrap(); + while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) { + assert!(!stop.load(Ordering::Relaxed), "the landing thread failed"); + std::thread::yield_now(); + } + check(round, &mut random, true); + // SAFETY: the test's own memory, written by nobody now. + let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) }; + let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y); + for c in &carded { + let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len)); + assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class); + let card = c.card.lock().unwrap(); + assert_eq!(first(&card.2, there), None, "round {round}: a card copy's card side (class {})", c.class); + } + assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy"); + } + drop(fly); + }); + } + + /// A range nothing wrote is known to be as it was, at its ends too, and + /// is so no more once something wrote it. + #[test] + fn unchanged_ranges_are_known() { + for view in [false, true] { + let region = title(8 * PAGE, view); + // (A page read for the first time counts as written.) + // SAFETY: the test's own memory. + unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) }; + let data = memory(8 * PAGE); + let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false); + // Ends in the middle of pages. + let (at, len) = (region + 500, 5 * PAGE); + let look = |expected: bool, what: &str| { + // The submission's one asking, which takes two ranges. (Again + // if a submission of another test ended it.) + let mut known = false; + for _ in 0..100 { + crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]); + known = copy.nothing_new(at, len); + if known || !expected { + break; + } + } + assert_eq!(known, expected, "view {view}: {what}"); + let copied = copy.update(at, len); + crate::watch::ask_once_end(); + copied + }; + assert_eq!(look(false, "never taken"), len); + assert_eq!(look(true, "taken"), 0); + assert_eq!(look(true, "taken"), 0); + // SAFETY: the test's own memory. + unsafe { ((region + 600) as *mut u8).write_volatile(1) }; + assert_eq!(look(false, "written at its end"), PAGE - 500); + assert_eq!(look(true, "taken again"), 0); + // Outside the range, on its last page. + // SAFETY: as above. + unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) }; + assert_eq!(look(false, "written on its last page"), 500); + // A longer range was never taken whole. + assert!(!copy.nothing_new(region, 6 * PAGE)); + } + } + + /// A part of a copy in the card's memory taken again goes up only if it + /// differs (with `VICTORY_SEND_CHANGED=1`), whole when never taken. + #[test] + fn only_what_differs_goes_up() { + let region = title(4 * PAGE, true); + let data = memory(4 * PAGE); + let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true); + copy.update(region, 4 * PAGE); + assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change"); + // What the relay does: shader writes into title memory, and into the + // CPU's side. + crate::watch::landing(region + PAGE + 640, 64); + // SAFETY: the test's own memory. + unsafe { + std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64); + std::ptr::write_bytes(data.add(PAGE + 640), 7, 64); + } + copy.update(region, 4 * PAGE); + let again = copy.take_dirty(); + // SAFETY: as above. + unsafe { ((region + 2 * PAGE + 128) as *mut u8).write_volatile(9) }; + copy.update(region, 4 * PAGE); + let written = copy.take_dirty(); + if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") { + assert_eq!(again, []); + assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 192)]); + } else { + assert_eq!(again, [(PAGE, 2 * PAGE)]); + assert_eq!(written, [(2 * PAGE, 3 * PAGE)]); + } + // SAFETY: as above. + assert_eq!(unsafe { data.add(2 * PAGE + 128).read() }, 9); + } + + /// The refreshes of a frame as run record-1 had them: 30 submissions, the + /// first with a copy for each of 4,400 ranges, the others with 60 and a + /// big copy that 55 landed pieces and 9 title writes opened, while a + /// thread lands what shaders wrote. Run with `--ignored --nocapture`, + /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was. + #[test] + #[ignore] + fn frame_of_refreshes() { + let mut random = Random(0x9876_5432_1234_5671); + const EACH: usize = 224 << 10; + const BIG: usize = 174 << 20; + let watched = title(3000 * EACH, false); + let views = title(1400 * EACH, true); + let big = title(BIG, true); + // SAFETY: the test's own memory. + unsafe { + std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH); + std::ptr::write_bytes(views as *mut u8, 1, 1400 * EACH); + std::ptr::write_bytes(big as *mut u8, 1, BIG); + } + let mut small = Vec::new(); + for i in 0..4400 { + let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) }; + let data = memory(EACH); + // The range views read, not all of the copy. + small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000)); + } + let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG); + // The same memory, as another copy: what is landed is landed through + // it, and the refreshes are of the first. + let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true); + let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]); + let (mut sum, mut landing) = (0.0, 0.0); + const FRAMES: usize = 12; + for frame in 0..FRAMES { + let mut took = [0f64; 2]; + for i in 0..30 { + // The title's writes, and the relay's beside the submission. + for _ in 0..9 { + let at = views + random.below(1400 * EACH / 8) * 8; + // SAFETY: the test's own memory. + unsafe { (at as *mut u64).write_volatile(frame as u64) }; + } + for _ in 0..60 { + let at = watched + random.below(3000 * EACH / 8) * 8; + // SAFETY: the test's own memory. + unsafe { (at as *mut u64).write_volatile(frame as u64) }; + } + let first = random.below(BIG / PAGE - 60); + let lands = lands.clone(); + let land = std::thread::spawn(move || { + let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE]; + let started = std::time::Instant::now(); + for pieces in (first..first + 55).collect::>().chunks(4) { + let pieces: Vec<_> = + pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect(); + let mut notes = crate::land::Notes::default(); + // SAFETY: the bytes of `now`; nothing else lands here. + unsafe { lands.land_card(&pieces, 0, &mut notes) }; + notes.flush(); + } + started.elapsed().as_secs_f64() * 1e3 + }); + let ranges: Vec<(Arc, usize, usize)> = if i == 0 { + small.iter().cloned().chain([heap.clone()]).collect() + } else { + (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect() + }; + let started = std::time::Instant::now(); + submission(&ranges, 3); + took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3; + let put = land.join().unwrap(); + if frame >= 2 { + landing += put; + } + heap.0.take_dirty(); + } + if frame >= 2 { + sum += took[0] + took[1]; + for k in 0..2 { + best[k] = best[k].min(took[k]); + asking[k] += took[k]; + } + } + } + println!( + "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \ + others {:.2} (best {:.2}); the landing thread's puts {:.2}", + crate::watch::light(), + sum / (FRAMES - 2) as f64, + asking[0] / (FRAMES - 2) as f64, + best[0], + asking[1] / (FRAMES - 2) as f64, + best[1], + landing / (FRAMES - 2) as f64, + ); + #[cfg(feature = "diagnostics")] + println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64)); + } +} + #[cfg(test)] mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file use super::Batch; diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index da3118a..56a883b 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -291,6 +291,22 @@ pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { v.sections.push((section, bytes, committed)); } +/// The runtime lets go of a section, and of its handle: no view the title +/// sees is of it any more, and [`beside`]'s view goes. +pub fn title_memory_section_gone(section: usize) { + let whole = { + let mut v = views(); + let at = v.whole.iter().position(|w| w.0 == section); + at.map(|i| v.whole.swap_remove(i).1) + }; + if let Some(base) = whole.filter(|&base| base != 0) { + // SAFETY: a view of ours. Who writes through it found the section + // in a view the title saw and holds off its unmapping + // (`crate::watch::title_memory_reading`), which came before this. + unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: base as *mut c_void }) }; + } +} + /// The runtime mapped `[at, at + len)` as a view of `section` from /// `offset` on. Call after [`crate::title_memory_remapped`] of the range. pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 8c5b164..faabc53 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -67,7 +67,7 @@ mod watch; #[cfg(windows)] pub use host::on_failure; #[cfg(windows)] -pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; +pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] pub use watch::{ title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping, diff --git a/crates/victory-gpu/src/safecopy.rs b/crates/victory-gpu/src/safecopy.rs index 66bb68a..aa331eb 100644 --- a/crates/victory-gpu/src/safecopy.rs +++ b/crates/victory-gpu/src/safecopy.rs @@ -75,6 +75,46 @@ std::arch::global_asm!( "vzeroupper", "xor eax, eax", "ret", + ".globl victory_safe_update", + ".globl victory_safe_update_at", + ".globl victory_safe_update_after", + ".globl victory_safe_update_failed", + // rcx destination, rdx source, r8 bytes (whole 64s, not none), r9 where + // the offset of the first 64 bytes that differed goes (-1: none did) and + // behind it the offset of the end of the last: stores the 64s that + // differ. eax: whether all could be read. + "victory_safe_update:", + "xor r10d, r10d", + "mov r11, -1", + "xor eax, eax", + "2:", + "victory_safe_update_at:", + "vmovdqu ymm0, ymmword ptr [rdx + r10]", + "vmovdqu ymm1, ymmword ptr [rdx + r10 + 32]", + "victory_safe_update_after:", + "vpxor ymm2, ymm0, ymmword ptr [rcx + r10]", + "vpxor ymm3, ymm1, ymmword ptr [rcx + r10 + 32]", + "vpor ymm2, ymm2, ymm3", + "vptest ymm2, ymm2", + "jz 3f", + "vmovdqu ymmword ptr [rcx + r10], ymm0", + "vmovdqu ymmword ptr [rcx + r10 + 32], ymm1", + "cmp r11, -1", + "cmove r11, r10", + "lea rax, [r10 + 64]", + "3:", + "add r10, 64", + "cmp r10, r8", + "jb 2b", + "mov qword ptr [r9], r11", + "mov qword ptr [r9 + 8], rax", + "vzeroupper", + "mov eax, 1", + "ret", + "victory_safe_update_failed:", + "vzeroupper", + "xor eax, eax", + "ret", ".globl victory_safe_merge", ".globl victory_safe_merge_at", ".globl victory_safe_merge_after", @@ -145,12 +185,63 @@ unsafe extern "system" { fn victory_safe_put_at(); fn victory_safe_put_after(); fn victory_safe_put_failed(); + fn victory_safe_update(dst: *mut u8, src: *const u8, len: usize, changed: *mut [usize; 2]) -> u32; + fn victory_safe_update_at(); + fn victory_safe_update_after(); + fn victory_safe_update_failed(); fn victory_safe_merge(title: *mut u8, now: *const u8, held: *mut u8, blocks: usize, counts: *mut [u64; 2]) -> usize; fn victory_safe_merge_at(); fn victory_safe_merge_after(); fn victory_safe_merge_failed(); } +/// What [`update`] found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Updated { + /// Every byte was the same already; nothing was stored. + Same, + /// The bytes that changed lie in these offsets. + Changed(usize, usize), + /// Not all of the source could be read; some may have been copied. + Failed, +} + +/// Makes `dst` hold what `src` holds, storing only what differs. The source +/// may change meanwhile: what is compared is what is stored, read once. +/// +/// # Safety +/// As [`copy`]'s, and the destination is memory of ours that nothing else +/// writes. +pub(crate) unsafe fn update(dst: *mut u8, src: *const u8, len: usize) -> Updated { + let whole = len / 64 * 64; + let (mut from, mut to) = (usize::MAX, 0); + if whole > 0 { + let mut changed = [usize::MAX, 0]; + // SAFETY: the source's faults leave through the failing exit; the + // rest is the caller's. + if unsafe { victory_safe_update(dst, src, whole, &mut changed) } == 0 { + return Updated::Failed; + } + [from, to] = changed; + } + if whole < len { + let mut rest = [0u8; 64]; + let rest = &mut rest[..len - whole]; + // SAFETY: as above; `rest` is ours. + unsafe { + if !copy(rest.as_mut_ptr(), src.add(whole), rest.len()) { + return Updated::Failed; + } + let held = std::slice::from_raw_parts_mut(dst.add(whole), rest.len()); + if held != rest { + held.copy_from_slice(rest); + (from, to) = (from.min(whole), len); + } + } + } + if from >= to { Updated::Same } else { Updated::Changed(from, to) } +} + /// What [`merge`] did. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct Merged { @@ -354,6 +445,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_update_at as *const () as usize, victory_safe_update_after as *const () as usize); + if (from..to).contains(&at) { + return Some(victory_safe_update_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 +504,52 @@ mod tests { } } + /// An update makes the two the same, says where they differed (to 64 + /// bytes), stores nothing where they did not, and fails at a page that + /// is not there. + #[test] + fn updates_store_what_differs() { + assert!(on()); + let (src, dst) = (Pages::new(1 << 14), Pages::new(1 << 14)); + for len in [0usize, 1, 63, 64, 65, 200, 4096, 5000] { + for (da, sa) in [(0usize, 0usize), (3, 0), (0, 5)] { + for changed in [vec![], vec![0usize], vec![len / 2], vec![len.saturating_sub(1)], vec![1, len / 3, len / 2]] { + src.fill(); + // SAFETY: inside the two allocations. + unsafe { + std::ptr::write_bytes(dst.0, 0xEE, dst.1); + std::ptr::copy_nonoverlapping(src.0.add(sa), dst.0.add(da), len); + let at: std::collections::BTreeSet = changed.iter().copied().filter(|&i| i < len).collect(); + for &i in &at { + *src.0.add(sa + i) ^= 0x40; + } + let found = update(dst.0.add(da), src.0.add(sa), len); + match (at.iter().min(), at.iter().max()) { + (Some(&first), Some(&last)) => { + let Updated::Changed(from, to) = found else { + panic!("{len} {at:?}: {found:?}") + }; + assert_eq!(from, first / 64 * 64); + assert_eq!(to, ((last / 64 + 1) * 64).min(len)); + } + _ => assert_eq!(found, Updated::Same), + } + let (to, from) = (std::slice::from_raw_parts(dst.0, dst.1), std::slice::from_raw_parts(src.0, src.1)); + assert_eq!(to[da..da + len], from[sa..sa + len]); + assert!(to[..da].iter().chain(&to[da + len..]).all(|&x| x == 0xEE)); + } + } + } + } + // SAFETY: our allocation. + unsafe { + VirtualFree(src.0.add(4096).cast(), 4096, MEM_DECOMMIT); + assert_eq!(update(dst.0, src.0, 8192), Updated::Failed); + assert_eq!(update(dst.0, src.0.add(4096), 10), Updated::Failed); + assert_ne!(update(dst.0, src.0, 4096), Updated::Failed); + } + } + /// 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 28f8c28..091c5ed 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -35,6 +35,11 @@ pub(crate) struct Shadow { /// Per page of title memory from `start`'s on: the write-watch asking /// after which it was last copied (0: never). copied: Mutex>, + /// Two ranges of title memory taken whole, the last one and the longest, + /// and the asking after which each was ([`Shadow::copy_stale`]). A page + /// a range holds in part cannot say so in `copied`. Locked inside + /// `copied`'s lock. + ranged: Mutex<[(usize, usize, u64); 2]>, /// Whether the memory is write-watched: unknown, yes, no. watched: AtomicU8, /// Ranges shaders of a submission not yet copied back may be writing: @@ -1027,6 +1032,11 @@ struct Workers { more: std::sync::Condvar, } +/// How many threads are kept for [`wide`]. +fn wide_threads() -> usize { + std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6) +} + fn workers() -> &'static Workers { static WORKERS: std::sync::OnceLock = std::sync::OnceLock::new(); static STARTED: std::sync::Once = std::sync::Once::new(); @@ -1035,8 +1045,7 @@ fn workers() -> &'static Workers { more: std::sync::Condvar::new(), }); STARTED.call_once(|| { - let n = std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6); - for i in 0..n { + for i in 0..wide_threads() { let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || { let workers = WORKERS.get().expect("made above"); loop { @@ -1102,6 +1111,30 @@ pub(crate) fn wide_run(jobs: Vec>) { wide(jobs); } +/// Calls `work` with every number under `n`, on the kept threads and on +/// this one, the next number to whichever is free: for thousands of small +/// pieces of work, where a job each ([`wide`]) is mostly the jobs' queue. +pub(crate) fn wide_each(n: usize, work: impl Fn(usize) + Send + Sync + 'static) { + let next = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let work = Arc::new(work); + let threads = (wide_threads() + 1).min(n); + let jobs = (0..threads) + .map(|_| { + let (next, work) = (next.clone(), work.clone()); + Box::new(move || { + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= n { + break; + } + work(i); + } + }) as Job + }) + .collect(); + wide(jobs); +} + /// About this many bytes to a piece of work for [`wide`]. const WIDE_JOB: usize = 1 << 20; @@ -1408,7 +1441,11 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { let mut runs = Vec::new(); let mut i = 0; while i < n { - // Equal bytes, eight at a time while they last. + // Equal bytes, many at a time while they last (a page looked at + // under a flight's writes hardly ever differs at all). + while i + 512 <= n && now[i..i + 512] == was[i..i + 512] { + i += 512; + } while i + 8 <= n && now[i..i + 8] == was[i..i + 8] { i += 8; } @@ -1427,6 +1464,52 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { runs } +/// Whether pages of a copy in the card's memory that a refresh takes again +/// go up to the card only where they are not what the CPU's side holds +/// already (`VICTORY_SEND_CHANGED=1`; off by default). +/// +/// A refresh copies the 64 KiB pages that were written since it last took +/// them, and all of each went up and was hashed there again. Most of them +/// the title did not write: the relay put what shaders wrote into title +/// memory, and the card and the CPU's side hold those bytes already +/// ([`Shadow::card_merge_relay`]). Run record-1: 1,500 pieces (98 MB) a +/// frame fetched from the card, 103 MB in 328 ranges sent up, 322 hash +/// passes, while the title's own writes took some 260 guards off. +/// +/// What it rests on: the card's side holds what the CPU's side holds, but +/// for ranges shaders may be writing (no refresh touches them) and what is +/// still to go up. A page's first taking always goes up whole, so does one +/// that could not be read; after that every byte that changes on the CPU's +/// side goes up (the bytes compared are the bytes stored). +/// +/// Why it is not on by default: a shader that writes a copy through a view +/// nobody declared (`crate::draw`, buffers picked by index) breaks that +/// rule. Taken again, its page went up over what it wrote; with the switch +/// its bytes stay, as they would on the console, until the title changes the +/// same 64 bytes: clearing them to the zeros they held before is then no +/// change. +fn send_changed() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + #[cfg(feature = "diagnostics")] + if crate::copystat::mode() != 0 { + return false; + } + std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") && crate::safecopy::on() + }) +} + +/// Since the last frame-rate line, of pages taken again into copies in the +/// card's memory ([`send_changed`]): bytes compared, those of pages that +/// held the same, and bytes to go up. +static SEND: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// [`SEND`], taken. +#[cfg(feature = "diagnostics")] +pub(crate) fn send_stats() -> [u64; 3] { + [0, 1, 2].map(|i| SEND[i].swap(0, Ordering::Relaxed)) +} + /// Whether what shaders wrote goes into title memory run by run /// ([`put_changed`]; on by default, `VICTORY_EXACT_BACK=0` writes the whole /// stretch from the first changed byte to the last, as before). @@ -1559,6 +1642,34 @@ mod merge_tests { /// The runs hold exactly the bytes that differ: putting them into the /// old bytes gives the new ones, and no run holds an equal byte. + /// What looking at a page that did not change costs, against the look + /// eight bytes at a time that it was (a frame has some 250 of them, on + /// the submitting thread). Run with `--ignored --nocapture`. + #[test] + #[ignore] + fn runs_of_equal_pages() { + let (a, b) = (vec![7u8; 64 << 10], vec![7u8; 64 << 10]); + let eights = || { + let (now, was) = (std::hint::black_box(&a), std::hint::black_box(&b)); + let mut i = 0; + while i + 8 <= now.len() && now[i..i + 8] == was[i..i + 8] { + i += 8; + } + std::hint::black_box(i); + }; + let best = |f: &dyn Fn()| { + (0..500) + .map(|_| { + let t = std::time::Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1e6 + }) + .fold(f64::MAX, f64::min) + }; + let runs = || drop(std::hint::black_box(changed_runs(std::hint::black_box(&a), std::hint::black_box(&b)))); + println!("64 KiB that are the same: {:.1} us by eights, {:.1} us now", best(&eights), best(&runs)); + } + #[test] fn changed_runs_are_exactly_the_bytes_that_differ() { let was: Vec = (0..300u32).map(|i| (i * 13 + 5) as u8).collect(); @@ -1915,6 +2026,7 @@ impl Shadow { start, len, copied: Mutex::new(vec![0; pages as usize]), + ranged: Mutex::default(), watched: AtomicU8::new(0), pending: Mutex::default(), flights: Mutex::default(), @@ -2604,6 +2716,43 @@ impl Shadow { self.update_free(from, to) } + /// Whether [`Shadow::update`] of `[address, address + len)` would copy + /// nothing, and knows it without asking anything + /// (`crate::watch::nothing_new`). `false` if it would have to ask. + pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool { + if self.place.is_some() { + return true; + } + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), (address + len).min(end)); + if from >= to { + return true; + } + if self.watched.load(Ordering::Relaxed) != 1 { + return false; + } + // Around ranges shaders are writing the refresh asks gap by gap. + if self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) { + return false; + } + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + let same = crate::watch::nothing_new(from, to, start / PAGE, &copied, self.ranged(from, to)); + #[cfg(feature = "diagnostics")] + if same { + use crate::copystat::{C, add}; + add(C::Checked, (to - from) as u64); + add(C::Unchanged, (to - from) as u64); + } + same + } + + /// The latest asking after which a range that holds `[from, to)` was + /// taken whole (0: none is known). The caller holds `copied`'s lock. + fn ranged(&self, from: usize, to: usize) -> u64 { + let ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner()); + ranged.iter().filter(|r| r.0 <= from && to <= r.1).map(|r| r.2).max().unwrap_or(0) + } + /// [`Shadow::update`] of `[from, to)` (inside the buffer) where no /// shader writes. fn update_free(&self, from: usize, to: usize) -> usize { @@ -2696,7 +2845,13 @@ impl Shadow { let base = self.start as usize / PAGE; let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); let mut writes = written.iter().peekable(); - let (mut bytes, mut run) = (0, None); + // Pages the range holds in part are never noted in `copied`, and + // were copied again at every refresh of the range, written or not: + // of the heap's buffer views alone two ends for each of 4,400 + // copies, every frame. A range that was taken whole, and not written + // since, is as it was. + let ranged = if crate::watch::light() { self.ranged(from, to) } else { 0 }; + let (mut runs, mut run) = (Vec::new(), None::<(usize, bool)>); let last = (to - 1) / PAGE; for page in from / PAGE..=last { let write = match writes.peek() { @@ -2707,25 +2862,111 @@ impl Shadow { _ => 0, }; let at = &mut copied[page - base]; - if *at == 0 || write > *at { + let taken = (*at).max(ranged); + if taken == 0 || write > taken { // A page only partly in the range is copied in part: it // stays stale for the rest. let (start, end) = (self.start as usize, (self.start + self.len) as usize); if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to { *at = now; } - run.get_or_insert(page); - } else if let Some(first) = run.take() { - bytes += self.copy((first * PAGE).max(from), (page * PAGE).min(to)); + // Cut where pages taken before meet pages never taken. + let again = taken != 0; + if let Some((first, known)) = run + && known != again + { + runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known)); + run = None; + } + run.get_or_insert((page, again)); + } else if let Some((first, known)) = run.take() { + runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known)); } } // Cut to the range: next to it shaders may be writing the copy. - if let Some(first) = run { - bytes += self.copy((first * PAGE).max(from), ((last + 1) * PAGE).min(to)); + if let Some((first, known)) = run { + runs.push(((first * PAGE).max(from), ((last + 1) * PAGE).min(to), known)); + } + let bytes = self.take_all(runs); + if crate::watch::light() { + // All of the range is in the copy as of this asking. + let mut ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner()); + ranged[0] = (from, to, now); + if to - from >= ranged[1].1 - ranged[1].0 { + ranged[1] = (from, to, now); + } } bytes } + /// [`Shadow::take`] of `runs` (from, to, known), on several threads if + /// they are long: the big heap's copy has some 4 MB of them in each of + /// 14 refreshes a frame, on one thread while the others had nothing. + fn take_all(&self, runs: Vec<(usize, usize, bool)>) -> usize { + const LONG: usize = 1 << 20; + const PART: usize = 256 << 10; + let bytes = runs.iter().map(|r| r.1 - r.0).sum(); + if bytes < LONG || !crate::watch::light() { + for (from, to, known) in runs { + self.take(from, to, known); + } + return bytes; + } + let mut parts = Vec::with_capacity(bytes / PART + runs.len()); + for (from, to, known) in runs { + let mut at = from; + while at < to { + // Whole pages to a part. + let next = ((at / PAGE) * PAGE + PART).min(to); + parts.push((at, next, known)); + at = next; + } + } + let this = std::ptr::from_ref(self) as usize; + wide_each(parts.len(), move |i| { + // SAFETY: `wide_each` returns when every part is done, before + // the borrow of `self` ends. The parts lie apart. + let this = unsafe { &*(this as *const Shadow) }; + let (from, to, known) = parts[i]; + this.take(from, to, known); + }); + bytes + } + + /// Copies title memory `[from, to)` (inside the buffer) into the copy; + /// `known`: the copy held it before ([`send_changed`]). + fn take(&self, from: usize, to: usize, known: bool) -> usize { + if !known || self.card.is_none() || !send_changed() { + return self.copy(from, to); + } + let start = self.start as usize; + let mut at = from; + while at < to { + let n = (PAGE - at % PAGE).min(to - at); + // SAFETY: inside the mapping of the copy's CPU side, which + // nothing else writes there: no shader's range holds it. + let found = unsafe { crate::safecopy::update(self.data.add(at - start), at as *const u8, n) }; + SEND[0].fetch_add(n as u64, Ordering::Relaxed); + match found { + crate::safecopy::Updated::Same => { + SEND[1].fetch_add(n as u64, Ordering::Relaxed); + } + crate::safecopy::Updated::Changed(a, b) => { + SEND[2].fetch_add((b - a) as u64, Ordering::Relaxed); + self.changed(at - start + a, at - start + b); + self.card_changed(at - start + a, at - start + b); + } + // A page is not there: as before, around it, and all of it + // goes up. + crate::safecopy::Updated::Failed => { + self.copy(at, at + n); + } + } + at += n; + } + to - from + } + /// Copies title memory `[from, to)`, cut to the buffer, into the copy. fn copy(&self, from: usize, to: usize) -> usize { let (start, end) = (self.start as usize, (self.start + self.len) as usize); @@ -2960,6 +3201,52 @@ impl Shadow { } } +/// For tests: copies with no host buffer behind them. +#[cfg(test)] +impl Shadow { + /// A copy at `data` of title memory `[start, start + len)`, with a card + /// side if `card`. It is never let go: there is no buffer to release. + pub(crate) fn unbacked(start: u64, data: *mut u8, len: u64, card: bool) -> Arc { + // SAFETY: an interface pointer nothing calls. + let none = || unsafe { std::mem::transmute::(8) }; + let mut shadow = Shadow::new(none(), data, 0, start, len); + if card { + shadow.card = Some(Card { + staging: none(), + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size: len.next_multiple_of(PIECE as u64), + }); + } + let shadow = Arc::new(shadow); + std::mem::forget(shadow.clone()); + shadow + } + + /// What shaders wrote goes into title memory ([`put_changed`]). + pub(crate) fn put(at: usize, title: &[u8], merged: &[u8]) { + put_changed(at, title, merged); + } + + /// What is to go up to the card, noted as sent with `number`, as + /// [`card_dirty`] does; notes of sends up to `merged` go. + pub(crate) fn send_up(&self, number: u64, merged: u64) -> Vec<(usize, usize)> { + let card = self.card.as_ref().unwrap(); + let mut dirty = card.dirty.lock().unwrap(); + let ranges = std::mem::take(&mut *dirty); + let mut sent = card.sent.lock().unwrap(); + sent.retain(|s| s.2 > merged); + sent.extend(ranges.iter().map(|&(a, b)| (a, b, number))); + ranges + } + + /// What is to go up to the card, taken. + pub(crate) fn take_dirty(&self) -> Vec<(usize, usize)> { + std::mem::take(&mut *self.card.as_ref().unwrap().dirty.lock().unwrap()) + } +} + impl Shadow { /// [`Shadow::card_merge_relay`] of several pieces, each within one /// 64 KiB block of title memory: from and to (offsets in the copy), and diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index debc8a9..dfae9f4 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -149,6 +149,8 @@ fn kernel_written(first: usize, last: usize) -> Option> { add(C::Watches, 1); add(C::WatchUs, started.elapsed().as_micros() as u64); slow(started.elapsed().as_micros() as u64); + tally(0, 1); + tally(1, ((last - first) * (PAGE >> 10)) as u64); } let mut pages: Vec = found[..count].iter().map(|&at| at / PAGE).collect(); pages.dedup(); @@ -173,7 +175,9 @@ const AHEAD_MAX: usize = (1 << 30) / PAGE; pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { let mut pieces: Vec<(usize, usize)> = ranges .iter() - .filter(|r| r.0 < r.1) + // Not view memory known by its bits: the kernel would refuse the + // asking (and, asked together with others, theirs). + .filter(|r| r.0 < r.1 && !published(r.0, r.1)) .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE))) .collect(); if pieces.len() < 2 { @@ -291,7 +295,7 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { // here, once; what is not write-watched stays with `writes`. let mut written = Vec::new(); for &(start, end) in ranges { - if start >= end { + if start >= end || published(start, end) { continue; } let (first, last) = (start / PAGE, end.div_ceil(PAGE)); @@ -384,15 +388,24 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve if let Some(known) = ahead(&journal()) { return Some(known); } + // Read-only since an asking noted it: the bits first, then the journal. + if guarded && published(start, end) { + #[cfg(feature = "diagnostics")] + tally(2, 1); + let j = journal(); + return Some((next_asking(), of(&j))); + } // Asked, and the answer noted, with the range held: nothing else asks // about any of it in between. let _range = Asking::hold(first, last); if let Some(known) = ahead(&journal()) { return Some(known); } + let mut guards_asked = false; let pages = match kernel_written(first, last) { Some(pages) => pages, None => { + guards_asked = true; if !guarded { return None; } @@ -418,15 +431,189 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let j = journal(); return Some((next_asking(), of(&j))); } - let mut j = journal_mut(); - let now = next_asking(); - j.written.extend(pages.into_iter().map(|page| (page, now))); - Some((now, of(&j))) + let answer = { + let mut j = journal_mut(); + let now = next_asking(); + j.written.extend(pages.iter().map(|&page| (page, now))); + (now, of(&j)) + }; + // Noted: what the guards made clean of it is known by its bits from + // now on. (The range is still held: no other asking of any of it came + // between.) + if guards_asked && light() { + publish(&pages); + } + Some(answer) +} + +/// Whether nothing of `[start, end)` was written that a copy with the notes +/// `copied` (the asking after which each page from page `base` on was taken) +/// and `ranged` (the asking after which a range that holds this one was +/// taken whole, or 0) does not hold, as [`writes`] would answer with nothing +/// asked: the submission's asking covers the range, or its blocks are known +/// by their bits. `false` if something would have to be asked. +pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], ranged: u64) -> bool { + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + // The bits first, then the journal, as in `writes`. + let known = published(start, end); + let j = journal(); + if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { + return false; + } + let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else { + return false; + }; + (ranged != 0 || taken.iter().all(|&at| at != 0)) + && j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged)) } /// Guarded blocks of view memory. const BLOCK: usize = PAGE; +/// Whether the refreshes of host copies go the light way +/// (`VICTORY_LIGHT_REFRESH=0`: as before): view memory nothing wrote since +/// it was last asked about is known by its bits ([`PUBLISHED`]), a copy +/// nothing of whose range changed is told so before any thread is woken +/// for it (`crate::host`, `Shadow::nothing_new`), and the ends of a range, +/// pages the range holds in part, are not copied again at every refresh +/// (`Shadow::copy_stale`). +/// +/// A frame asked about view memory some 1,500 times, for nearly all of it +/// to hear that nothing was written, on up to seven threads at once, each +/// asking under the guards' one lock and behind [`ASKING`]'s: 94 ms a frame +/// of all threads' time (run record-1), most of it waiting. +pub(crate) fn light() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIGHT_REFRESH").is_none_or(|v| v != "0")) +} + +/// A bit per block of the address space, in pieces made when first needed +/// and never let go. +struct Bits([std::sync::atomic::AtomicPtr; Bits::PIECES]); + +/// The bits of 4 GiB. +type BitsPiece = [std::sync::atomic::AtomicU64; Bits::WORDS]; + +impl Bits { + const WORDS: usize = 1 << 10; + /// 128 TiB, what a process has. + const PIECES: usize = 1 << 15; + + const fn new() -> Bits { + Bits([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Bits::PIECES]) + } + + fn piece(&self, word: usize) -> Option<&BitsPiece> { + let piece = self.0.get(word / Bits::WORDS)?.load(std::sync::atomic::Ordering::Acquire); + // SAFETY: null, or a piece made by `set`, which is never freed. + unsafe { piece.as_ref() } + } + + /// One caller at a time (under the guards' lock). + fn set(&self, block: usize) { + use std::sync::atomic::Ordering::{Relaxed, Release}; + let word = block / 64; + let Some(place) = self.0.get(word / Bits::WORDS) else { + return; + }; + if place.load(Relaxed).is_null() { + let piece: Box = Box::new([const { std::sync::atomic::AtomicU64::new(0) }; Bits::WORDS]); + place.store(Box::into_raw(piece), Release); + } + if let Some(piece) = self.piece(word) { + piece[word % Bits::WORDS].fetch_or(1 << (block % 64), Release); + } + } + + fn clear(&self, block: usize) { + let word = block / 64; + if let Some(piece) = self.piece(word) { + // Ahead of the protection's change, and seen by whoever the + // writer tells of its write. + piece[word % Bits::WORDS].fetch_and(!(1 << (block % 64)), std::sync::atomic::Ordering::SeqCst); + } + } + + /// Whether the bits of all of `[first, last)` are set (not so of none). + fn all(&self, first: usize, last: usize) -> bool { + let mut block = first; + while block < last { + let word = block / 64; + let until = ((word + 1) * 64).min(last); + let mask = (u64::MAX >> (64 - (until - block))) << (block % 64); + let Some(piece) = self.piece(word) else { + return false; + }; + if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::Acquire) & mask != mask { + return false; + } + block = until; + } + first < last + } +} + +/// The blocks that are read-only by our hand, not written since, and of +/// which the journal holds every write from before that: for those, what +/// [`writes`] answers is in the journal, and neither the kernel, nor the +/// guards' lock, nor [`ASKING`] need be asked. +/// +/// Why that is so: a block's bit is set under the guards' lock while the +/// block is clean, by the asking that made it clean, after that asking noted +/// in the journal what it found ([`publish`]). It is cleared under the same +/// lock, before the block becomes writable again ([`open`]) or is forgotten +/// ([`title_memory_remapped`]). So while the bit is set nothing can have +/// written the block through this address, and who sees the bit and looks +/// at the journal after that finds every earlier write in it. A write that +/// comes while the bit is looked at is no different from one that comes just +/// after an asking: the next asking finds the block open. +static PUBLISHED: Bits = Bits::new(); + +/// An asking made blocks of `pages` clean and noted them in the journal. +fn publish(pages: &[usize]) { + let g = guards(); + for page in pages { + if g.clean.contains(page) { + PUBLISHED.set(*page); + } + } +} + +/// Whether nothing of `[start, end)` can have been written since an asking +/// noted it in the journal ([`PUBLISHED`]). +fn published(start: usize, end: usize) -> bool { + light() && PUBLISHED.all(start / BLOCK, end.div_ceil(BLOCK)) +} + +/// Since the last frame line: what asking about title memory was. Kernel +/// askings and the KiB they walked; view ranges answered by their bits, by +/// the guards whole clean, and block by block; blocks made read-only; blocks +/// opened by ourselves; nanoseconds waiting for the guards' lock and +/// nanoseconds of changing protections (all threads). +#[cfg(feature = "diagnostics")] +static ASKS: [std::sync::atomic::AtomicU64; 9] = [const { std::sync::atomic::AtomicU64::new(0) }; 9]; + +#[cfg(feature = "diagnostics")] +fn tally(what: usize, n: u64) { + ASKS[what].fetch_add(n, std::sync::atomic::Ordering::Relaxed); +} + +/// [`ASKS`], taken. +#[cfg(feature = "diagnostics")] +pub(crate) fn asks() -> [u64; 9] { + std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// The guards' lock, the wait for it counted. +fn guards_timed() -> std::sync::MutexGuard<'static, Guards> { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + let g = guards(); + #[cfg(feature = "diagnostics")] + tally(7, started.elapsed().as_nanos() as u64); + g +} + struct Guards { /// Blocks we made read-only. protected: BTreeSet, @@ -485,16 +672,21 @@ pub(crate) fn landing(at: usize, len: usize) { writing(at, len); } + /// What shaders wrote went into title memory through another view of the /// same pages (`crate::inplace::beside`): `pages` (of 4 KiB, by number) /// hold some of it, all of them in `spans` (address, bytes). /// -/// Nothing faulted and no guard was opened. A guarded block stays read-only -/// and is noted as written, as [`guard`] notes one "written through the -/// runtime": the next asking reports it, to every copy that has it, and has -/// nothing to protect. Noted after the bytes are in, never before: a copy -/// that takes the block while they go in notes it clean, and this makes it -/// written again; noted before, such a copy would keep the half it read. +/// Nothing faulted and no guard was opened. A guarded block stays read-only, +/// clean, and known by its bit ([`PUBLISHED`]), all of which say that the +/// title wrote nothing there: our write is an entry of the journal, which +/// every answer about the block comes from, the quick ones and the guards' +/// alike (a block whose guard is off they report anyway). So neither the +/// guards' lock nor a protection is touched here, or by the next refresh. +/// Noted after the bytes are in, never before: a copy that read the block +/// before they were did so with the number of an asking made before that, +/// which is under the one given here, and takes it again; noted before, a +/// copy could read the older bytes with a number above the note's. pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) { { let frame = crate::frame::current(); @@ -505,12 +697,13 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) { } } { - let mut g = guards(); + let mut j = journal_mut(); + let now = next_asking(); let mut last = usize::MAX; for &page in pages { - let block = page * KERNEL_PAGE / BLOCK; + let block = page * KERNEL_PAGE / PAGE; if block != last { - g.clean.remove(&block); + j.written.insert(block, now); last = block; } } @@ -532,9 +725,9 @@ pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool { } /// Whether every block of `[at, at + len)` is view memory written since a -/// host copy last took it: guarded then, and the guard is off, or noted -/// written behind it. (Written by the title, or by us putting a flight's -/// shader writes into it, [`landed_beside`].) Not for +/// host copy last took it: guarded then, and the guard is off. (Written by +/// the title, or by us putting a flight's shader writes into it, if not +/// beside the guard, [`landed_beside`].) Not for /// blocks no copy ever took, which were never guarded: the caller's range /// lies in a copy a flight was given, which took all of it. pub(crate) fn written_since_taken(at: usize, len: usize) -> bool { @@ -559,7 +752,7 @@ fn guard(start: usize, end: usize) -> Option> { // `VICTORY_GUARD_ASK=1` asks every time, as before. static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && { - let g = guards(); + let g = guards_timed(); let first = start / BLOCK; g.protected.contains(&first) || g.absent.contains(&first) }; @@ -567,7 +760,7 @@ fn guard(start: usize, end: usize) -> Option> { return None; } install(); - let mut g = guards(); + let mut g = guards_timed(); let mut written = Vec::new(); let mut run: Option = None; let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); @@ -579,8 +772,12 @@ fn guard(start: usize, end: usize) -> Option> { let clean: Vec = g.clean.range(first..last).copied().collect(); if clean.len() == last - first { // Nothing written, mapped or new since the range was last taken. + #[cfg(feature = "diagnostics")] + tally(3, 1); return Some(written); } + #[cfg(feature = "diagnostics")] + tally(4, 1); let mut next_clean = 0; let mut uncommitted_until = first; for block in first..=last { @@ -668,15 +865,23 @@ fn protect(g: &mut Guards, from: usize, to: usize) { use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; let set = |from: usize, to: usize| { let mut old = 0; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); // SAFETY: title view memory; only its protection changes. - unsafe { + let done = unsafe { VirtualProtect( (from * BLOCK) as *const _, (to - from) * BLOCK, PAGE_READONLY, &mut old, ) != 0 + }; + #[cfg(feature = "diagnostics")] + { + tally(5, (to - from) as u64); + tally(8, started.elapsed().as_nanos() as u64); } + done }; let note = |g: &mut Guards, from: usize, to: usize| { g.protected.extend(from..to); @@ -720,13 +925,21 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { .range(start / BLOCK..end.div_ceil(BLOCK)) .copied() .collect(); + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); for &block in &blocks { g.protected.remove(&block); g.clean.remove(&block); + // Before the block can be written. + PUBLISHED.clear(block); let mut old = 0; // SAFETY: a block we made read-only. unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; } + #[cfg(feature = "diagnostics")] + if !blocks.is_empty() { + tally(8, started.elapsed().as_nanos() as u64); + } !blocks.is_empty() } @@ -736,7 +949,14 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { /// reads into its own memory. pub fn writing(at: usize, len: usize) { // The length is the title's (`fread`'s size times count, saturated). - open(&mut guards(), at, at.saturating_add(len)); + { + let mut g = guards_timed(); + #[cfg(feature = "diagnostics")] + let held = g.protected.len(); + open(&mut g, at, at.saturating_add(len)); + #[cfg(feature = "diagnostics")] + tally(6, (held - g.protected.len()) as u64); + } // A placed texture there changes with no descriptor written. crate::descriptor::host::remapped(at, len); } @@ -816,6 +1036,7 @@ pub fn title_memory_unmapping(at: usize, len: usize) { for block in blocks { g.protected.remove(&block); g.clean.remove(&block); + PUBLISHED.clear(block); } } @@ -1396,4 +1617,111 @@ mod many_askers_tests { // SAFETY: the reservation made above. unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) }; } + + /// The same of view memory, which is guarded: what its bits answer + /// misses no write either, however often blocks are opened and guarded + /// again between. + #[test] + fn no_write_to_views_is_lost_between_askers() { + const PAGES: usize = 12; + const THREADS: usize = 8; + // SAFETY: a view of a section of our own. + let at = unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (PAGES * PAGE) as u32, + std::ptr::null(), + ); + let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, PAGES * PAGE).Value as usize; + crate::title_memory_section(section as usize, (PAGES * PAGE) as u64, true); + super::title_memory_remapped(at, PAGES * PAGE); + crate::title_memory_view(at, PAGES * PAGE, section as usize, 0); + at + }; + assert!(at != 0 && at.is_multiple_of(PAGE)); + let by_bits = std::sync::atomic::AtomicUsize::new(0); + let past = std::sync::atomic::AtomicUsize::new(0); + std::thread::scope(|s| { + for t in 0..THREADS { + let (by_bits, past) = (&by_bits, &past); + s.spawn(move || { + let mut last = [0u64; PAGES]; + let mut seed = t as u64 * 7919 + 1; + let mut next = |n: usize| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as usize % n + }; + for _ in 0..500 { + let page = next(PAGES); + let from = page - next(page.min(3) + 1); + let to = page + 1 + next((PAGES - page).min(3)); + if next(4) != 0 { + // As in the test above, or after a word of ours, + // or past the guard. + let word = at + page * PAGE + t * 8; + // SAFETY (both): as above. + let reading = (next(3) == 0).then(super::title_memory_reading_now).flatten(); + let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8)); + if let Some(to) = beside { + unsafe { (to as *mut u64).write_volatile(2) }; + super::landed_beside(&[word / 4096], &[(word, 8)]); + past.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + assert_eq!(unsafe { (word as *const u64).read_volatile() }, 2, "put elsewhere"); + } else { + if next(4) == 0 { + super::writing(word, 8); + } + unsafe { (word as *mut u64).write_volatile(1) }; + } + } else { + // Nothing written: what is asked counts as before. + by_bits.fetch_add( + usize::from(super::published(at + from * PAGE, at + to * PAGE)), + std::sync::atomic::Ordering::Relaxed, + ); + let (now, _) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view"); + for l in &mut last[from..to] { + *l = now; + } + continue; + } + let (now, written) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view"); + let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1); + assert!(number > last[page], "page {page}: {number} is not after {}", last[page]); + for l in &mut last[from..to] { + *l = now; + } + } + }); + } + }); + assert!(by_bits.into_inner() > 0, "the bits answered none"); + assert!(past.into_inner() > 0, "nothing was put past the guards"); + // (The view stays: at its address other tests' memory would be told + // of these writes.) + } + + /// A range's bits are all of its blocks', whatever lies beside them. + #[test] + fn bits_of_ranges() { + static BITS: super::Bits = super::Bits::new(); + let blocks = [0usize, 1, 63, 64, 65, 127, 128, 200, 65535, 65536, 65537, 1 << 20, (1 << 31) - 1]; + for &b in &blocks { + assert!(!BITS.all(b, b + 1)); + BITS.set(b); + assert!(BITS.all(b, b + 1)); + } + assert!(BITS.all(0, 2) && BITS.all(63, 66) && BITS.all(127, 129) && BITS.all(65535, 65538)); + assert!(!BITS.all(0, 3) && !BITS.all(62, 64) && !BITS.all(65534, 65536) && !BITS.all(5, 5)); + for b in 300..700 { + BITS.set(b); + } + assert!(BITS.all(300, 700) && !BITS.all(299, 700) && !BITS.all(300, 701)); + BITS.clear(511); + assert!(!BITS.all(300, 700) && BITS.all(300, 511) && BITS.all(512, 700)); + assert!(!BITS.all(1 << 40, (1 << 40) + 1), "outside the address space"); + } } diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 56d56ca..36dd2bd 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -419,6 +419,7 @@ impl Drop for Section { }) }; } + victory_gpu::title_memory_section_gone(self.handle as usize); // SAFETY: our handle; views keep the section alive on their own. unsafe { CloseHandle(self.handle) }; }