diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 2b065a2..a067acc 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1047,6 +1047,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 7d290a3..712298b 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -365,6 +365,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. @@ -1368,18 +1488,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 }; @@ -1389,7 +1516,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; }; @@ -1420,13 +1547,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); @@ -1466,7 +1595,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 4ae7669..a580438 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4176,6 +4176,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). @@ -4183,7 +4185,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 @@ -4198,6 +4200,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 @@ -4213,6 +4217,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); firsts.push(lists.len()); @@ -4223,6 +4229,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. @@ -4233,6 +4241,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. @@ -4246,6 +4256,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; @@ -4258,6 +4270,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); @@ -5471,40 +5485,46 @@ impl HostList { fn run_deferred(&self, batch: &mut Batch) { #[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 step in &self.deferred().copies { - 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(); } @@ -5545,12 +5565,132 @@ 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 ({:.0} pieces \ + put past the guards, VICTORY_LAND_WINDOW); {:.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[9], + 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). /// @@ -5612,7 +5752,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, } @@ -5644,7 +5784,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. @@ -5673,6 +5819,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; @@ -5693,12 +5869,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 { @@ -6116,6 +6308,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 { @@ -6853,6 +7047,315 @@ 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 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); + 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 land = std::thread::spawn(move || { + let mut took = 0.0; + for piece in first..first + 55 { + let mut was = vec![0; PAGE]; + assert!(super::read_into((big + piece * PAGE) as *const u8, &mut was)); + let mut now = was.clone(); + now[8..PAGE - 8].fill(frame as u8 ^ i as u8); + let started = std::time::Instant::now(); + Shadow::put(big + piece * PAGE, &was, &now); + took += started.elapsed().as_secs_f64() * 1e3; + } + took + }); + 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 25461df..2d3e27e 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -280,11 +280,41 @@ fn views() -> std::sync::MutexGuard<'static, Views> { /// The runtime made a section of `bytes` for physical pages; `committed` /// if with `SEC_COMMIT` (only such a section can be opened as a heap). pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { + title_memory_section_gone(section); let mut v = views(); v.sections.retain(|s| s.0 != section); v.sections.push((section, bytes, committed)); } +/// Views of ours of whole sections, by the section's handle: where. +static WINDOWS: Mutex> = Mutex::new(BTreeMap::new()); + +/// The runtime lets go of a section, and of its handle: no view of it is +/// mapped any more. +pub fn title_memory_section_gone(section: usize) { + let window = WINDOWS.lock().unwrap_or_else(|e| e.into_inner()).remove(§ion); + if let Some(base) = window.filter(|&base| base != 0) { + // SAFETY: a view of ours. Who writes through it holds off the + // runtime's unmapping of the view it found the section by + // (`crate::watch::land_through`), which came before this. + unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: base as *mut c_void }) }; + } +} + +/// Where a view of ours of all of `section` is, made when first asked for; +/// `None` if the host gives none. The caller holds off remapping +/// (`crate::title_memory_reading`) and found the section in a view the +/// runtime told us of, so the section lives. +pub(crate) fn window(section: usize) -> Option { + let bytes = views().sections.iter().find(|s| s.0 == section)?.1; + let mut windows = WINDOWS.lock().unwrap_or_else(|e| e.into_inner()); + let base = *windows.entry(section).or_insert_with(|| { + // SAFETY: a live section of that many bytes. + unsafe { mem::MapViewOfFile(section as *mut c_void, mem::FILE_MAP_WRITE, 0, 0, bytes as usize) }.Value as usize + }); + (base != 0).then_some(base) +} + /// 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 2ecf3ab..f09fac1 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -65,7 +65,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, writing as kernel_will_write, diff --git a/crates/victory-gpu/src/safecopy.rs b/crates/victory-gpu/src/safecopy.rs index 24eb646..3dd7bc2 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", ); unsafe extern "system" { @@ -86,6 +126,57 @@ 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(); +} + +/// 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) } } /// Puts `now` at `dst` where it differs from `was`, whole dwords (as `dst` @@ -160,7 +251,11 @@ pub(crate) fn failing_exit(at: usize) -> Option { return Some(victory_safe_copy_failed as *const () as usize); } let (from, to) = (victory_safe_put_at as *const () as usize, victory_safe_put_after as *const () as usize); - (from..to).contains(&at).then_some(victory_safe_put_failed as *const () as usize) + 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); + (from..to).contains(&at).then_some(victory_safe_update_failed as *const () as usize) } #[cfg(test)] @@ -214,6 +309,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 68817e0..37363bd 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: @@ -1028,6 +1033,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(); @@ -1036,8 +1046,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 { @@ -1103,6 +1112,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; @@ -1390,7 +1423,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; } @@ -1409,6 +1446,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). @@ -1452,6 +1535,16 @@ fn dword_runs(at: usize, title: &[u8], merged: &[u8], gap: usize) -> Vec<(usize, /// shortcut: a piece with very many runs has them joined over small gaps, /// where the old race is left. fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { + // Past the guard, if it is one (`VICTORY_LAND_WINDOW`). + if exact_back() + && crate::safecopy::on() + // SAFETY: the same title memory through a view of ours. + && crate::watch::land_through(at, title.len(), |to| unsafe { crate::safecopy::put_changed(to, title, merged) }) + { + PUT[0].fetch_add(1, Ordering::Relaxed); + PUT[2].fetch_add(merged.len() as u64, Ordering::Relaxed); + return merged.len(); + } crate::watch::landing(at, title.len()); if !exact_back() { crate::host::write_mapped(at as *mut u8, merged.as_ptr(), merged.len()); @@ -1520,6 +1613,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(); @@ -1871,6 +1992,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(), @@ -2547,6 +2669,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 { @@ -2581,7 +2740,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() { @@ -2592,25 +2757,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); @@ -2809,6 +3060,40 @@ 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, taken. + pub(crate) fn take_dirty(&self) -> Vec<(usize, usize)> { + std::mem::take(&mut *self.card.as_ref().unwrap().dirty.lock().unwrap()) + } +} + struct Entry { end: u64, shadow: Option>, diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 27774d6..0b19382 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,190 @@ 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); pieces put into title +/// memory past the guards ([`land_through`]). +#[cfg(feature = "diagnostics")] +static ASKS: [std::sync::atomic::AtomicU64; 10] = [const { std::sync::atomic::AtomicU64::new(0) }; 10]; + +#[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; 10] { + 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, @@ -453,15 +641,78 @@ static LANDED: Mutex>> = Mutex::new /// What shaders wrote is about to go into title memory at `[at, at + len)`. pub(crate) fn landing(at: usize, len: usize) { + note_landed(at, len); + writing(at, len); +} + +fn note_landed(at: usize, len: usize) { + let frame = crate::frame::current(); + let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); + let landed = landed.get_or_insert_with(Default::default); + for page in at / 4096..=(at + len.max(1) - 1) / 4096 { + landed.insert(page, frame); + } +} + +/// Whether what shaders wrote goes into guarded title memory past the guard +/// (`VICTORY_LAND_WINDOW=1`; off by default, not yet run in the game). +/// +/// Each piece put into title memory took the guard off its block, and the +/// next refresh of a copy of it put it on again, two changes of protection +/// under the guards' one lock, 10 microseconds each with the title's threads +/// running: some 1,600 pieces a frame, in the relay's landing and in the +/// submitting thread's refreshes. The title's own writes take some 260. +fn land_window() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_WINDOW").is_some_and(|v| v == "1") && light()) +} + +/// With [`land_window`], if `[at, at + len)` is guarded view memory: `put` +/// writes what shaders wrote there, at the address it is given, through a +/// view of ours of the same section. Whether it did (`put` says whether it +/// could); if not the caller goes the other way ([`landing`]), `put` begun +/// or not. +/// +/// Why it is the same: the runtime tells of every view it maps, and forgets +/// those it unmaps, under the lock held here for reading, so while it is +/// held the pages the title sees at `at` are the pages written. The block +/// stays read-only for the title, whose own writes are seen as before. Ours +/// is noted in the journal, after the bytes are in: an asking before that +/// may or may not copy them, and has a number under the note's, so the next +/// one copies the page (again). +pub(crate) fn land_through(at: usize, len: usize, put: impl FnOnce(*mut u8) -> bool) -> bool { + land_window() && land_past(at, len, put) +} + +fn land_past(at: usize, len: usize, put: impl FnOnce(*mut u8) -> bool) -> bool { + if len == 0 || !published(at, at + len) { + return false; + } + let Some(_mapped) = title_memory_reading_now() else { + return false; + }; + let crate::inplace::Cover::Run(section, offset) = crate::inplace::cover(at, len) else { + return false; + }; + let Some(base) = crate::inplace::window(section) else { + return false; + }; + if !put((base + offset as usize) as *mut u8) { + return false; + } + note_landed(at, len); { - let frame = crate::frame::current(); - let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); - let landed = landed.get_or_insert_with(Default::default); - for page in at / 4096..=(at + len.max(1) - 1) / 4096 { - landed.insert(page, frame); + let mut j = journal_mut(); + let now = next_asking(); + for page in at / PAGE..(at + len).div_ceil(PAGE) { + j.written.insert(page, now); } } - writing(at, len); + #[cfg(feature = "diagnostics")] + tally(9, 1); + // As `writing` says. + crate::descriptor::host::remapped(at, len); + true } /// Whether shaders' writes went into a page of `[at, at + len)` in the last @@ -501,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) }; @@ -509,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)); @@ -521,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 { @@ -610,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); @@ -662,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() } @@ -678,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); } @@ -753,6 +1031,7 @@ pub fn title_memory_remapped(at: usize, len: usize) { for block in blocks { g.protected.remove(&block); g.clean.remove(&block); + PUBLISHED.clear(block); } } @@ -1264,4 +1543,113 @@ 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 put = next(3) == 0 + && super::land_past(word, 8, |to| { + unsafe { to.cast::().write_volatile(2) }; + true + }); + if put { + 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"); + super::title_memory_remapped(at, PAGES * PAGE); + // SAFETY: the view mapped above. + unsafe { UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: at as *mut _ }) }; + } + + /// 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 fe5b4c5..95fd0df 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) }; }