diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index cb57a59f98..1fcc4d3658 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -5172,9 +5172,9 @@ fn wide_refresh() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_REFRESH").is_some_and(|v| v == "1")) } -/// A submission's refreshes not done yet, merged per buffer copy into the -/// range that covers them: done before a step that writes title memory or -/// gives a range to shaders, and before the lists run. +/// A submission's pending refreshes, grouped by buffer copy. Refreshes +/// run before a step writes title memory or gives a range to shaders, +/// and before the lists run. /// /// Also the textures brought up to date in the submission so far: most /// lists of a world submission sample the same textures, and a texture in @@ -5182,7 +5182,7 @@ fn wide_refresh() -> bool { /// once, it is checked again only after a step that writes title memory. #[derive(Default)] struct Batch { - refreshes: Vec<(std::sync::Arc, usize, usize)>, + refreshes: Vec, /// Where each copy (by address) is in `refreshes`: the list that makes /// the heap's buffers ready adds some 4,100 copies, and searching them /// for every refresh of a submission was tens of millions of @@ -5192,18 +5192,66 @@ struct Batch { textures: std::collections::HashSet, } +type ShadowRefresh = (std::sync::Arc, RefreshRanges); + +/// Preserve holes between requests (`VICTORY_DISJOINT_REFRESH=1`). +fn disjoint_refresh() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_DISJOINT_REFRESH").is_some_and(|v| v == "1")) +} + +/// Keep a single range inline. Merge accumulated overlaps before refreshing. +enum RefreshRanges { + One((usize, usize)), + Many(Vec<(usize, usize)>), +} + +impl RefreshRanges { + fn add(&mut self, (from, to): (usize, usize), preserve_gaps: bool) { + match self { + Self::One((start, end)) if !preserve_gaps || (from <= *end && *start <= to) => { + *start = (*start).min(from); + *end = (*end).max(to); + } + Self::One(previous) => *self = Self::Many(vec![*previous, (from, to)]), + Self::Many(ranges) => ranges.push((from, to)), + } + } + + fn merge(&mut self) { + if let Self::Many(ranges) = self { + ranges.sort_unstable(); + // dedup_by passes the later element first and removes it on true. + ranges.dedup_by(|next, previous| { + if next.0 > previous.1 { + return false; + } + previous.1 = previous.1.max(next.1); + true + }); + } + } + + fn as_slice(&self) -> &[(usize, usize)] { + match self { + Self::One(range) => std::slice::from_ref(range), + Self::Many(ranges) => ranges, + } + } +} + impl Batch { fn add(&mut self, shadow: &std::sync::Arc, address: usize, len: usize) { - let end = address + len; + if len == 0 && disjoint_refresh() { + return; + } + let range = (address, address + len); let key = std::sync::Arc::as_ptr(shadow) as usize; match self.index.get(&key) { - Some(&at) => { - let r = &mut self.refreshes[at]; - (r.1, r.2) = (r.1.min(address), r.2.max(end)); - } + Some(&at) => self.refreshes[at].1.add(range, disjoint_refresh()), None => { self.index.insert(key, self.refreshes.len()); - self.refreshes.push((shadow.clone(), address, end)); + self.refreshes.push((shadow.clone(), RefreshRanges::One(range))); } } } @@ -5214,23 +5262,26 @@ impl Batch { let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else { return; }; - let (shadow, from, to) = self.refreshes.swap_remove(at); + let (shadow, mut ranges) = self.refreshes.swap_remove(at); // The last entry took its place. 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); + ranges.merge(); + Self::update(&shadow, &ranges); } - /// Brings `[from, to)` of a copy up to date, timed. - fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) { - let started = std::time::Instant::now(); - let copied = shadow.update(from, to - from); - let us = started.elapsed().as_micros() as u64; - #[cfg(feature = "diagnostics")] - crate::copystat::range(from, to - from, us, 0); - PREPARING[0].fetch_add(us, Ordering::Relaxed); - PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + /// Brings each requested range of a copy up to date, timed. + fn update(shadow: &crate::shadow::Shadow, ranges: &RefreshRanges) { + for &(from, to) in ranges.as_slice() { + let started = std::time::Instant::now(); + let copied = shadow.update(from, to - from); + let us = started.elapsed().as_micros() as u64; + #[cfg(feature = "diagnostics")] + crate::copystat::range(from, to - from, us, 0); + PREPARING[0].fetch_add(us, Ordering::Relaxed); + PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + } } /// Whether `staging` is still to be refreshed in this submission (and @@ -5248,16 +5299,19 @@ impl Batch { fn flush(&mut self) { self.index.clear(); - // One write-watch asking for the copies that lie close together, - // not one per copy. - let ahead = self.refreshes.len() > 1; + for (_, ranges) in &mut self.refreshes { + ranges.merge(); + } + // One write-watch asking for ranges that lie close together. + let ahead = self.refreshes.len() > 1 + || self.refreshes.first().is_some_and(|(_, ranges)| ranges.as_slice().len() > 1); if ahead { let started = std::time::Instant::now(); let ranges: Vec<(usize, usize)> = self .refreshes .iter() - .filter(|r| !r.0.unwatched()) - .map(|r| (r.1, r.2)) + .filter(|(shadow, _)| !shadow.unwatched()) + .flat_map(|(_, ranges)| ranges.as_slice().iter().copied()) .collect(); crate::watch::ask_ahead(&ranges); PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); @@ -5271,14 +5325,14 @@ impl Batch { let jobs: Vec> = self .refreshes .drain(..) - .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box) + .map(|(shadow, ranges)| Box::new(move || Self::update(&shadow, &ranges)) 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 { - for (shadow, from, to) in self.refreshes.drain(..) { - Self::update(&shadow, from, to); + for (shadow, ranges) in self.refreshes.drain(..) { + Self::update(&shadow, &ranges); } } if ahead { @@ -6409,9 +6463,60 @@ mod spare { #[cfg(test)] mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file - use super::Batch; + use super::{Batch, RefreshRanges}; use std::sync::Arc; + fn assert_refresh_range_union(requests: &[(usize, usize)], expected: &[(usize, usize)]) { + let (&first, rest) = requests.split_first().unwrap(); + let mut ranges = RefreshRanges::One(first); + for &request in rest { + ranges.add(request, true); + } + + ranges.merge(); + assert_eq!(ranges.as_slice(), expected, "requests: {requests:?}"); + ranges.merge(); + assert_eq!(ranges.as_slice(), expected, "second merge of {requests:?}"); + } + + #[test] + fn refresh_ranges_merges_adjacent_inline_ranges() { + for requests in [[(10, 20), (20, 30)], [(20, 30), (10, 20)]] { + assert_refresh_range_union(&requests, &[(10, 30)]); + } + } + + #[test] + fn refresh_ranges_merges_accumulated_ranges() { + let cases: &[(&[(usize, usize)], &[(usize, usize)])] = &[ + // Disjoint ranges added in reverse order. + (&[(30, 40), (10, 20)], &[(10, 20), (30, 40)]), + // Adjacency, containment, and a duplicate after promotion to Many. + ( + &[(30, 40), (10, 20), (20, 25), (12, 16), (10, 20)], + &[(10, 25), (30, 40)], + ), + // A bridge closes a previously disjoint gap. + (&[(30, 40), (10, 20), (20, 30)], &[(10, 40)]), + // Chained overlaps collapse while the final gap stays open. + ( + &[(50, 60), (10, 20), (35, 55), (18, 30), (28, 40), (75, 85)], + &[(10, 60), (75, 85)], + ), + ]; + for &(requests, expected) in cases { + assert_refresh_range_union(requests, expected); + } + } + + #[test] + fn refresh_ranges_keep_the_bounding_span_by_default() { + let mut ranges = RefreshRanges::One((30, 40)); + ranges.add((10, 20), false); + ranges.merge(); + assert_eq!(ranges.as_slice(), &[(10, 40)]); + } + #[test] fn a_texture_is_checked_once_per_submission() { let mut batch = Batch::default(); @@ -6441,6 +6546,119 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at assert!(next.texture_due(&a)); } + #[cfg(feature = "diagnostics")] + #[test] + #[ignore = "dedicated host process, compares hardware or WARP at the requested switch setting"] + fn disjoint_refresh_leaves_the_dirty_gap_pending() { + use super::{ + CreateDXGIFactory2, DXGI_ADAPTER_FLAG_SOFTWARE, DXGI_CREATE_FACTORY_FLAGS, + IDXGIAdapter1, IDXGIFactory4, Ordering, PREPARING, disjoint_refresh, host, + }; + use crate::{shadow, watch::PAGE}; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, + VirtualFree, + }; + + let host = host().expect("requested host device"); + // SAFETY: inspect the DXGI adapter for this specific D3D12 device. + let adapter = unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap(); + factory + .EnumAdapterByLuid::(host.device.GetAdapterLuid()) + .unwrap() + .GetDesc1() + .unwrap() + }; + let software = adapter.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0; + assert_eq!(software, std::env::var_os("VICTORY_D3D12_WARP").is_some()); + let name = String::from_utf16_lossy(adapter.Description.split(|&n| n == 0).next().unwrap()); + println!("adapter={name}, disjoint_refresh={}", disjoint_refresh()); + + const MEM_WRITE_WATCH: u32 = 0x20_0000; + const SIZE: usize = 3 * PAGE; + // SAFETY: a new committed, write-watched allocation owned by the test. + let title = unsafe { + VirtualAlloc( + std::ptr::null(), + SIZE, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + } as usize; + assert_ne!(title, 0); + let fill_page = move |page: usize, value: u8| { + assert!(page < 3); + // SAFETY: the test retains the committed allocation until all lists finish. + unsafe { ((title + page * PAGE) as *mut u8).write_bytes(value, PAGE) }; + }; + shadow::register(title, title as u64, SIZE as u64); + let shadow = shadow::find(title as u64, SIZE as u64).expect("shared shadow buffer"); + + let submit = |ranges: &[(usize, usize)], write: bool| { + let list = host.new_list().unwrap(); + let readback = host.read_back_buffer(SIZE as u64).unwrap(); + let copied = || PREPARING[1].load(Ordering::Relaxed); + let before = copied(); + for &(offset, len) in ranges { + shadow.refresh(&list, (title + offset) as u64, len as u64); + } + if write { + shadow.gpu_writes(&list, title as u64, 4); + list.defer_host(move || { + assert_eq!(copied() - before, (2 * PAGE) as u64, "GPU write drains both ranges"); + }); + // A title write after the declaration makes the third page stale again. + list.defer(move || fill_page(2, 66)); + shadow.refresh(&list, (title + 2 * PAGE) as u64, PAGE as u64); + } + // SAFETY: both buffers cover SIZE bytes and live through synchronous execution. + unsafe { list.list.CopyBufferRegion(&readback, 0, &shadow.buffer, 0, SIZE as u64) }; + let mut data = vec![0u8; SIZE]; + list.defer_read_back(readback, data.as_mut_ptr(), [SIZE, 1, SIZE]); + list.close(); + host.execute(&[&list]); + let markers = std::array::from_fn(|page| { + let bytes = &data[page * PAGE..(page + 1) * PAGE]; + assert!(bytes.iter().all(|&byte| byte == bytes[0]), "page {page} is uniform"); + bytes[0] + }); + (copied() - before, markers) + }; + + for (page, value) in [1, 2, 3].into_iter().enumerate() { + fill_page(page, value); + } + assert_eq!(submit(&[(0, SIZE)], false), (SIZE as u64, [1, 2, 3])); + for (page, value) in [11, 22, 33].into_iter().enumerate() { + fill_page(page, value); + } + let first = submit(&[(2 * PAGE, PAGE), (0, PAGE)], false); + let gap = submit(&[(PAGE, PAGE)], false); + + fill_page(0, 44); + let overlap = submit(&[(PAGE / 2, PAGE / 2), (0, 3 * PAGE / 4)], false); + fill_page(0, 55); + fill_page(2, 60); + let write = submit(&[(0, PAGE), (2 * PAGE, PAGE)], true); + + drop(shadow); + shadow::unregister(title, title as u64); + // SAFETY: the allocation is no longer used by any list or shadow. + assert_ne!(unsafe { VirtualFree(title as *mut _, 0, MEM_RELEASE) }, 0); + + println!("copied bytes and page contents: first {first:?}, gap {gap:?}, overlap {overlap:?}, write {write:?}"); + assert_eq!(overlap, (PAGE as u64, [44, 22, 33])); + assert_eq!(write, (SIZE as u64, [55, 22, 66])); + if disjoint_refresh() { + assert_eq!(first, ((2 * PAGE) as u64, [11, 2, 33])); + assert_eq!(gap, (PAGE as u64, [11, 22, 33])); + } else { + assert_eq!(first, (SIZE as u64, [11, 22, 33])); + assert_eq!(gap, (0, [11, 22, 33])); + } + } + /// The hashing a submission does for textures in physical-page memory, /// with every list checking the textures it samples (before) and with /// each checked once (after). Run with