From 41af42e5fd3a5d68df60a1bb60b325dc8ab45ad1 Mon Sep 17 00:00:00 2001 From: wrothgaril <211408787+wrothgaril@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:43:12 +0100 Subject: [PATCH 1/4] GPU: remember unmapped guarded view blocks until the runtime maps them A copy of view memory (physical-page views, which cannot be write-watched) guards each 64 KiB block it took read-only. A block that is not mapped (a placeholder between views of a GPU heap) cannot be made read-only, so it never became clean: every asking reported it written again, and the copy read it through the per-page fallback, whose failing kernel reads cost hundreds of ms per world frame. Note such blocks absent (only after VirtualProtect fails and the block is not committed). An absent block is not reported again until title_memory_remapped, which the runtime calls after mapping or unmapping views, clears it. The copy keeps the zeros it took. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 150 +++++++++++++++++++++++++++++--- 1 file changed, 137 insertions(+), 13 deletions(-) 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); + } } From 5ff3a3585a91738688249def26e08b9bc3a05d40 Mon Sep 17 00:00:00 2001 From: wrothgaril <211408787+wrothgaril@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:04:41 +0100 Subject: [PATCH 2/4] GPU: keep what shaders may write by page, in reused page buffers Before a submission runs, the bytes of each range its shaders write are kept to tell afterwards what the GPU changed. They were one buffer per copy, grown to the bounding range of every range the submission declared: each growth took a buffer from a pool of eight (a fresh one, page faults and all, when none was free and big enough) and copied the whole old snapshot into it. Keep them per title page instead, in 64 KiB buffers from a pool of up to 4,096, each page's part grown as ranges in it are declared (newly covered bytes taken from the copy as it is then, as before). A range inside one already taken returns at once. Copy-back compares page by page as it did by 64 KiB piece, with its scratch page from the same pool. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/shadow.rs | 256 +++++++++++++++++++++++-------- 1 file changed, 189 insertions(+), 67 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index c7b390b1d8..a6dd206377 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]>, +} + +/// 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 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); +/// 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,56 @@ 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); + 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(), + }); + if lo < snap.lo { + snap.bytes[lo..snap.lo].copy_from_slice(host(page, lo, snap.lo)); + snap.lo = lo; + } + 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; } - None => grown.extend_from_slice(host(start, end)), + at += hi - lo; } - *before = Some((start, grown)); } /// After the submission ran: copies the bytes its shaders wrote back @@ -192,25 +222,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 +264,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 +285,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 } @@ -497,3 +530,92 @@ 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); + } +} From b11ab3134496ae956b405c273feaf2fc31c39879 Mon Sep 17 00:00:00 2001 From: swarm Date: Tue, 24 Nov 2026 02:50:19 -0500 Subject: [PATCH 3/4] Port Shadow snapshot preservation controls --- crates/victory-gpu/src/shadow.rs | 130 +++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index a6dd206377..a9d4388f41 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -619,3 +619,133 @@ mod tests { drop(memory); } } + +#[cfg(test)] +mod snapshot_preservation_controls { + use super::*; + + /// Three pages of title memory on page bounds (plain heap memory, so + /// not write-watched: refreshes copy whole ranges) and their host + /// copy; `None` without a host GPU. Returns the memory's owner, the + /// address of the first page and the copy. + fn title() -> Option<(Vec, usize, Shadow)> { + let memory = vec![0u8; 4 * PAGE]; + let base = (memory.as_ptr() as usize).next_multiple_of(PAGE); + let (buffer, data) = host()?.shared_buffer(3 * PAGE as u64)?; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let shadow = Shadow::new(buffer, data, gpu, base as u64, 3 * PAGE as u64); + Some((memory, base, shadow)) + } + + /// A write of one byte: the title's into its memory, or a shader's + /// into the copy. + fn poke(at: usize, value: u8) { + // SAFETY: the tests pass addresses inside the memory or the copy. + unsafe { (at as *mut u8).write_volatile(value) } + } + + fn peek(at: usize) -> u8 { + // SAFETY: as in `poke`. + unsafe { (at as *const u8).read_volatile() } + } + + /// A range declared after ranges on both sides of it, once the snapshot + /// already spans it: what its refresh brought into the copy is not a + /// shader's write, and does not go back over what the title wrote since. + #[test] + fn a_range_between_earlier_ones_keeps_the_titles_newer_bytes() { + let Some((_memory, base, s)) = title() else { + eprintln!("no GPU; Shadow snapshot control skipped"); + return; + }; + let (a, b, c) = (base, base + PAGE, base + 2 * PAGE); + let copy = |at: usize| s.data as usize + (at - base); + // An earlier submission read the middle page; the title has written + // it since. + s.update(b, PAGE); + poke(b + 5, 1); + poke(b + 6, 3); + // This submission's shaders write the outer pages, then the middle + // one: each range refreshed, then declared. + for at in [a, c, b] { + s.update(at, PAGE); + s.writing(at, PAGE); + } + assert_eq!(peek(copy(b + 5)), 1, "the refresh"); + // While the GPU runs: a shader writes two bytes, the title one. + poke(copy(a + 7), 9); + poke(copy(b + 9), 7); + poke(b + 5, 2); + for at in [a, c, b] { + s.copy_back(at, PAGE); + } + assert_eq!(peek(b + 5), 2, "the title's newer byte"); + assert_eq!(peek(b + 6), 3, "the title's byte from before"); + // What the shader wrote does go back, in either kind of range. + assert_eq!((peek(a + 7), peek(b + 9)), (9, 7)); + eprintln!("gap-range Shadow snapshot readback completed"); + assert!(s.before.lock().unwrap().pages.is_empty(), "the snapshot is done"); + } + + #[test] + fn a_gap_inside_one_page_keeps_the_titles_newer_bytes() { + let Some((_memory, base, s)) = title() else { + eprintln!("no GPU; Shadow snapshot control skipped"); + return; + }; + let (a, b, c) = (base, base + 256, base + 512); + let copy = |at: usize| s.data as usize + (at - base); + // An earlier submission read the middle page; the title has written + // it since. + s.update(b, 32); + poke(b + 5, 1); + poke(b + 6, 3); + // This submission's shaders write the outer pages, then the middle + // one: each range refreshed, then declared. + for at in [a, c, b] { + s.update(at, 32); + s.writing(at, 32); + } + assert_eq!(peek(copy(b + 5)), 1, "the refresh"); + // While the GPU runs: a shader writes two bytes, the title one. + poke(copy(a + 7), 9); + poke(copy(b + 9), 7); + poke(b + 5, 2); + for at in [a, c, b] { + s.copy_back(at, 32); + } + assert_eq!(peek(b + 5), 2, "the title's newer byte"); + assert_eq!(peek(b + 6), 3, "the title's byte from before"); + // What the shader wrote does go back, in either kind of range. + assert_eq!((peek(a + 7), peek(b + 9)), (9, 7)); + eprintln!("intra-page gap Shadow snapshot readback completed"); + assert!(s.before.lock().unwrap().pages.is_empty(), "the snapshot is done"); + } + + /// Two declared ranges that overlap: the first one's copy-back gives + /// the copy the title's bytes, which the second must not take for a + /// shader's and put back over what the title wrote in between. + #[test] + fn overlapping_ranges_keep_the_titles_newer_bytes() { + let Some((_memory, base, s)) = title() else { + eprintln!("no GPU; Shadow snapshot control skipped"); + return; + }; + let copy = |at: usize| s.data as usize + (at - base); + s.update(base, 2 * PAGE); + s.writing(base, PAGE); + s.writing(base, 2 * PAGE); + // While the GPU runs: a shader's byte and the title's, in one page. + poke(copy(base + 3), 9); + poke(base + 8, 1); + s.copy_back(base, PAGE); + assert_eq!((peek(base + 3), peek(base + 8)), (9, 1)); + // The title writes its byte again before the second range's turn. + poke(base + 8, 2); + s.copy_back(base, 2 * PAGE); + assert_eq!(peek(base + 8), 2, "the title's newer byte"); + assert_eq!(peek(base + 3), 9, "the shader's byte"); + eprintln!("overlapping-range Shadow snapshot readback completed"); + } +} From ddc47deee49f11ea4a72ab6b3f6d417a375a961c Mon Sep 17 00:00:00 2001 From: swarm Date: Tue, 24 Nov 2026 02:50:31 -0500 Subject: [PATCH 4/4] Preserve newer title bytes with paged Shadow snapshots --- crates/victory-gpu/src/shadow.rs | 63 ++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 23 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index a9d4388f41..73fe01c947 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -56,8 +56,8 @@ struct Before { 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). +/// A title page's snapshot before the submission ran. The page-local +/// bounds `[lo, hi)` can contain gaps outside the declared write spans. struct Snap { lo: usize, hi: usize, @@ -179,6 +179,7 @@ impl Shadow { if from >= to || before.spans.iter().any(|&(a, b)| a <= from && to <= b) { return; } + let new = outside(from, to, before.spans.clone()); let (mut a, mut b) = (from, to); before.spans.retain(|&(x, y)| { let meets = x <= b && a <= y; @@ -188,25 +189,22 @@ impl Shadow { !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(), - }); - if lo < snap.lo { - snap.bytes[lo..snap.lo].copy_from_slice(host(page, lo, snap.lo)); - snap.lo = lo; - } - 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; + for (mut at, to) in new { + 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, + bytes: page_buffer(), + }); + // Save only newly declared bytes. A gap within a page may be + // refreshed before it is declared for writing. + snap.bytes[lo..hi].copy_from_slice(host(page, lo, hi)); + snap.lo = snap.lo.min(lo); + snap.hi = snap.hi.max(hi); + at += hi - lo; } - at += hi - lo; } } @@ -233,7 +231,7 @@ impl Shadow { let n = (PAGE - lo).min(to - at); let Some(snap) = snapshot .pages - .get(&page) + .get_mut(&page) .filter(|s| s.lo <= lo && lo + n <= s.hi) else { at += n; @@ -242,18 +240,21 @@ impl Shadow { // 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 = &snap.bytes[lo..lo + n]; + let old = &mut 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. let mut changed = false; - for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) { + for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old.iter_mut()) { if *h != *o && *t != *h { *t = *h; changed = true; } *h = *t; + // A later overlapping range must not see merged + // title bytes as fresh GPU writes. + *o = *t; } if changed { crate::watch::writing(start + at, n); @@ -398,6 +399,22 @@ impl Shadow { } } +/// The portions of a span not covered by earlier declarations. +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, e) in ranges { + if at < to && a > at { + parts.push((at, a.min(to))); + } + at = at.max(e); + } + if at < to { + parts.push((at, to)); + } + parts +} + struct Entry { end: u64, shadow: Option>,