diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index c7b390b1d8..3a0cc153b4 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -40,38 +40,52 @@ pub(crate) struct Shadow { /// Ranges shaders of a submission not yet copied back may be writing: /// title memory there is older than the copy. pending: Mutex>, - /// The copy's bytes before the submission ran, from an offset on, - /// covering the ranges its shaders write: what the GPU wrote differs. - before: Mutex)>>, + /// The copy's bytes before the submission ran, by title page, covering + /// the ranges its shaders write: what the GPU wrote differs. + before: Mutex, } -/// Snapshot memory kept for reuse (already touched, so no page faults). -static POOL: Mutex>> = Mutex::new(Vec::new()); - -/// An empty buffer with room for `n` bytes, from the pool if it has one. -fn pooled(n: usize) -> Vec { - let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); - let fit = pool - .iter() - .enumerate() - .filter(|(_, v)| v.capacity() >= n) - .min_by_key(|(_, v)| v.capacity()) - .map(|(i, _)| i); - let mut v = match fit { - Some(i) => pool.swap_remove(i), - None => Vec::with_capacity(n), - }; - v.clear(); - v +/// A copy's bytes before a submission ran. +#[derive(Default)] +struct Before { + /// By title page. + pages: BTreeMap, + /// The ranges taken (offsets in the copy, merged where they meet): a + /// range declared again (the world's are, dozens of times) is inside + /// one and needs no walk over its pages. + spans: Vec<(usize, usize)>, +} + +/// A title page's bytes in the copy before the submission ran: `[lo, hi)` +/// of `bytes` (offsets in the page; a page's buffer is a page long). +struct Snap { + lo: usize, + hi: usize, + bytes: Box<[u8]>, } -/// Returns a snapshot buffer to the pool (at most 8 kept, the largest). -fn give_back(v: Vec) { - let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); - pool.push(v); - if pool.len() > 8 { - pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); - pool.truncate(8); +/// Page buffers kept for reuse (already touched, so no page faults). A +/// snapshot as one buffer grown to the submission's bounding range took a +/// fresh buffer whenever the few kept were in use or too small, and copied +/// all of the old one into it at each growth. +static PAGES: Mutex>> = Mutex::new(Vec::new()); +/// At most this many page buffers kept (256 MiB). +const KEPT: usize = 4096; + +/// A page buffer, from the pool if it has one. +fn page_buffer() -> Box<[u8]> { + let kept = PAGES.lock().unwrap_or_else(|e| e.into_inner()).pop(); + kept.unwrap_or_else(|| vec![0; PAGE].into_boxed_slice()) +} + +/// Returns page buffers to the pool. +fn give_back(buffers: impl IntoIterator>) { + let mut pool = PAGES.lock().unwrap_or_else(|e| e.into_inner()); + for b in buffers { + if pool.len() >= KEPT { + break; + } + pool.push(b); } } @@ -144,40 +158,72 @@ impl Shadow { /// At submission, after the range's refresh: a submitted list's shaders /// write this range. Its bytes are kept to tell later what the GPU wrote: - /// one snapshot per copy and submission, grown to cover every range the - /// submission declares (the world declares overlapping views of its - /// 174 MB heap dozens of times), in reused memory (fresh snapshots cost - /// ~2.3 million page faults per world frame). + /// per title page and submission, each page's part grown to cover every + /// range the submission declares in it (the world declares overlapping + /// views of its 174 MB heap dozens of times), parts newly covered taken + /// from the copy as it is now, in reused page buffers. pub(crate) fn writing(&self, address: usize, len: usize) { self.pending .lock() .unwrap_or_else(|e| e.into_inner()) .push((address, address + len)); let (from, to) = self.inside(address, len); - // SAFETY: inside the mapping. - let host = |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) }; - let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); - let (start, end) = match &*before { - Some((at, bytes)) => ((*at).min(from), (at + bytes.len()).max(to)), - None => (from, to), + let start = self.start as usize; + // In-page offsets `[a, b)` of `page`, from the copy. + // SAFETY: inside the mapping (the caller passes offsets in the buffer). + let host = |page: usize, a: usize, b: usize| unsafe { + std::slice::from_raw_parts(self.data.add(page * PAGE + a - start), b - a) }; - if let Some((at, bytes)) = &*before - && (*at, at + bytes.len()) == (start, end) - { + let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let before = &mut *before; + if from >= to || before.spans.iter().any(|&(a, b)| a <= from && to <= b) { return; } - // Parts newly covered from the copy, the rest as it was taken. - let mut grown = pooled(end - start); - match before.take() { - Some((at, bytes)) => { - grown.extend_from_slice(host(start, at)); - grown.extend_from_slice(&bytes); - grown.extend_from_slice(host(at + bytes.len(), end)); - give_back(bytes); + // An earlier snapshot can span a gap that was not declared yet. + // Capture its refresh now, rather than treat it as a later GPU write. + let fresh = outside(from, to, before.spans.clone()); + let (mut a, mut b) = (from, to); + before.spans.retain(|&(x, y)| { + let meets = x <= b && a <= y; + if meets { + (a, b) = (a.min(x), b.max(y)); + } + !meets + }); + before.spans.push((a, b)); + let mut at = from; + while at < to { + let (page, lo) = ((start + at) / PAGE, (start + at) % PAGE); + let hi = lo + (PAGE - lo).min(to - at); + let snap = before.pages.entry(page).or_insert_with(|| Snap { + lo, + hi: lo, + bytes: page_buffer(), + }); + let previous = (snap.lo, snap.hi); + if lo < snap.lo { + snap.bytes[lo..snap.lo].copy_from_slice(host(page, lo, snap.lo)); + snap.lo = lo; } - None => grown.extend_from_slice(host(start, end)), + if hi > snap.hi { + let from = snap.hi.max(snap.lo); + snap.bytes[from..hi].copy_from_slice(host(page, from, hi)); + snap.hi = hi; + } + // Newly covered edges were copied above. Refresh only fresh + // portions inside the old extent; previously declared bytes + // must keep the original snapshot across overlapping ranges. + let page_start = page * PAGE; + for &(a, b) in &fresh { + let a = (start + a).max(page_start + previous.0); + let b = (start + b).min(page_start + previous.1); + if a < b { + let (a, b) = (a - page_start, b - page_start); + snap.bytes[a..b].copy_from_slice(host(page, a, b)); + } + } + at += hi - lo; } - *before = Some((start, grown)); } /// After the submission ran: copies the bytes its shaders wrote back @@ -192,25 +238,28 @@ impl Shadow { let mut written = 0; let (from, to) = self.inside(address, len); let start = self.start as usize; - if let Some((taken, before)) = &*snapshot - && *taken <= from - && to <= taken + before.len() - && from < to - { - let before = &before[from - taken..to - taken]; - // By 64 KiB piece: the copy compared with its bytes before the + if from < to { + // By title page: the copy compared with its bytes before the // submission, title memory read only where the GPU wrote. - const PIECE: usize = 64 << 10; - let mut title = vec![0u8; PIECE]; + let mut scratch = page_buffer(); let mut synced = Vec::new(); let mut at = from; while at < to { - let n = (PIECE - (start + at) % PIECE).min(to - at); + let (page, lo) = ((start + at) / PAGE, (start + at) % PAGE); + let n = (PAGE - lo).min(to - at); + let Some(snap) = snapshot + .pages + .get(&page) + .filter(|s| s.lo <= lo && lo + n <= s.hi) + else { + at += n; + continue; + }; // SAFETY: inside the mapping; only the submitting thread // writes it. let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; - let old = &before[at - from..at - from + n]; - let title = &mut title[..n]; + let old = &snap.bytes[lo..lo + n]; + let title = &mut scratch[..n]; if host != old && crate::host::read_into((start + at) as *const u8, title) { // Title memory with the GPU's bytes put in; the copy // takes the title's bytes in turn. @@ -231,6 +280,7 @@ impl Shadow { } at += n; } + give_back([scratch]); // Pages made equal to title memory are current in the copy, so // our own write is not taken for the title's; others keep what // they had (a title write there shows at the next refresh). @@ -251,10 +301,9 @@ impl Shadow { // submission runs at a time), and the snapshot with the last range. let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); pending.retain(|&r| r != (address, address + len)); - if pending.is_empty() - && let Some((_, bytes)) = snapshot.take() - { - give_back(bytes); + if pending.is_empty() { + let taken = std::mem::take(&mut *snapshot); + give_back(taken.pages.into_values().map(|s| s.bytes)); } written } @@ -365,6 +414,20 @@ impl Shadow { } } +/// Portions not yet declared by this submission, in copy-relative offsets. +fn outside(from: usize, to: usize, mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + ranges.sort_unstable(); + let (mut at, mut parts) = (from, Vec::new()); + for (a, b) in ranges { + if at < to && a > at { + parts.push((at, a.min(to))); + } + at = at.max(b); + } + if at < to { parts.push((at, to)); } + parts +} + struct Entry { end: u64, shadow: Option>, @@ -497,3 +560,122 @@ pub(crate) fn near(va: u64) -> String { } text } + +#[cfg(test)] +mod tests { + use super::*; + + /// A copy of title memory `[at, at + len)` holding the same bytes, if + /// there is a host device. + fn shadow_of(at: usize, len: usize) -> Option { + let (buffer, data) = host()?.shared_buffer((len as u64).next_multiple_of(PAGE as u64))?; + // SAFETY: the mapping holds `len` bytes; the title memory is ours. + unsafe { std::ptr::copy_nonoverlapping(at as *const u8, data, len) }; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + Some(Shadow::new(buffer, data, gpu, at as u64, len as u64)) + } + + /// Two overlapping ranges shaders write, declared with a refresh in + /// between: only the bytes the GPU changed go back, the title's own + /// writes meanwhile stay, and the page buffers return to the pool. + #[test] + fn copy_back_takes_only_what_the_gpu_wrote() { + let mut memory = vec![1u8; 4 * PAGE]; + // Off a page boundary, over three title pages. + let base = (memory.as_mut_ptr() as usize).next_multiple_of(PAGE) + 100; + let len = 2 * PAGE + 500; + let Some(shadow) = shadow_of(base, len) else { + return; + }; + // SAFETY: offsets inside the title range and the copy. + let title = |at: usize| unsafe { (base as *mut u8).add(at) }; + // SAFETY: as above. + let host = |at: usize| unsafe { shadow.data.add(at) }; + // SAFETY: (all writes below) bytes of the title range and the copy, + // which nothing else uses. + unsafe { + shadow.writing(base + 10, PAGE + 10); + // A refresh next to the first range, in its last page. + title(PAGE + 100).write(7); + host(PAGE + 100).write(7); + shadow.writing(base + PAGE + 50, PAGE + 50); + // The GPU writes in both ranges; the title writes meanwhile. + host(20).write(0xaa); + host(PAGE + 200).write(0xbb); + title(30).write(0xcc); + } + assert!(shadow.copy_back(base + 10, PAGE + 10) > 0); + assert!(shadow.copy_back(base + PAGE + 50, PAGE + 50) > 0); + // SAFETY: as above. + unsafe { + assert_eq!(title(20).read(), 0xaa); + assert_eq!(title(PAGE + 200).read(), 0xbb); + assert_eq!(title(30).read(), 0xcc, "the title's own write stays"); + assert_eq!(host(30).read(), 0xcc, "and the copy takes it"); + assert_eq!(title(PAGE + 100).read(), 7); + assert_eq!(title(40).read(), 1); + } + assert!(shadow.before.lock().unwrap().pages.is_empty()); + assert!(PAGES.lock().unwrap().len() >= 3); + drop(memory); + } + + /// A range declared again, or inside one declared, takes nothing new. + #[test] + fn declaring_a_range_again_keeps_its_snapshot() { + let memory = vec![3u8; 3 * PAGE]; + let base = memory.as_ptr() as usize; + let Some(shadow) = shadow_of(base, 3 * PAGE) else { + return; + }; + shadow.writing(base, 2 * PAGE); + // SAFETY: a byte of the copy, which nothing else uses: a GPU write + // between two dispatches declaring the range. + unsafe { shadow.data.add(5).write(9) }; + shadow.writing(base, 2 * PAGE); + shadow.writing(base + 4, 100); + { + let before = shadow.before.lock().unwrap(); + assert_eq!(before.spans, [(0, 2 * PAGE)]); + let at = base + 5; + assert_eq!(before.pages[&(at / PAGE)].bytes[at % PAGE], 3); + } + shadow.copy_back(base, 2 * PAGE); + shadow.copy_back(base + 4, 100); + // SAFETY: title memory of ours. + assert_eq!(unsafe { (base as *const u8).add(5).read() }, 9); + assert!(shadow.before.lock().unwrap().pages.is_empty()); + drop(memory); + } + + /// Refreshing an undeclared gap inside one snapshot page must not be + /// mistaken for a GPU write and overwrite a later CPU write. + #[test] + fn refreshed_gap_inside_a_page_keeps_the_titles_newer_byte() { + let mut memory = vec![0u8; 3 * PAGE]; + let base = (memory.as_mut_ptr() as usize).next_multiple_of(PAGE); + let Some(shadow) = shadow_of(base, PAGE) else { return }; + shadow.writing(base, 16); + shadow.writing(base + 128, 16); + // SAFETY: these bytes belong to the test and its mapped copy. + unsafe { + (base as *mut u8).add(64).write(1); + shadow.data.add(64).write(1); // mimic the middle range's refresh + } + shadow.writing(base + 64, 16); + // SAFETY: the CPU changes the middle byte after the snapshot; an + // actual GPU change is mimicked in the first range. + unsafe { + (base as *mut u8).add(64).write(2); + shadow.data.add(3).write(9); + } + for at in [base, base + 128, base + 64] { shadow.copy_back(at, 16); } + // SAFETY: still inside memory, which remains live for this test. + unsafe { + assert_eq!((base as *const u8).add(64).read(), 2, "CPU's newer byte"); + assert_eq!((base as *const u8).add(3).read(), 9, "GPU's actual write"); + } + } + +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 1cbe2b7522..e965aa64cc 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -10,7 +10,11 @@ //! copy leaves each 64 KiB block it took read-only, and our vectored handler //! takes the first write to it: it notes the block as written and gives the //! write access back. The runtime tells us when it maps or unmaps views -//! ([`title_memory_remapped`]), which resets their protection. +//! ([`title_memory_remapped`]), which resets their protection. Blocks found +//! unmapped are not asked about again until it maps them: view memory +//! comes from placeholders, which only the runtime's mapping fills. +//! shortcut: so memory committed otherwise into such a block (a range +//! reaching from a view into a plain reservation) is not seen. //! //! shortcut: writes into physical pages through another view (xmem's //! `write_physical`, DirectStorage's page destinations) are not seen at @@ -108,11 +112,19 @@ struct Guards { protected: BTreeSet, /// Of those, the ones not written since a copy took them. clean: BTreeSet, + /// Blocks found unmapped (not committed) when a copy took them: the + /// copy holds their zeros until the runtime maps them + /// ([`title_memory_remapped`]). Without this, every asking found them + /// "written" again (they cannot be made read-only) and the copy read + /// them page by page through the kernel's failing reads, hundreds of + /// MB per world frame. + absent: BTreeSet, } static GUARDS: Mutex = Mutex::new(Guards { protected: BTreeSet::new(), clean: BTreeSet::new(), + absent: BTreeSet::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { @@ -137,7 +149,7 @@ fn guard(start: usize, end: usize) -> Option> { let mut run: Option = None; let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); for block in first..=last { - let open = block < last && !g.clean.contains(&block); + let open = block < last && !g.clean.contains(&block) && !g.absent.contains(&block); if open { written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE); if g.protected.contains(&block) { @@ -156,7 +168,8 @@ fn guard(start: usize, end: usize) -> Option> { } /// Makes blocks `[from, to)` read-only and notes them guarded and clean; -/// block by block if they span views, leaving out any that fail (unmapped). +/// block by block if they span views, leaving out any that fail, and +/// noting those not committed (unmapped) absent. fn protect(g: &mut Guards, from: usize, to: usize) { use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; let set = |from: usize, to: usize| { @@ -182,10 +195,22 @@ fn protect(g: &mut Guards, from: usize, to: usize) { for block in from..to { if set(block, block + 1) { note(g, block, block + 1); + } else if unmapped(block * BLOCK) { + g.absent.insert(block); } } } +/// Whether nothing is committed at `at` (a placeholder between views). +fn unmapped(at: usize) -> bool { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + n != 0 && info.State != MEM_COMMIT +} + /// Gives write access back to the guarded blocks of `[start, end)` and /// notes them written; true if any was guarded. fn open(g: &mut Guards, start: usize, end: usize) -> bool { @@ -214,14 +239,16 @@ pub fn writing(at: usize, len: usize) { } /// The runtime mapped or unmapped title memory `[at, at + len)`: what it -/// shows is new and read-write, so it is no longer guarded. +/// shows is new and read-write, so it is no longer guarded (nor known +/// unmapped). pub fn title_memory_remapped(at: usize, len: usize) { let mut g = guards(); - let blocks: Vec = g - .protected - .range(at / BLOCK..(at + len).div_ceil(BLOCK)) - .copied() - .collect(); + let range = at / BLOCK..(at + len).div_ceil(BLOCK); + let absent: Vec = g.absent.range(range.clone()).copied().collect(); + for block in absent { + g.absent.remove(&block); + } + let blocks: Vec = g.protected.range(range).copied().collect(); for block in blocks { g.protected.remove(&block); g.clean.remove(&block); @@ -357,14 +384,111 @@ mod tests { let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) }; file.read(into).is_ok_and(|n| n == 13) }; - assert!(!read(&mut file), "the kernel does not fault into our handler"); + assert!( + !read(&mut file), + "the kernel does not fault into our handler" + ); writing(view + 100, 13); assert!(read(&mut file)); // SAFETY: the bytes just read. - assert_eq!(unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, b"from the disk"); - assert_eq!(guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect())); + let landed = unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }; + assert_eq!(landed, b"from the disk"); + assert_eq!( + guard(view, view + 2 * BLOCK), + Some((view / PAGE..view / PAGE + 1).collect()) + ); // SAFETY: our view. - unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) }; + unsafe { + UnmapViewOfFile( + windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { + Value: view as *mut _, + }, + ) + }; title_memory_remapped(view, 2 * BLOCK); } + + /// Blocks of a placeholder between views are reported once, then not + /// again (they cannot be guarded) until the runtime maps them. + #[test] + fn unmapped_blocks_are_reported_once_until_mapped() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, + MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2, + VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder of three blocks and a pagefile + // section of two; block 0 shows the section's first block, as the + // runtime maps physical pages. + let (p, section) = unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + 3 * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + (p, section) + }; + let map = |block: usize| { + // SAFETY: splits the placeholder at the block and maps the + // section's block there. + let view = unsafe { + VirtualFree( + (p + block * BLOCK) as *mut _, + BLOCK, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + section, + GetCurrentProcess(), + (p + block * BLOCK) as *const _, + (block * BLOCK) as u64, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p + block * BLOCK); + view + }; + let first = map(0); + let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; + let all: Vec = (0..3).flat_map(pages).collect(); + assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); + assert_eq!( + guard(p, p + 3 * BLOCK), + Some(Vec::new()), + "nothing written since" + ); + let second = map(1); + title_memory_remapped(p + BLOCK, BLOCK); + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + // SAFETY: our views and placeholder. + unsafe { + UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); + UnmapViewOfFile2(GetCurrentProcess(), second, MEM_PRESERVE_PLACEHOLDER); + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + windows_sys::Win32::Foundation::CloseHandle(section); + } + title_memory_remapped(p, 3 * BLOCK); + } }