From 5f21abda742c87fb0e855ae0d7c09ed2c66f36f0 Mon Sep 17 00:00:00 2001 From: Davide Date: Fri, 27 Nov 2026 22:29:25 +0100 Subject: [PATCH 1/4] Windows of title memory that grow instead of 4 MiB each (VICTORY_WINDOW_GROW=1, off by default) A window outside buffers is a 4 MiB host buffer whatever is read, and all of it is resident: on an RTX 5080 (run nv-1127-k) 727 windows held 3,100 MB while what was asked for in them lay within 1,700 MB. A finer grid (VICTORY_WINDOW_KB=256 VICTORY_WINDOW_TAILS=1, run nv-1127-l) saved nothing: 3,060 MB of windows over 1,746 MB of title memory, because the descriptor slots made on the shorter windows kept them alive beside the longer ones. With VICTORY_WINDOW_GROW=1 a 4 MiB cell has one window, from the lowest to the highest 256 KiB step asked for (to the cell's end for an ask without a length). An ask past it makes a longer window that takes the place of the shorter one: - find gives the longer one from then on; - the pass over the heap makes again the slots that show the shorter one; - until nothing holds the shorter one, what is brought up to date or written through the longer one is through it too (Shadow::forward); - the shorter one is kept in TAKEN_OVER until no slot, list or pass holds it, then retired with the idle windows. The memory line (diagnostics) says how many windows grew, how many taken over are still held and their bytes, and how many heap slots moved. --- crates/victory-gpu/src/copystat.rs | 7 +- crates/victory-gpu/src/descriptor/host.rs | 20 ++ crates/victory-gpu/src/draw.rs | 9 +- crates/victory-gpu/src/shadow.rs | 233 ++++++++++++++++++++-- 4 files changed, 255 insertions(+), 14 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 948da3265..a4b71c389 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -949,10 +949,15 @@ fn log_memory() { tracing::info!( "memory, windows: the {:.0} MB of windows lie over {:.0} MB of title memory (the rest is \ memory that is in more than one window, and is copied once for each); host lists never \ - reset since they were made: {}", + reset since they were made: {}; windows grown (VICTORY_WINDOW_GROW): {} since the start, \ + {} taken over and still held {:.0} MB, {} slots of the heap moved to the longer one", mb(copies[3]), mb(crate::shadow::window_cover()), lists[3], + crate::shadow::GROWN[0].load(Relaxed), + crate::shadow::taken_over_held().0, + mb(crate::shadow::taken_over_held().1), + crate::shadow::GROWN[1].load(Relaxed), ); } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 475c5645d..af5bd8be7 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -4136,6 +4136,26 @@ impl HostHeap { Some(windows::core::Interface::as_raw(&shown) == windows::core::Interface::as_raw(buffer)) } + /// Whether host slot `index` shows a window of title memory that a longer + /// one took the place of (`crate::shadow::grow`). + pub(crate) fn shows_taken_over(&self, index: u32) -> bool { + crate::shadow::grow() + && crate::shadow::any_taken_over() + && self.kept_in(index).is_some_and(|shown| crate::shadow::taken_over(&shown)) + } + + /// Host slot `index` is made again by the next [`HostHeap::mirror`] of + /// it, as if the title had written it: what it showed is retired when + /// the new view is kept. + pub(crate) fn make_again(&self, index: u32) { + if index >= self.count { + return; + } + let _held = self.made.lock(index); + self.quick_is(index, 0); + self.made.set(index, 0); + } + /// What the queue of textures picked by index knows of title slot /// `index` at `frame`, in a few words (diagnostics). #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index cfc3fe29c..1526b30d4 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1210,7 +1210,14 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho if host.copied_tabled(index, frame) { return None; } - let view = host.mirror(index, heap.handle(index)?, true)?; + let mut view = host.mirror(index, heap.handle(index)?, true)?; + // A slot made on a window a longer one took the place of is made + // again on the longer one (`crate::shadow::grow`). + if host.shows_taken_over(index) { + host.make_again(index); + view = host.mirror(index, heap.handle(index)?, true)?; + crate::shadow::GROWN[1].fetch_add(1, Ordering::Relaxed); + } // The copy the slot shows (`buffer_copy`), not the one the // view's range alone would find. let (shadow, address, len) = crate::descriptor::host::buffer_copy(&view)?; diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 0020ed52a..66c8f7135 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -105,6 +105,14 @@ pub(crate) struct Shadow { /// and the bytes from the buffer's first byte to `start` (the heap /// begins on a 64 KiB line; a title buffer need not). place: Option<(windows::Win32::Graphics::Direct3D12::ID3D12Heap, u64)>, + /// With [`grow`]: the windows of the same memory this one took the place + /// of, while anything still holds them (a descriptor slot made before, a + /// pass's kept range, a list): what is brought up to date or written + /// through this one is through them too, so whatever reads them reads + /// the same bytes ([`Shadow::forward`]). + before_me: Mutex>>, + /// With [`grow`]: a longer window took this one's place ([`TAKEN_OVER`]). + taken_over: std::sync::atomic::AtomicBool, } /// What a copy in the card's memory ([`cards`]) has beside the buffer @@ -3213,6 +3221,7 @@ pub(crate) fn window_use() -> [u64; 8] { /// again. Called before a submission starts, by the thread that submits. pub(crate) fn let_go_idle() { const IDLE_FRAMES: u64 = 4; + let_go_taken_over(); let gone: Vec> = { // Held from the look to the removal: `loose` hands a copy out // under the same lock, so none is handed out in between. @@ -3355,6 +3364,30 @@ impl Shadow { pub(crate) fn refresh(self: &Arc, list: &HostList, address: u64, len: u64) { let len = len.min(self.start + self.len - address); list.defer_refresh(self, address as usize, len as usize); + self.forward(address, len, |before, address, len| before.refresh(list, address, len)); + } + + /// With [`grow`]: `f` for each window this one took the place of that + /// is still held, with the part of `[address, address + len)` it holds. + fn forward(&self, address: u64, len: u64, f: impl Fn(&Arc, u64, u64)) { + if !grow() { + return; + } + let before: Vec> = { + let mut before = self.before_me.lock().unwrap_or_else(|e| e.into_inner()); + if before.is_empty() { + return; + } + before.retain(|w| w.strong_count() > 0); + before.iter().filter_map(std::sync::Weak::upgrade).collect() + }; + for shadow in before { + let from = address.max(shadow.start); + let to = (address + len).min(shadow.start + shadow.len); + if from < to { + f(&shadow, from, to - from); + } + } } /// The bytes of the host buffer. @@ -3398,6 +3431,8 @@ impl Shadow { wc: AtomicU8::new(0), mapped: false, place: None, + before_me: Mutex::default(), + taken_over: Default::default(), } } @@ -3418,6 +3453,9 @@ impl Shadow { /// before the submission (a copy per declared range and submission); /// a GPU-side dirty mask would save that if big ranges make it slow. pub(crate) fn gpu_writes(self: &Arc, list: &HostList, address: u64, len: u64) { + // A slot made before a longer window took the place of this one's + // window may be what the shaders write through. + self.forward(address, len, |before, address, len| before.gpu_writes(list, address, len)); // In place the shaders write title memory itself: no snapshot, no // compare, nothing to copy back, and no wait on its account. // shortcut: another host copy of the same bytes (a title buffer @@ -5596,7 +5634,96 @@ fn holder(windows: impl Iterator, address: u64, end: u64) -> /// Whether windows may be smaller than their 4 MiB cell (a finer grid, or /// tails): only then is there more than one window to choose from. fn fine() -> bool { - tails() || window() < WINDOW + !grow() && (tails() || window() < WINDOW) +} + +/// Whether a window covers only what was asked for in its 4 MiB cell, and +/// grows when more is (`VICTORY_WINDOW_GROW=1`; off by default). +/// +/// A window is the PC's memory, all of it, whatever is read (run +/// nv-1127-k, RTX 5080: 727 windows, 3,100 MB, all resident; between the +/// lowest and highest address asked for in each, 1,700 MB). Cut on a finer +/// grid (`VICTORY_WINDOW_KB`, `VICTORY_WINDOW_TAILS`) the same memory lay +/// in several windows held at once, each by the descriptor slots made on +/// it (nv-1127-l: 3,060 MB of windows over 1,746 MB of title memory). +/// +/// Here a cell has one window, from the lowest [`GROW_STEP`] asked for to +/// the highest (to the cell's end for an ask without a length, which reads +/// that far). An ask past it makes a longer window that takes the place of +/// the shorter one: [`find`] gives the longer one from then on, the pass +/// over the heap remakes the slots that show the shorter one +/// ([`taken_over`]), and until nothing holds the shorter one any more what +/// is brought up to date or written through the longer one is through it +/// too ([`Shadow::forward`]). +/// +/// shortcut: a slot of a draw's table made on the shorter window keeps it +/// until the title writes the slot again (it is brought up to date all the +/// same). +pub(crate) fn grow() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOW_GROW").is_some_and(|v| v == "1")) +} + +/// The steps a growing window's ends lie on: each step it grows by is a new +/// host buffer filled again, so not the 64 KiB page. +const GROW_STEP: u64 = TAIL_STEP; + +/// The windows a longer window took the place of, by their host buffer +/// ([`grow`]), kept here until nothing else holds them ([`let_go_taken_over`]). +/// A descriptor slot holds a window's buffer and not the copy: let go while +/// a slot still showed it, the copy would be brought up to date no more, +/// and the pass over the heap would not know the slot is to be made again. +static TAKEN_OVER: Mutex>> = Mutex::new(BTreeMap::new()); +/// How many there are (asked by every slot the pass over the heap looks at). +static TAKEN_OVER_N: AtomicU64 = AtomicU64::new(0); + +/// Windows grown since the start, and the slots of the heap moved to the +/// longer window. +pub(crate) static GROWN: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// Whether `buffer` is a window's that a longer window took the place of. +pub(crate) fn taken_over(buffer: &ID3D12Resource) -> bool { + use windows::core::Interface; + grow() + && TAKEN_OVER_N.load(Ordering::Relaxed) > 0 + && TAKEN_OVER.lock().unwrap_or_else(|e| e.into_inner()).contains_key(&(buffer.as_raw() as usize)) +} + +/// Whether any window was taken over and is still held. +pub(crate) fn any_taken_over() -> bool { + TAKEN_OVER_N.load(Ordering::Relaxed) > 0 +} + +/// Lets go of the windows taken over that only [`TAKEN_OVER`] holds: no list, +/// no pass's kept range, no newer window's [`Shadow::forward`] holds the +/// copy, and no descriptor slot its buffer. Called with [`let_go_idle`]. +fn let_go_taken_over() { + if !any_taken_over() { + return; + } + let gone: Vec> = { + let mut map = TAKEN_OVER.lock().unwrap_or_else(|e| e.into_inner()); + let free: Vec = map + .iter() + .filter(|(_, s)| Arc::strong_count(s) == 1 && crate::host::references(&s.buffer) == 1) + .map(|(&key, _)| key) + .collect(); + let gone: Vec> = free.into_iter().filter_map(|key| map.remove(&key)).collect(); + TAKEN_OVER_N.store(map.len() as u64, Ordering::Relaxed); + gone + }; + for shadow in gone { + LET_GO[0].fetch_add(1, Ordering::Relaxed); + LET_GO[1].fetch_add(shadow.len, Ordering::Relaxed); + crate::host::retire(shadow); + } +} + +/// For the memory line: windows taken over and still held, and their bytes. +#[cfg(feature = "diagnostics")] +pub(crate) fn taken_over_held() -> (u64, u64) { + let map = TAKEN_OVER.lock().unwrap_or_else(|e| e.into_inner()); + (map.len() as u64, map.values().map(|s| s.len).sum()) } /// For the memory line: the bytes of title memory the windows alive lie @@ -5730,6 +5857,9 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option Option Option> { // In place, if asked for and the window's memory can be opened: the // window is the title's own memory, with nothing to copy. if let Some(placed) = crate::port::place_for(start, len, true).or_else(|| crate::inplace::place_for(start, len, true)) { - let shadow = Arc::new(Shadow::placed(placed, start, len, true)); - note(&shadow); - map.insert((start, len), shadow.clone()); - return Some(shadow); + return Some(Arc::new(Shadow::placed(placed, start, len, true))); } // One buffer in the card's memory, filled by the CPU through the bus. if let Some((buffer, data)) = window_mapped_for(len) { @@ -5771,10 +5907,7 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option Option) -> (u64, u64) { + let (from, to) = (address & !(GROW_STEP - 1), reach.next_multiple_of(GROW_STEP)); + match now { + Some((start, len)) => (from.min(start), to.max(start + len)), + None => (from, to), + } +} + +/// [`loose`] with [`grow`]: the window of the ask's cell, grown first if it +/// does not hold the ask. +fn grown(address: u64, end: u64, unsized_ask: bool, note: &dyn Fn(&Shadow)) -> Option> { + let (cell, _) = window_of(address, end, WINDOW); + // An ask without a length reads from its address to its cell's end. + let reach = if unsized_ask { end.max(cell + WINDOW) } else { end }; + // A window that begins in the cell, or in the one below and reaches this + // far, and holds the ask. + let holding = |map: &BTreeMap<(u64, u64), Arc>| { + map.range((cell.saturating_sub(WINDOW), 0)..=(address, u64::MAX)) + .rev() + .find(|&(&(start, len), _)| start <= address && start + len >= reach) + .map(|(_, shadow)| shadow.clone()) + }; + if let Some(shadow) = holding(&LOOSE.read().unwrap_or_else(|e| e.into_inner())) { + note(&shadow); + return Some(shadow); + } + let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner()); + if let Some(shadow) = holding(&map) { + note(&shadow); + return Some(shadow); + } + // The cell's window now (one at most begins in a cell), which the new + // one takes in. + let now = map.range((cell, 0)..(cell + WINDOW, 0)).next().map(|(&key, shadow)| (key, shadow.clone())); + let (from, to) = grown_extent(address, reach, now.as_ref().map(|(key, _)| *key)); + let shadow = made_window(from, to - from)?; + if let Some((key, old)) = now { + use windows::core::Interface; + map.remove(&key); + let mut before = std::mem::take(&mut *old.before_me.lock().unwrap_or_else(|e| e.into_inner())); + before.retain(|w| w.strong_count() > 0); + before.push(Arc::downgrade(&old)); + *shadow.before_me.lock().unwrap_or_else(|e| e.into_inner()) = before; + if !old.taken_over.swap(true, Ordering::Relaxed) { + let mut taken = TAKEN_OVER.lock().unwrap_or_else(|e| e.into_inner()); + taken.insert(old.buffer.as_raw() as usize, old.clone()); + TAKEN_OVER_N.store(taken.len() as u64, Ordering::Relaxed); + } + shadow.asked[0].fetch_min(old.asked[0].load(Ordering::Relaxed), Ordering::Relaxed); + shadow.asked[1].fetch_max(old.asked[1].load(Ordering::Relaxed), Ordering::Relaxed); + shadow.unsized_asks.fetch_add(old.unsized_asks.load(Ordering::Relaxed), Ordering::Relaxed); + GROWN[0].fetch_add(1, Ordering::Relaxed); + } note(&shadow); - map.insert((start, len), shadow.clone()); + map.insert((from, to - from), shadow.clone()); Some(shadow) } @@ -5936,10 +6127,28 @@ mod write_combined_tests { #[cfg(test)] mod window_tests { use super::{ - WINDOW, cover, default_card_limits_mb, grid, holder, longest_tail, resolve_card_limits, - tail_of, window_of, + GROW_STEP, WINDOW, cover, default_card_limits_mb, grid, grown_extent, holder, longest_tail, + resolve_card_limits, tail_of, window_of, }; + /// A growing window holds what was asked on 256 KiB steps, takes in the + /// cell's window it replaces, and reaches the cell's end for an ask + /// without a length (whose reach the caller makes the cell's end). + #[test] + fn grown_windows_hold_the_asks_and_what_was_there() { + let cell = 0xd_1200_0000u64; + assert_eq!(GROW_STEP, 256 << 10); + // First ask, with a length: its steps only. + assert_eq!(grown_extent(cell + 0x5_1000, cell + 0x5_2000, None), (cell + 0x4_0000, cell + 0x8_0000)); + // A later ask below it: the new window runs from it to the old one's end. + let now = Some((cell + 0x4_0000, 0x4_0000)); + assert_eq!(grown_extent(cell + 0x1_0000, cell + 0x1_0100, now), (cell, cell + 0x8_0000)); + // An ask without a length: to the cell's end. + assert_eq!(grown_extent(cell + 0x30_0000, cell + WINDOW, now), (cell + 0x4_0000, cell + WINDOW)); + // An ask that runs into the next cell keeps going past it. + assert_eq!(grown_extent(cell + 0x3f_0000, cell + WINDOW + 0x100, None), (cell + 0x3c_0000, cell + WINDOW + GROW_STEP)); + } + #[test] fn card_limits_scale_with_local_vram_budget() { const GIB: u64 = 1 << 30; From 22521695b3a733acd12f81f45846ca6dfc0388f7 Mon Sep 17 00:00:00 2001 From: Davide Date: Fri, 27 Nov 2026 23:04:35 +0100 Subject: [PATCH 2/4] Grown windows: one per cell, forward only to windows a slot shows, keep the chain Three faults of 129a821 found in review: - A window was also looked for among those beginning in the cell below. find gave that one until the cell had a window of its own and this one from then on, without a takeover: a slot made on the first showed a window nothing brought up to date and what shaders wrote through it was lost. Now only the window beginning in the ask's cell holds an ask. - forward went to every window taken over, which TAKEN_OVER holds until it is let go, and put it in the list too: a window in use every frame kept the one it took the place of for good. Now it forwards only to those a descriptor slot still shows. - The takeover took the old window's chain (mem::take), so a thread that had the old window from find no longer forwarded to the ones before it. Now it is copied. --- crates/victory-gpu/src/shadow.rs | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 66c8f7135..7b93c294f 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -3367,8 +3367,11 @@ impl Shadow { self.forward(address, len, |before, address, len| before.refresh(list, address, len)); } - /// With [`grow`]: `f` for each window this one took the place of that - /// is still held, with the part of `[address, address + len)` it holds. + /// With [`grow`]: `f` for each window this one took the place of that a + /// descriptor slot still shows, with the part of `[address, address + + /// len)` it holds. Only those: [`TAKEN_OVER`] holds each until it is let + /// go, and forwarding to one no slot shows would put it in this list + /// too, so that one in use every frame would keep it for good. fn forward(&self, address: u64, len: u64, f: impl Fn(&Arc, u64, u64)) { if !grow() { return; @@ -3379,7 +3382,11 @@ impl Shadow { return; } before.retain(|w| w.strong_count() > 0); - before.iter().filter_map(std::sync::Weak::upgrade).collect() + before + .iter() + .filter_map(std::sync::Weak::upgrade) + .filter(|s| crate::host::references(&s.buffer) > 1) + .collect() }; for shadow in before { let from = address.max(shadow.start); @@ -5962,10 +5969,14 @@ fn grown(address: u64, end: u64, unsized_ask: bool, note: &dyn Fn(&Shadow)) -> O let (cell, _) = window_of(address, end, WINDOW); // An ask without a length reads from its address to its cell's end. let reach = if unsized_ask { end.max(cell + WINDOW) } else { end }; - // A window that begins in the cell, or in the one below and reaches this - // far, and holds the ask. + // The window that begins in the cell, if it holds the ask. Not one of + // the cell below that reaches this far: `find` would give that one until + // the cell has a window of its own and this one from then on, and a slot + // made on the first would show a window nothing brings up to date (it + // was not taken over). One window per cell, changed only by a takeover; + // memory at a cell's line may be in two windows. let holding = |map: &BTreeMap<(u64, u64), Arc>| { - map.range((cell.saturating_sub(WINDOW), 0)..=(address, u64::MAX)) + map.range((cell, 0)..=(address, u64::MAX)) .rev() .find(|&(&(start, len), _)| start <= address && start + len >= reach) .map(|(_, shadow)| shadow.clone()) @@ -5987,7 +5998,9 @@ fn grown(address: u64, end: u64, unsized_ask: bool, note: &dyn Fn(&Shadow)) -> O if let Some((key, old)) = now { use windows::core::Interface; map.remove(&key); - let mut before = std::mem::take(&mut *old.before_me.lock().unwrap_or_else(|e| e.into_inner())); + // A copy, not taken: a thread that got `old` from `find` before + // this may still bring it up to date, and must forward to them. + let mut before = old.before_me.lock().unwrap_or_else(|e| e.into_inner()).clone(); before.retain(|w| w.strong_count() > 0); before.push(Arc::downgrade(&old)); *shadow.before_me.lock().unwrap_or_else(|e| e.into_inner()) = before; From bae083d58961d95854f778b7b7512a14e2f902f0 Mon Sep 17 00:00:00 2001 From: Davide Date: Fri, 27 Nov 2026 23:19:49 +0100 Subject: [PATCH 3/4] Tests for the growing windows' logic, taken out into pure functions holding_in (the cell's window that holds an ask), overlap (the part forward hands to a window taken over) and chained (the chain a takeover gives the new window) are free functions now, with tests in window_tests. No change in behaviour. --- crates/victory-gpu/src/shadow.rs | 143 +++++++++++++++++++++++++++---- 1 file changed, 126 insertions(+), 17 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 7b93c294f..40a33c9ea 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -3389,10 +3389,8 @@ impl Shadow { .collect() }; for shadow in before { - let from = address.max(shadow.start); - let to = (address + len).min(shadow.start + shadow.len); - if from < to { - f(&shadow, from, to - from); + if let Some((from, bytes)) = overlap(address, len, shadow.start, shadow.len) { + f(&shadow, from, bytes); } } } @@ -5585,6 +5583,14 @@ fn grid(kb: Option) -> u64 { } } +/// The part (start, bytes) of `[address, address + len)` that lies in +/// `[start, start + bytes)`, if any does. +fn overlap(address: u64, len: u64, start: u64, bytes: u64) -> Option<(u64, u64)> { + let from = address.max(start); + let to = (address + len).min(start + bytes); + (from < to).then(|| (from, to - from)) +} + /// The window (start, bytes) of title memory for an ask of `[address, /// end)` on a grid of `grid` bytes. fn window_of(address: u64, end: u64, grid: u64) -> (u64, u64) { @@ -5963,6 +5969,24 @@ fn grown_extent(address: u64, reach: u64, now: Option<(u64, u64)>) -> (u64, u64) } } +/// Of the windows in `map`, by (start, bytes), the one that begins in +/// `cell` at or below `address` and holds `[address, reach)`. +fn holding_in(map: &BTreeMap<(u64, u64), T>, cell: u64, address: u64, reach: u64) -> Option { + map.range((cell, 0)..=(address, u64::MAX)) + .rev() + .find(|&(&(start, len), _)| start <= address && start + len >= reach) + .map(|(_, window)| window.clone()) +} + +/// The chain of the window that takes the place of `old`: those of `old`'s +/// chain `before` that are still held, then `old`. +fn chained(before: &[std::sync::Weak], old: &Arc) -> Vec> { + let mut chain = before.to_vec(); + chain.retain(|w| w.strong_count() > 0); + chain.push(Arc::downgrade(old)); + chain +} + /// [`loose`] with [`grow`]: the window of the ask's cell, grown first if it /// does not hold the ask. fn grown(address: u64, end: u64, unsized_ask: bool, note: &dyn Fn(&Shadow)) -> Option> { @@ -5975,18 +5999,12 @@ fn grown(address: u64, end: u64, unsized_ask: bool, note: &dyn Fn(&Shadow)) -> O // made on the first would show a window nothing brings up to date (it // was not taken over). One window per cell, changed only by a takeover; // memory at a cell's line may be in two windows. - let holding = |map: &BTreeMap<(u64, u64), Arc>| { - map.range((cell, 0)..=(address, u64::MAX)) - .rev() - .find(|&(&(start, len), _)| start <= address && start + len >= reach) - .map(|(_, shadow)| shadow.clone()) - }; - if let Some(shadow) = holding(&LOOSE.read().unwrap_or_else(|e| e.into_inner())) { + if let Some(shadow) = holding_in(&LOOSE.read().unwrap_or_else(|e| e.into_inner()), cell, address, reach) { note(&shadow); return Some(shadow); } let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner()); - if let Some(shadow) = holding(&map) { + if let Some(shadow) = holding_in(&map, cell, address, reach) { note(&shadow); return Some(shadow); } @@ -6000,9 +6018,7 @@ fn grown(address: u64, end: u64, unsized_ask: bool, note: &dyn Fn(&Shadow)) -> O map.remove(&key); // A copy, not taken: a thread that got `old` from `find` before // this may still bring it up to date, and must forward to them. - let mut before = old.before_me.lock().unwrap_or_else(|e| e.into_inner()).clone(); - before.retain(|w| w.strong_count() > 0); - before.push(Arc::downgrade(&old)); + let before = chained(&old.before_me.lock().unwrap_or_else(|e| e.into_inner()), &old); *shadow.before_me.lock().unwrap_or_else(|e| e.into_inner()) = before; if !old.taken_over.swap(true, Ordering::Relaxed) { let mut taken = TAKEN_OVER.lock().unwrap_or_else(|e| e.into_inner()); @@ -6140,9 +6156,11 @@ mod write_combined_tests { #[cfg(test)] mod window_tests { use super::{ - GROW_STEP, WINDOW, cover, default_card_limits_mb, grid, grown_extent, holder, longest_tail, - resolve_card_limits, tail_of, window_of, + GROW_STEP, WINDOW, chained, cover, default_card_limits_mb, grid, grown_extent, holder, holding_in, + longest_tail, overlap, resolve_card_limits, tail_of, window_of, }; + use std::collections::BTreeMap; + use std::sync::{Arc, Weak}; /// A growing window holds what was asked on 256 KiB steps, takes in the /// cell's window it replaces, and reaches the cell's end for an ask @@ -6162,6 +6180,97 @@ mod window_tests { assert_eq!(grown_extent(cell + 0x3f_0000, cell + WINDOW + 0x100, None), (cell + 0x3c_0000, cell + WINDOW + GROW_STEP)); } + /// Only the window that begins in the ask's cell is given, even when one + /// of the cell below reaches far enough to hold the ask. + #[test] + fn a_window_of_the_cell_below_does_not_hold_the_ask() { + let cell = 0xd_1200_0000u64; + // From the cell below, to 512 KiB into this one. + let map = BTreeMap::from([((cell - 0x4_0000, 0xc_0000), 1u32)]); + assert_eq!(holding_in(&map, cell, cell + 0x1_0000, cell + 0x2_0000), None); + } + + #[test] + fn the_cells_window_holds_an_ask_only_up_to_its_end() { + let cell = 0xd_1200_0000u64; + let map = BTreeMap::from([((cell + 0x4_0000, 0x4_0000), 2u32)]); + assert_eq!(holding_in(&map, cell, cell + 0x5_0000, cell + 0x6_0000), Some(2)); + // To its last byte, and from its first. + assert_eq!(holding_in(&map, cell, cell + 0x4_0000, cell + 0x8_0000), Some(2)); + // Past its end. + assert_eq!(holding_in(&map, cell, cell + 0x7_0000, cell + 0x8_0001), None); + // Below its start. + assert_eq!(holding_in(&map, cell, cell + 0x3_0000, cell + 0x5_0000), None); + } + + /// An ask without a length reaches the cell's end: the cell's window that + /// already goes past it holds the ask. + #[test] + fn a_window_past_the_cells_end_holds_an_ask_without_a_length() { + let cell = 0xd_1200_0000u64; + let map = BTreeMap::from([((cell + 0x3c_0000, 0x8_0000), 3u32)]); + assert_eq!(holding_in(&map, cell, cell + 0x3d_0000, cell + WINDOW), Some(3)); + } + + /// W1, then W2 for an ask above it, then W3 for one below: each new + /// window holds the one it takes the place of. + #[test] + fn each_grown_window_holds_the_one_before() { + let cell = 0xd_1200_0000u64; + let bytes = |(from, to): (u64, u64)| (from, to - from); + let holds = |(from, to): (u64, u64), (start, len): (u64, u64)| from <= start && to >= start + len; + let first = grown_extent(cell + 0x11_0000, cell + 0x12_0000, None); + assert_eq!(first, (cell + 0x10_0000, cell + 0x14_0000)); + let second = grown_extent(cell + 0x21_0000, cell + 0x22_0000, Some(bytes(first))); + assert_eq!(second, (cell + 0x10_0000, cell + 0x24_0000)); + assert!(holds(second, bytes(first))); + let third = grown_extent(cell + 0x5_0000, cell + 0x6_0000, Some(bytes(second))); + assert_eq!(third, (cell + 0x4_0000, cell + 0x24_0000)); + assert!(holds(third, bytes(second))); + assert!(holds(third, bytes(first))); + } + + #[test] + fn overlap_is_the_part_both_ranges_have() { + // Against [0x1000, 0x3000). + let part = |address, len| overlap(address, len, 0x1000, 0x2000); + assert_eq!(part(0x1800, 0x800), Some((0x1800, 0x800)), "inside"); + assert_eq!(part(0x800, 0x1000), Some((0x1000, 0x800)), "across its start"); + assert_eq!(part(0x2800, 0x1000), Some((0x2800, 0x800)), "across its end"); + assert_eq!(part(0x5000, 0x1000), None, "apart"); + assert_eq!(part(0, 0x800), None, "apart, below"); + assert_eq!(part(0, 0x1000), None, "touching its start"); + assert_eq!(part(0x3000, 0x1000), None, "touching its end"); + } + + #[test] + fn a_chain_drops_the_windows_gone_and_ends_with_the_old_one() { + let (held, gone, old) = (Arc::new(1u32), Arc::new(2u32), Arc::new(3u32)); + let before = vec![Arc::downgrade(&gone), Arc::downgrade(&held)]; + drop(gone); + let chain = chained(&before, &old); + let values: Vec = chain.iter().filter_map(Weak::upgrade).map(|v| *v).collect(); + assert_eq!(values, [1, 3]); + assert_eq!(chain.len(), 2); + // The list it started from is as it was. + assert_eq!(before.len(), 2); + assert!(before[0].upgrade().is_none()); + assert!(Weak::ptr_eq(&before[1], &Arc::downgrade(&held))); + // The chain holds nothing. + assert_eq!(Arc::strong_count(&old), 1); + } + + #[test] + fn a_chain_of_three_keeps_their_order() { + let (first, second, third) = (Arc::new(1u32), Arc::new(2u32), Arc::new(3u32)); + let of_second = chained(&[], &first); + let of_third = chained(&of_second, &second); + let of_fourth = chained(&of_third, &third); + let values: Vec = of_fourth.iter().filter_map(Weak::upgrade).map(|v| *v).collect(); + assert_eq!(values, [1, 2, 3]); + assert_eq!((of_second.len(), of_third.len()), (1, 2)); + } + #[test] fn card_limits_scale_with_local_vram_budget() { const GIB: u64 = 1 << 30; From 0bbbbf416ddf81f504037a704e99ed48b089742e Mon Sep 17 00:00:00 2001 From: Davide Date: Fri, 27 Nov 2026 23:41:04 +0100 Subject: [PATCH 4/4] Grown windows: make slots again on the longer window at their next use Two faults of the growing windows, both with VICTORY_WINDOW_GROW=1 only: - A slot made on a window a longer one took the place of went on showing it: a slot of a draw's table until the title wrote it again, a slot the pass over the heap keeps until its turn in the round (up to 16 passes). Root views, vertex buffers and newer slots use the longer window, so what shaders wrote through one reached the other a frame late. Now the draw makes its table's slot again (State::table_entry), and the pass looks at once at the slots it keeps on a window taken over (HeapRanges::slots_where). TAKEN_OVER is a RwLock: every slot of a draw's table reads it while any window is held. - The pass brought one copy up to date while the slot showed another: for a view's own bytes when the window's start moved down (view_home counts from it), the slot then read a copy nothing brought up to date. The pass now makes such a slot again, once. A list recorded before the takeover and run after a slot is made again may find the longer window not filled yet there; nothing copies the bytes over and nothing counts it. The memory lines (diagnostics) say how many slots of draws' tables moved, and a new one ("heap slots elsewhere") by which kinds of copy the slots disagreed, how many still did after being made again, and how often a pass. --- crates/victory-gpu/src/copystat.rs | 43 +++++++- crates/victory-gpu/src/descriptor/host.rs | 27 ++++- crates/victory-gpu/src/draw.rs | 120 +++++++++++++++++++++- crates/victory-gpu/src/shadow.rs | 55 ++++++++-- 4 files changed, 224 insertions(+), 21 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index a4b71c389..8b0140562 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -950,7 +950,8 @@ fn log_memory() { "memory, windows: the {:.0} MB of windows lie over {:.0} MB of title memory (the rest is \ memory that is in more than one window, and is copied once for each); host lists never \ reset since they were made: {}; windows grown (VICTORY_WINDOW_GROW): {} since the start, \ - {} taken over and still held {:.0} MB, {} slots of the heap moved to the longer one", + {} taken over and still held {:.0} MB, {} slots of the heap and {} of draws' tables moved \ + to the longer one", mb(copies[3]), mb(crate::shadow::window_cover()), lists[3], @@ -958,6 +959,46 @@ fn log_memory() { crate::shadow::taken_over_held().0, mb(crate::shadow::taken_over_held().1), crate::shadow::GROWN[1].load(Relaxed), + crate::shadow::GROWN[2].load(Relaxed), + ); + if crate::shadow::grow() { + log_heap_elsewhere(); + } +} + +/// The memory line on the slots the pass over the heap found showing another +/// copy than the one it brings up to date (`VICTORY_WINDOW_GROW`). +fn log_heap_elsewhere() { + use crate::draw::{ + HEAP_ELSEWHERE_OUTSIDE, HEAP_ELSEWHERE_SLOTS, HEAP_ELSEWHERE_WHY, HEAP_LOOKS, HEAP_MADE_AGAIN_NULL, + HEAP_VIEWS_ELSEWHERE, HEAP_VIEWS_STILL_ELSEWHERE, + }; + // Shown kind by found kind (`crate::shadow::copy_kind`). + let w = |shown: usize, found: usize| HEAP_ELSEWHERE_WHY[shown * 5 + found].load(Relaxed); + let (looks, passes) = (HEAP_LOOKS[0].load(Relaxed), HEAP_LOOKS[1].load(Relaxed)); + let elsewhere = HEAP_VIEWS_ELSEWHERE.load(Relaxed); + let named = [w(0, 1), w(1, 1), w(2, 1), w(1, 2), w(1, 3), w(3, 1), w(3, 3), (0..5).map(|f| w(4, f)).sum::()]; + tracing::info!( + "memory, heap slots elsewhere: {elsewhere} in {looks} looks over {passes} passes ({:.3} a pass), \ + {} distinct slots; still elsewhere after being made again {}; begin outside their buffer {}; \ + shown -> found: taken over -> window {}, window -> window {}, own bytes -> window {}, \ + window -> own bytes {}, window -> title buffer {}, title buffer -> window {}, \ + title buffer -> title buffer {}, let go -> any {}, other {}; made again on the longer window \ + and left null {}", + elsewhere as f64 / passes.max(1) as f64, + HEAP_ELSEWHERE_SLOTS.lock().unwrap_or_else(|e| e.into_inner()).len(), + HEAP_VIEWS_STILL_ELSEWHERE.load(Relaxed), + HEAP_ELSEWHERE_OUTSIDE.load(Relaxed), + named[0], + named[1], + named[2], + named[3], + named[4], + named[5], + named[6], + named[7], + elsewhere.saturating_sub(named.iter().sum()), + HEAP_MADE_AGAIN_NULL.load(Relaxed), ); } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index af5bd8be7..5347cdb36 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -4128,12 +4128,19 @@ impl HostHeap { } /// Whether host slot `index` shows `buffer`; `None` if it shows no - /// resource (diagnostics: a buffer view's slot must show the host copy - /// that is brought up to date for it). - #[cfg(feature = "diagnostics")] + /// resource (a buffer view's slot must show the host copy that is + /// brought up to date for it: with growing windows the pass over the + /// heap makes it again when it does not). pub(crate) fn shows(&self, index: u32, buffer: &ID3D12Resource) -> Option { - let shown = self.kept_in(index)?; - Some(windows::core::Interface::as_raw(&shown) == windows::core::Interface::as_raw(buffer)) + use windows::core::Interface; + let kept = self.kept.get(index as usize)?.lock().unwrap_or_else(|e| e.into_inner()); + Some(kept.as_ref()?.as_raw() == buffer.as_raw()) + } + + /// What slot `index` views (diagnostics). + #[cfg(feature = "diagnostics")] + pub(crate) fn shown(&self, index: u32) -> Option { + self.kept_in(index) } /// Whether host slot `index` shows a window of title memory that a longer @@ -4424,6 +4431,16 @@ pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc bool { + match (buffer_range(view), buffer_extent(view)) { + (Some((address, _)), Some((base, width))) => address < base || address - base >= width.max(1), + _ => false, + } +} + /// [`buffer_range`] of an unordered access view of memory at `base`. fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { let desc = uav_desc(words); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 1526b30d4..c2524615a 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -686,9 +686,33 @@ type RootSlot = (u32, Option>); /// the copy the pass brought up to date for them, since the start /// (diagnostics; for the memory line). It stays 0 while the pass and the /// slots agree; with `VICTORY_VIEW_EXTENT=0` it counts the views that were -/// read stale. +/// read stale. With growing windows (`crate::shadow::grow`) the pass then +/// makes the slot again; what is counted is what it found before that. #[cfg(feature = "diagnostics")] pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0); +// The counters below are kept with growing windows only (diagnostics, for +// the memory line "heap slots elsewhere"). +/// Of [`HEAP_VIEWS_ELSEWHERE`], the ones whose slot made again still showed +/// another copy: `make` and `buffer_copy` look the copy up differently. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_VIEWS_STILL_ELSEWHERE: AtomicU64 = AtomicU64::new(0); +/// The heap pass's slots that showed another copy, by (kind of the copy +/// shown) * 5 + (kind of the copy found), `crate::shadow::copy_kind`. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_ELSEWHERE_WHY: [AtomicU64; 25] = [const { AtomicU64::new(0) }; 25]; +/// Of them, the views that begin outside their buffer. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_ELSEWHERE_OUTSIDE: AtomicU64 = AtomicU64::new(0); +/// Slots made again on the longer window that show nothing since. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_MADE_AGAIN_NULL: AtomicU64 = AtomicU64::new(0); +/// The distinct slots that showed another copy. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_ELSEWHERE_SLOTS: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); +/// Slots looked at, and passes, since the start. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_LOOKS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; /// Passes over the view heap's buffer views for shaders that pick them by /// index ([`State::heap_buffers`]), and the microseconds they took. pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0); @@ -754,6 +778,15 @@ impl HeapRanges { fn ranges(&self) -> impl Iterator { self.0.iter().flatten() } + + /// The slots whose kept copy `f` picks. + fn slots_where(&self, f: impl Fn(&T) -> bool) -> Vec { + self.0 + .iter() + .enumerate() + .filter_map(|(slot, range)| range.as_ref().filter(|(copy, ..)| f(copy)).map(|_| slot as u32)) + .collect() + } } #[cfg(test)] @@ -786,6 +819,22 @@ mod heap_range_tests { assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize - 1); } + /// The slots whose kept copy is a window taken over are found, and + /// those forgotten for this pass's part are not. + #[test] + fn the_slots_on_a_window_taken_over_are_found() { + let mut ranges = HeapRanges(Vec::new()); + ranges.set(2, Some((false, 0, 1))); + ranges.set(5, Some((true, 0, 1))); + ranges.set(9, Some((true, 4, 8))); + ranges.set(12, None); + assert_eq!(ranges.slots_where(|&taken| taken), [5, 9]); + assert_eq!(ranges.slots_where(|&taken| !taken), [2]); + // Part 1 of 4 is 1, 5, 9: the pass looks at those anyway. + ranges.forget_part(1, 4); + assert!(ranges.slots_where(|&taken| taken).is_empty()); + } + /// 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`. @@ -1173,7 +1222,7 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho let BufferSweep { passes, ranges, unwatched } = &mut *kept; let changed = host.buffer_changes(); let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()); - let slots = if all { + let mut slots = if all { ranges.0.clear(); host.buffer_slots() } else if heap_spread() { @@ -1187,6 +1236,20 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho changed }; *passes += 1; + #[cfg(feature = "diagnostics")] + if crate::shadow::grow() { + HEAP_LOOKS[1].fetch_add(1, Ordering::Relaxed); + } + // Slots kept on a window a longer one took the place of are looked at + // now, not at their turn in the round (up to HEAP_ROUND passes later): + // `look` makes them again on the longer one (`crate::shadow::grow`). + // Meanwhile what shaders write through the one is not in the other + // before the copy back and a refresh, a frame late. + if !all && crate::shadow::grow() && crate::shadow::any_taken_over() { + slots.extend(ranges.slots_where(|copy| copy.is_taken_over())); + slots.sort_unstable(); + slots.dedup(); + } // Whether the device was there before the pass: a view that removes // it is named below. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -1206,6 +1269,10 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho // What a slot of the title's shows: its copy and range, and whether it is // an unordered view. let look = |index: u32| { + #[cfg(feature = "diagnostics")] + if crate::shadow::grow() { + HEAP_LOOKS[0].fetch_add(1, Ordering::Relaxed); + } // A draw's table's: the draw brings what it reads up to date. if host.copied_tabled(index, frame) { return None; @@ -1217,13 +1284,42 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho host.make_again(index); view = host.mirror(index, heap.handle(index)?, true)?; crate::shadow::GROWN[1].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + if host.shown(index).is_none() { + HEAP_MADE_AGAIN_NULL.fetch_add(1, Ordering::Relaxed); + } } // The copy the slot shows (`buffer_copy`), not the one the // view's range alone would find. - let (shadow, address, len) = crate::descriptor::host::buffer_copy(&view)?; + let (mut shadow, mut address, mut len) = crate::descriptor::host::buffer_copy(&view)?; #[cfg(feature = "diagnostics")] if host.shows(index, &shadow.buffer) == Some(false) { HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); + if crate::shadow::grow() { + if let Some(shown) = host.shown(index) { + let why = crate::shadow::copy_kind(&shown) * 5 + crate::shadow::copy_kind(&shadow.buffer); + HEAP_ELSEWHERE_WHY[why].fetch_add(1, Ordering::Relaxed); + } + if crate::descriptor::host::view_outside_buffer(&view) { + HEAP_ELSEWHERE_OUTSIDE.fetch_add(1, Ordering::Relaxed); + } + HEAP_ELSEWHERE_SLOTS.lock().unwrap_or_else(|e| e.into_inner()).insert(index); + } + } + // With growing windows the slot may show another copy than the one + // brought up to date for it: a takeover between the look above and + // here, a view's own bytes whose window moved (`view_home` counts + // from the window's start), a title buffer made or let go since the + // slot was. Made again once, on what is found now; what it showed is + // retired by `keep`. + if crate::shadow::grow() && host.shows(index, &shadow.buffer) == Some(false) { + host.make_again(index); + view = host.mirror(index, heap.handle(index)?, true)?; + (shadow, address, len) = crate::descriptor::host::buffer_copy(&view)?; + #[cfg(feature = "diagnostics")] + if host.shows(index, &shadow.buffer) == Some(false) { + HEAP_VIEWS_STILL_ELSEWHERE.fetch_add(1, Ordering::Relaxed); + } } let written = crate::picked::on() && view_kind(&view) == Some(ResourceType::Uav); Some(((shadow, address, address + len), written)) @@ -4474,7 +4570,23 @@ impl State { let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else { return; }; - if let Some(view) = host.mirror(index, handle, true) { + if let Some(mut view) = host.mirror(index, handle, true) { + // A slot made on a window a longer one took the place of is made + // again on the longer one here, as the pass over the heap does + // for the slots it looks at (`crate::shadow::grow`): the pass + // leaves a draw's table to the draw, and the slot would show the + // shorter window until the title wrote it again, while root + // views, vertex buffers and the slots made since use the longer + // one. What shaders write through the one is in the other only + // after the copy back and a refresh: a frame late. + if host.shows_taken_over(index) { + host.make_again(index); + match host.mirror(index, handle, true) { + Some(again) => view = again, + None => return, + } + crate::shadow::GROWN[2].fetch_add(1, Ordering::Relaxed); + } readable(list, u.kind, &view); // Up to date by this draw: not the texture pass's to make. if crate::descriptor::host::is_texture_view(&view) { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 40a33c9ea..5af3d1159 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -3395,6 +3395,11 @@ impl Shadow { } } + /// With [`grow`]: whether a longer window took this one's place. + pub(crate) fn is_taken_over(&self) -> bool { + self.taken_over.load(Ordering::Relaxed) + } + /// The bytes of the host buffer. pub(crate) fn width(&self) -> u64 { // SAFETY: a live buffer. @@ -5669,9 +5674,11 @@ fn fine() -> bool { /// is brought up to date or written through the longer one is through it /// too ([`Shadow::forward`]). /// -/// shortcut: a slot of a draw's table made on the shorter window keeps it -/// until the title writes the slot again (it is brought up to date all the -/// same). +/// A slot of a draw's table made on the shorter window is made again by +/// the next draw that reads it (`State::table_entry`), a slot the pass +/// keeps by the next pass. Until then the two windows are two copies of the +/// same bytes: what shaders write through one reaches the other a frame +/// late (copy back, then refresh). pub(crate) fn grow() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOW_GROW").is_some_and(|v| v == "1")) @@ -5686,20 +5693,46 @@ const GROW_STEP: u64 = TAIL_STEP; /// A descriptor slot holds a window's buffer and not the copy: let go while /// a slot still showed it, the copy would be brought up to date no more, /// and the pass over the heap would not know the slot is to be made again. -static TAKEN_OVER: Mutex>> = Mutex::new(BTreeMap::new()); +/// (Read by every slot of a draw's table while any is held: a reader's lock.) +static TAKEN_OVER: RwLock>> = RwLock::new(BTreeMap::new()); /// How many there are (asked by every slot the pass over the heap looks at). static TAKEN_OVER_N: AtomicU64 = AtomicU64::new(0); -/// Windows grown since the start, and the slots of the heap moved to the -/// longer window. -pub(crate) static GROWN: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; +/// Windows grown since the start, the slots the pass over the heap moved to +/// the longer window, and the slots of draws' tables the draws moved. +pub(crate) static GROWN: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; /// Whether `buffer` is a window's that a longer window took the place of. pub(crate) fn taken_over(buffer: &ID3D12Resource) -> bool { use windows::core::Interface; grow() && TAKEN_OVER_N.load(Ordering::Relaxed) > 0 - && TAKEN_OVER.lock().unwrap_or_else(|e| e.into_inner()).contains_key(&(buffer.as_raw() as usize)) + && TAKEN_OVER.read().unwrap_or_else(|e| e.into_inner()).contains_key(&(buffer.as_raw() as usize)) +} + +/// Of what kind host copy `buffer` is (diagnostics, for the heap pass's slots +/// that show another copy than the one brought up to date): 0 a window taken +/// over, 1 a window of [`LOOSE`], 2 a copy of a view's own bytes ([`EXACT`]), +/// 3 a title buffer's copy, 4 none of these (let go). +#[cfg(feature = "diagnostics")] +pub(crate) fn copy_kind(buffer: &ID3D12Resource) -> usize { + use windows::core::Interface; + let raw = buffer.as_raw(); + let is = |s: &Shadow| s.buffer.as_raw() == raw; + // (A lock at a time: each is let go before the next is taken.) + if TAKEN_OVER.read().unwrap_or_else(|e| e.into_inner()).values().any(|s| is(s)) { + return 0; + } + if LOOSE.read().unwrap_or_else(|e| e.into_inner()).values().any(|s| is(s)) { + return 1; + } + if EXACT.lock().unwrap_or_else(|e| e.into_inner()).1.values().any(|(s, _)| is(s)) { + return 2; + } + if buffers_read().values().any(|e| e.shadow.as_deref().is_some_and(is)) { + return 3; + } + 4 } /// Whether any window was taken over and is still held. @@ -5715,7 +5748,7 @@ fn let_go_taken_over() { return; } let gone: Vec> = { - let mut map = TAKEN_OVER.lock().unwrap_or_else(|e| e.into_inner()); + let mut map = TAKEN_OVER.write().unwrap_or_else(|e| e.into_inner()); let free: Vec = map .iter() .filter(|(_, s)| Arc::strong_count(s) == 1 && crate::host::references(&s.buffer) == 1) @@ -5735,7 +5768,7 @@ fn let_go_taken_over() { /// For the memory line: windows taken over and still held, and their bytes. #[cfg(feature = "diagnostics")] pub(crate) fn taken_over_held() -> (u64, u64) { - let map = TAKEN_OVER.lock().unwrap_or_else(|e| e.into_inner()); + let map = TAKEN_OVER.read().unwrap_or_else(|e| e.into_inner()); (map.len() as u64, map.values().map(|s| s.len).sum()) } @@ -6021,7 +6054,7 @@ fn grown(address: u64, end: u64, unsized_ask: bool, note: &dyn Fn(&Shadow)) -> O let before = chained(&old.before_me.lock().unwrap_or_else(|e| e.into_inner()), &old); *shadow.before_me.lock().unwrap_or_else(|e| e.into_inner()) = before; if !old.taken_over.swap(true, Ordering::Relaxed) { - let mut taken = TAKEN_OVER.lock().unwrap_or_else(|e| e.into_inner()); + let mut taken = TAKEN_OVER.write().unwrap_or_else(|e| e.into_inner()); taken.insert(old.buffer.as_raw() as usize, old.clone()); TAKEN_OVER_N.store(taken.len() as u64, Ordering::Relaxed); }