diff --git a/README.md b/README.md index f97432661e..0c945c3a59 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,18 @@ The window caption shows the framerate. Saves, settings and `crashes.log` are kept under the data folder (default `%LOCALAPPDATA%\victory\data`), derived data under the cache folder. +Experimental memory tuning (off by default; compare the same scene with +and without each switch): + +- `VICTORY_WINDOW_KB=1024`: finer shadow windows for known-length accesses, + from 64 to 4096 KiB (powers of two); default 4096. Lengthless root views + keep the original 4 MiB grid. Smaller windows can increase overlapping + copies and page-table work, so check rendering and memory use. +- `VICTORY_SCRATCH_SPARE_MB=128`: share unused upload scratch chunks + between successfully reset command lists, capped at 512 MiB. Default 0 + retains the existing per-list reuse. This trades spare memory for fewer + driver allocations; it is not a total scratch-memory limit. + Set `VICTORY_WINDOW_MAX=1920x1080` before launching to limit the title's top-level window to that bounding box. Smaller windows keep their size, larger windows keep their proportions, and the monitor's work area still diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 340f6b1928..b3e87754b4 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -623,8 +623,28 @@ pub(crate) mod tests { } } + #[test] + fn scratch_spare_is_bounded_and_uses_best_fit() { + let mut spare = ScratchSpare::new(); + assert_eq!(spare.give(64, 1, 512), None); + assert_eq!(spare.give(128, 2, 512), None); + assert_eq!(spare.give(256, 3, 512), None); + assert_eq!(spare.give(128, 4, 512), Some(4)); + assert_eq!(spare.bytes, 448); + assert_eq!(spare.take(96), Some(2)); + assert_eq!(spare.bytes, 320); + assert_eq!(spare.take(64), Some(1)); + assert_eq!(spare.take(64), None); + assert_eq!(spare.take(128), Some(3)); + assert_eq!(spare.bytes, 0); + } + #[test] fn list_scratch_grows_to_fit_and_reuses_fenced_chunks() { + if scratch_spare_bytes() != 0 { + eprintln!("skipping default per-list scratch reuse test: shared pool enabled"); + return; + } let Some(host) = host() else { return }; let list = host.new_list().unwrap(); let first = list.scratch(1).unwrap(); @@ -972,6 +992,74 @@ struct ScratchChunk { capacity: u64, } +/// Free scratch chunks shared by command lists. Only returned after a +/// successful reset (the caller has waited for the list's last submission). +/// A zero budget preserves the old per-list reuse. +struct ScratchSpare { + chunks: Vec<(u64, T)>, + bytes: u64, +} + +impl ScratchSpare { + const fn new() -> Self { + Self { chunks: Vec::new(), bytes: 0 } + } + + fn take(&mut self, capacity: u64) -> Option { + // Prefer the smallest adequate chunk, with a bounded size mismatch. + let index = self.chunks.iter().enumerate() + .filter(|(_, (size, _))| *size >= capacity && *size <= capacity.saturating_mul(2)) + .min_by_key(|(_, (size, _))| *size) + .map(|(i, _)| i)?; + let (size, chunk) = self.chunks.swap_remove(index); + self.bytes -= size; + Some(chunk) + } + + fn give(&mut self, size: u64, chunk: T, cap: u64) -> Option { + if size > cap.saturating_sub(self.bytes) { + return Some(chunk); + } + self.chunks.push((size, chunk)); + self.bytes += size; + None + } +} + +static SCRATCH_SPARE: Mutex> = Mutex::new(ScratchSpare::new()); + +fn scratch_spare_bytes() -> u64 { + static CAP: OnceLock = OnceLock::new(); + *CAP.get_or_init(|| { + let cap = std::env::var("VICTORY_SCRATCH_SPARE_MB").ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0) + .min(512) << 20; + if cap != 0 { + tracing::info!(mb = cap >> 20, "shared command-list scratch pool enabled"); + } + cap + }) +} + +/// The list has reset successfully, so its former GPU addresses are no +/// longer referenced by its recording. Keep no more than the configured cap. +fn return_scratch(scratch: &mut Scratch, cap: u64) { + let mut excess = Vec::new(); + { + let mut spare = SCRATCH_SPARE.lock().unwrap_or_else(|e| e.into_inner()); + for chunk in scratch.chunks.drain(..) { + if let Some(chunk) = spare.give(chunk.capacity, chunk, cap) { + excess.push(chunk); + } + } + } + // Driver destruction can be slow; never hold the shared pool lock for it. + if !excess.is_empty() { + release_later(Box::new(excess)); + } +} + /// One piece of submission-time work, in recorded order. enum Step { /// A copy into title memory (destination, source, bytes): the title's @@ -1809,6 +1897,11 @@ impl HostList { if let Err(e) = reset { fail(format_args!("a host command list did not reset ({e})")); } + let cap = scratch_spare_bytes(); + if cap != 0 { + let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + return_scratch(&mut scratch, cap); + } } /// Moves a title texture's host copy to `wanted` (a host state) in this @@ -2208,14 +2301,25 @@ impl HostList { if s.current == s.chunks.len() { let next = s.chunks.last().map_or(FIRST_SCRATCH_CHUNK, |c| 2 * c.capacity); let capacity = len.next_multiple_of(FIRST_SCRATCH_CHUNK).max(next).min(SCRATCH_CHUNK); - let (buffer, data) = host.upload_buffer(capacity)?; - name(&buffer, || format!("list scratch {capacity:#x}")); - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - #[cfg(feature = "diagnostics")] - tracing::debug!(target: "victory_gpu::scratch", list = ?std::ptr::from_ref(self), - chunk = s.current, requested = len, capacity, "allocated list scratch"); - s.chunks.push(ScratchChunk { _buffer: buffer, mapped: data as usize, gpu, capacity }); + let kept = if scratch_spare_bytes() != 0 { + SCRATCH_SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(capacity) + } else { + None + }; + let chunk = match kept { + Some(chunk) => chunk, + None => { + let (buffer, data) = host.upload_buffer(capacity)?; + name(&buffer, || format!("list scratch {capacity:#x}")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + #[cfg(feature = "diagnostics")] + tracing::debug!(target: "victory_gpu::scratch", list = ?std::ptr::from_ref(self), + chunk = s.current, requested = len, capacity, "allocated list scratch"); + ScratchChunk { _buffer: buffer, mapped: data as usize, gpu, capacity } + } + }; + s.chunks.push(chunk); s.used = 0; } let chunk = &s.chunks[s.current]; diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index a455a965ea..cc8b549119 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1057,12 +1057,44 @@ pub(crate) fn find(address: u64, len: u64) -> Option> { /// allocations if memory use grows. const WINDOW: u64 = 4 << 20; +/// Experimental grid for asks with a known length. Keep the original grid +/// for lengthless root views: their shaders may read far beyond the address. +fn window_grid(kb: Option) -> u64 { + match kb { + Some(kb) if kb.is_power_of_two() && (64..=4096).contains(&kb) => kb << 10, + _ => WINDOW, + } +} + +fn loose_grid() -> u64 { + static GRID: std::sync::OnceLock = std::sync::OnceLock::new(); + *GRID.get_or_init(|| { + let kb = std::env::var("VICTORY_WINDOW_KB").ok() + .and_then(|v| v.trim().parse::().ok()); + let grid = window_grid(kb); + if grid != WINDOW { + tracing::info!(kb = grid >> 10, "experimental fine memory windows for known-length views"); + } + grid + }) +} + +fn loose_range(address: u64, end: u64, grid: u64) -> Option<(u64, u64)> { + let bytes = end.checked_sub(address)?; + if bytes == 0 { + return None; + } + let grid = if bytes == 1 { WINDOW } else { grid }; + let start = address & !(grid - 1); + let len = end.checked_next_multiple_of(grid)?.checked_sub(start)?; + Some((start, len)) +} + /// Copies of title memory outside buffers, by (start, length). static LOOSE: Mutex>> = Mutex::new(BTreeMap::new()); fn loose(address: u64, end: u64) -> Option> { - let start = address & !(WINDOW - 1); - let len = end.next_multiple_of(WINDOW) - start; + let (start, len) = loose_range(address, end, loose_grid())?; let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); if let Some(shadow) = map.get(&(start, len)) { return Some(shadow.clone()); @@ -1306,6 +1338,22 @@ pub(crate) fn near(va: u64) -> String { pub(crate) mod tests { use super::*; + #[test] + fn fine_window_grid_covers_explicit_ranges_and_keeps_root_hulls() { + let mib = 1 << 20; + assert_eq!(window_grid(None), WINDOW); + for kb in [0, 32, 1000, 8192, u64::MAX] { + assert_eq!(window_grid(Some(kb)), WINDOW); + } + assert_eq!(window_grid(Some(1024)), mib); + assert_eq!(window_grid(Some(64)), 64 << 10); + assert_eq!(loose_range(mib + 32, mib + 96, mib), Some((mib, mib))); + assert_eq!(loose_range(2 * mib - 16, 2 * mib + 16, mib), Some((mib, 2 * mib))); + assert_eq!(loose_range(mib + 32, mib + 33, mib), Some((0, WINDOW))); + assert_eq!(loose_range(mib, mib, mib), None); + assert_eq!(loose_range(u64::MAX - 8, u64::MAX, mib), None); + } + /// A shader's read mark of heap slot `slot` in the bitmap of shaders /// that use title memory (`memory`) or of the others. pub(crate) fn mark_read(memory: bool, slot: u32) {