diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index cfc65e18e..8a0a78d09 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -978,10 +978,56 @@ 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 and {} of draws' tables 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), + 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 79eb3a4e0..43eef07a7 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -4682,12 +4682,39 @@ 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 + /// 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 @@ -4947,6 +4974,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 09d6d9354..e40143144 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -768,9 +768,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); @@ -880,6 +904,14 @@ impl HeapRanges { fn is_none(&self, slot: u32) -> bool { self.index.get(slot as usize).is_none_or(|&idx| idx == u32::MAX) } + + /// The slots whose kept copy `f` picks. + fn slots_where(&self, f: impl Fn(&T) -> bool) -> Vec { + let mut slots: Vec = self.dense.iter().filter(|(_, (copy, ..))| f(copy)).map(|&(slot, _)| slot).collect(); + // (`dense` is in no order once a slot was removed.) + slots.sort_unstable(); + slots + } } #[cfg(test)] @@ -912,6 +944,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::default(); + 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`. @@ -1403,7 +1451,7 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho let BufferSweep { passes, ranges, unwatched, last_spans } = &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.clear(); host.buffer_slots() } else if heap_spread() { @@ -1417,6 +1465,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); @@ -1436,17 +1498,57 @@ 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; } - 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); + #[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)) @@ -4915,7 +5017,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 215be62bf..884940c7e 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -107,6 +107,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 @@ -3417,6 +3425,7 @@ pub(crate) fn window_use() -> [u64; 8] { pub(crate) fn let_go_idle() { const IDLE_FRAMES: u64 = 4; trim_exact_pool(crate::residency::pressured()); + 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. @@ -3565,6 +3574,40 @@ 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 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; + } + 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) + .filter(|s| crate::host::references(&s.buffer) > 1) + .collect() + }; + for shadow in before { + if let Some((from, bytes)) = overlap(address, len, shadow.start, shadow.len) { + f(&shadow, from, bytes); + } + } + } + + /// 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. @@ -3609,6 +3652,8 @@ impl Shadow { wc: AtomicU8::new(0), mapped: false, place: None, + before_me: Mutex::default(), + taken_over: Default::default(), } } @@ -3629,6 +3674,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 @@ -5903,6 +5951,14 @@ fn named_window(address: u64, end: u64, unsized_ask: bool, grid: u64, reach: u64 if sized == (long.0, WINDOW) { long } else { sized } } +/// 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) { @@ -5960,7 +6016,124 @@ 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 (for an ask without a length, to the cell's end and +/// [`reach`] past it, which it reads). 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`]). +/// +/// 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")) +} + +/// 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. +/// (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, 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.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.map.read().unwrap_or_else(|e| e.into_inner()).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. +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.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) + .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.read().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 @@ -6095,6 +6268,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) { @@ -6136,10 +6318,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), + } +} + +/// 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 +} + +/// Where an ask ending at `end` in `cell` reads to. An ask without a length +/// reads from its address to its cell's end and `reach` bytes past it, as +/// its window does without [`grow`] ([`unsized_window`]). +fn grow_reach(cell: u64, end: u64, unsized_ask: bool, reach: u64) -> u64 { + if unsized_ask { end.max(cell + WINDOW + reach) } else { end } +} + +/// [`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); + let reach = grow_reach(cell, end, unsized_ask, reach()); + // 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. + 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_in(&map, cell, address, reach) { + 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); + // 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 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.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); + } + 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) } @@ -6719,9 +6978,140 @@ mod write_combined_tests { #[cfg(test)] mod window_tests { use super::{ - WINDOW, cover, default_card_limits_mb, grid, holder, longest_tail, resolve_card_limits, - named_window, reach_of, tail_of, unsized_window, window_of, + GROW_STEP, WINDOW, chained, cover, default_card_limits_mb, grid, grow_reach, grown_extent, holder, holding_in, + longest_tail, named_window, overlap, reach_of, resolve_card_limits, tail_of, unsized_window, + 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 + /// 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)); + } + + /// 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))); + } + + /// An ask without a length reads past its cell by the reach: the grown + /// window holds what its window holds without `grow`, so a vertex block + /// that begins near the cell's end is not cut off. + #[test] + fn a_grown_window_for_an_ask_without_a_length_holds_the_reach() { + let cell = 0xd_1200_0000u64; + let reach = 2 << 20; + let ask = cell + 0x3e_0000; + let to = grow_reach(cell, ask + 1, true, reach); + assert_eq!(to, cell + WINDOW + reach); + let (from, end) = grown_extent(ask, to, None); + let (start, bytes) = unsized_window(ask, reach); + assert!(from >= start && end == start + bytes, "{from:#x}..{end:#x}"); + // Reach 0: to the cell's end, as before the reach. + assert_eq!(grow_reach(cell, ask + 1, true, 0), cell + WINDOW); + // An ask with a length reads what it asked for. + assert_eq!(grow_reach(cell, ask + 0x100, false, reach), ask + 0x100); + } + + #[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() {