From f0d1eb7682cc0685599da5e10fc42d3485f63ab2 Mon Sep 17 00:00:00 2001 From: theme613 <66501763+theme613@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:12:49 +0800 Subject: [PATCH] feat(residency): VICTORY_RAM_PRESSURE_MB gates heavy trims on physical RAM Add residency::ram_critical(): when VICTORY_RAM_PRESSURE_MB=N>0 and sampled physical available RAM < N MiB (hysteresis, enter N+256MiB), the once-a-second host sweep also runs the fence-safe heavy trims + let_go_idle sweeps that were previously gated only on critical_commit() (OS commit headroom), which never fires on a 16 GB box with a large pagefile. Inert and behavior-identical when the var is unset/0: no new sample or branch taken. Rate-limited to the existing ~1 Hz sweep; logs one line (avail MB, freed MB, host copies/textures alive). trim_idle keeps a tighter idle pool (24 vs 64) under RAM pressure. All existing fence/ownership guards preserved. Verified: cargo test -p victory-gpu --lib -j 4 (495 passed, 0 failed); cargo build --profile diag -p victory --features diagnostics -j 4 (ok). Asset policy: no new violation (only pre-existing .agents .diff + imgui.ini). --- crates/victory-gpu/src/host.rs | 454 ++++++++++++++++++++++++++-- crates/victory-gpu/src/list.rs | 115 ++++++- crates/victory-gpu/src/residency.rs | 257 +++++++++++++++- crates/victory-gpu/src/resource.rs | 221 +++++++++++--- 4 files changed, 964 insertions(+), 83 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 72716f5..2dfa574 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -76,7 +76,17 @@ unsafe impl Sync for Host {} /// releases reach the host at once, from its own threads, while the host /// runs a submission: freeing there is a GPU page fault on the freed /// texture (a device hang). -static RETIRED: Mutex> = Mutex::new(std::collections::VecDeque::new()); +const RETIRED_SHARDS: usize = 16; +static RETIRED: [Mutex>; RETIRED_SHARDS] = + [const { Mutex::new(std::collections::VecDeque::new()) }; RETIRED_SHARDS]; + +fn retired_shard() -> &'static Mutex> { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + thread_local! { + static INDEX: usize = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) & (RETIRED_SHARDS - 1); + } + &RETIRED[INDEX.with(|&i| i)] +} /// Submissions started and finished (waited for). static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -456,10 +466,41 @@ fn sweep() { if crate::residency::pressured() { trim_spare_chunks(); } - if crate::residency::critical_commit() { + // The heavy fence-safe trims fire on OS commit pressure as before, and + // also on physical-RAM pressure when VICTORY_RAM_PRESSURE_MB is set + // (`ram_critical`), which is where this box actually hurts: a large + // pagefile keeps commit headroom wide while free RAM is exhausted. + // `ram_critical()` is always false when the feature is unset, so this + // stays identical to before in that case. + let ram_critical = crate::residency::ram_critical(); + if crate::residency::critical_commit() || ram_critical { + // Measure what the heavy pass sheds, from cheap alive counters, so + // we can see it frees real bytes rather than churning copies. + let before = ram_critical.then(ram_pressure_alive); send::trim_spare(); crate::shadow::trim_snapshot_pool(); crate::list::trim_idle(); + if let Some(before) = before { + // The idle sweeps below do the bulk of the RAM-pressure shed; + // run them first so the freed figure reflects this pass, then + // let the rest of the sweep (pool/library) run as usual. + crate::shadow::let_go_idle(); + crate::texture::let_go_idle(); + crate::resource::let_go_idle(); + let after = ram_pressure_alive(); + let freed = before.saturating_sub(after); + tracing::info!( + target: "victory_gpu::residency", + available_physical_mib = crate::residency::avail_phys_mib(), + freed_mib = freed >> 20, + host_copies_alive_mib = crate::shadow::live_span_bytes() >> 20, + host_textures_alive_mib = crate::resource::host_textures_alive_bytes() >> 20, + "RAM-pressure trimming ran" + ); + crate::pool::room(host().and_then(|h| h.video_memory())); + crate::pipeline::trim_library(); + return; + } } crate::pool::room(host().and_then(|h| h.video_memory())); crate::pipeline::trim_library(); @@ -468,6 +509,16 @@ fn sweep() { crate::resource::let_go_idle(); } +/// Cheaply-read sum of the system-RAM retainers the RAM-pressure sweep can +/// shed: host copies of windows of title memory, host copies of textures, +/// and spare upload scratch. Used only to report how many bytes a pass +/// freed (before/after), never to gate behavior. +fn ram_pressure_alive() -> u64 { + crate::shadow::live_span_bytes() + + crate::resource::host_textures_alive_bytes() + + ALIVE[4].load(Ordering::Relaxed) +} + /// The number of the newest submission begun, and of the newest of which all /// before it have finished too. pub(crate) fn submissions() -> (u64, u64) { @@ -486,7 +537,7 @@ pub(crate) fn retire(object: T) { return; } RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); - RETIRED + retired_shard() .lock() .unwrap_or_else(|e| e.into_inner()) .push_back((started, Retired::Any(Box::new(object)))); @@ -502,7 +553,10 @@ pub(crate) fn retire_resource(object: ID3D12Resource) { return; } RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); - RETIRED.lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object))); + retired_shard() + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push_back((started, Retired::Resource(object))); } /// How many submissions later than it could (the last one that may use it @@ -524,14 +578,14 @@ fn bury_lag() -> u64 { /// those is dropped a little later than it could be. fn bury(finished: u64) { let finished = finished.saturating_sub(bury_lag()); - let done: Vec<(u64, Retired)> = { - let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); + let mut done: Vec<(u64, Retired)> = Vec::new(); + for shard in &RETIRED { + let mut retired = shard.lock().unwrap_or_else(|e| e.into_inner()); let n = retired.iter().take_while(|(at, _)| *at <= finished).count(); - if n == 0 { - return; + if n > 0 { + done.extend(retired.drain(..n)); } - retired.drain(..n).collect() - }; + } drop(done); } @@ -1755,6 +1809,15 @@ impl PlanePass { } } +/// Whether a depth plane a shader wrote through its twin is drawn into the +/// plane right after that draw or dispatch is recorded, not when the list +/// closes (`VICTORY_DEPTH_PLANE_NOW=1`; off by default until measured). +#[cfg(windows)] +pub(crate) fn depth_plane_now() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_DEPTH_PLANE_NOW").is_some_and(|v| v == "1")) +} + /// Records into `list` the pass that draws `plane`, the twin of the depth /// plane of `depth`, into that plane: `depth` in the depth-write state, /// `plane` readable by pixel shaders. The pass sets the list's descriptor @@ -2633,6 +2696,38 @@ impl CardPlan { } } } + + /// Verification mode (`VICTORY_GPU_RO_CHECK=1`): warns if any compared + /// 64 KiB piece that changed on the card overlaps a GPU-read-only region. + fn check_gpu_ro(&self, differs: &[u32]) { + if !crate::shadow::gpu_ro_check() { + return; + } + static WARNED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + for r in self.ranges.iter().filter(|r| !r.picked && r.compared) { + let (base, shadow_len) = r.shadow.span(); + for p in 0..r.span.pieces { + if !differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)) { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + let at = base + lo as u64; + let len = (hi - lo) as u64; + if crate::shadow::overlaps_gpu_readonly(at, len) { + let n = WARNED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 16 || n.is_power_of_two() { + tracing::warn!( + hit = n, + piece = format_args!("{at:#x}..{:#x}", at + len), + declared = format_args!("{:#x}..{:#x}", r.declared.0, r.declared.1), + shadow = format_args!("{base:#x}+{shadow_len:#x}"), + "VICTORY_GPU_RO_CHECK: GPU compare saw changed bytes inside a GPU-read-only region" + ); + } + } + } + } + } } /// What a submission does for copies in the card's memory. @@ -2708,6 +2803,10 @@ struct Deferred { /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. refreshed: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, + /// Per-shadow coalesced span `(copies_index, from, to)` in the current + /// uninterrupted segment: lets `VICTORY_THIN` workers merge overlapping/ + /// adjacent refreshes before the submitting thread walks `copies`. + refreshed_span: std::collections::HashMap>, /// Ranges declared written by shaders since the list last wrote title /// memory (host copy, address, bytes): declaring them again would /// change nothing. @@ -2760,6 +2859,7 @@ impl Deferred { /// date before them is not any more. fn title_written(&mut self) { self.refreshed.clear(); + self.refreshed_span.clear(); self.gpu_written.clear(); self.filled.clear(); self.constants.clear(); @@ -3734,20 +3834,68 @@ pub(crate) fn settle_for_present() { settle_now(WHY_SYNC); } pub(crate) fn settle_for_fence() { + if late() && relay() { + let target = line().target; + relay_wait(WHY_FENCE, |l| { + !l.settling + && !l.line.iter().any(|item| matches!(item, Late::Run(f) if f.fence <= target)) + && (l.line.is_empty() || matches!(l.line.first(), Some(Late::Run(f)) if f.fence > target)) + }); + return; + } settle_now(WHY_FENCE); } +/// Incremented each time completed GPU flights release their dynamic +/// descriptor slots (`relay_land` / `land`), so [`reclaim_dynamic`] wakes +/// immediately without waiting for `victory-late-wait` to finish allocator resets. +static DYNAMIC_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Reclaims dynamic descriptor slots by recycling already-landed host lists +/// immediately, and if none were ready, waits (without holding `host.submitted`) +/// for the next landing instead of draining the whole pipeline under the +/// submission lock. +pub(crate) fn reclaim_dynamic() { + let before = DYNAMIC_EPOCH.load(Ordering::Acquire); + if land() > 0 || DYNAMIC_EPOCH.load(Ordering::Acquire) != before { + return; + } + if late() && relay() { + relay_wait(WHY_FENCE, |l| { + DYNAMIC_EPOCH.load(Ordering::Acquire) != before || (l.line.is_empty() && !l.settling) + }); + return; + } + settle_for_fence(); + let _ = land(); +} + +/// Whether resetting and recycling landed host lists is delegated to the +/// dedicated `victory-late-wait` helper thread instead of blocking the +/// submitting thread after every submission (`VICTORY_LAND_OFF_SUBMIT=0` +/// restores synchronous `land()` on the submitting thread). +fn land_off_submit() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_OFF_SUBMIT").is_none_or(|v| v != "0")) +} + /// Resets the host lists of settled flights and keeps them for reuse, as -/// a queue does for the lists it ran (`crate::list::recycle`). -fn land() { +/// a queue does for the lists it ran (`crate::list::recycle`). Returns how +/// many landed batches were recycled. +fn land() -> usize { let landed: Vec<_> = { let mut line = line(); let n = line.landed.len().saturating_sub(bury_lag() as usize); line.landed.drain(..n).collect() }; + let count = landed.len(); for (lists, order) in landed { crate::list::recycle(lists, &order); } + if count > 0 { + DYNAMIC_EPOCH.fetch_add(1, Ordering::Release); + } + count } #[cfg(test)] @@ -4214,6 +4362,8 @@ mod font; mod menu; mod panel; mod place; +#[cfg(feature = "diagnostics")] +mod refresh_loop; mod send; pub(crate) use send::{goes_as_words, words_under}; #[cfg(feature = "diagnostics")] @@ -4832,7 +4982,7 @@ impl Host { let mut whole: Vec> = Vec::new(); for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) { if shadow.card_make_before(|size| { - let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?; + let before = self.uav_buffer_for_list(crate::shadow::card_hash_bytes(size))?; name(&before, || "title buffer on the card, hashes of its pieces".into()); Some(before) }) { @@ -5183,6 +5333,7 @@ impl Host { let mut seen = std::collections::HashSet::new(); for &(plan, behind) in plans { plan.picked_found(differs); + plan.check_gpu_ro(differs); let flags: Vec<(usize, u32, bool)> = plan .ranges .iter() @@ -5491,6 +5642,9 @@ impl Host { for detached in &mut flight.lists { detached.release_tables(); } + if !flight.lists.is_empty() { + DYNAMIC_EPOCH.fetch_add(1, Ordering::Release); + } landed.push((flight.lists, flight.order)); crate::land::spent(crate::land::stat::READ_BACKS, telling) } @@ -5577,6 +5731,7 @@ impl Host { let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new(); let mut total = 0u64; plan.picked_found(differs); + plan.check_gpu_ro(differs); for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) { for p in 0..r.span.pieces { if r.compared && !torn::flagged(differs[(r.at + p) as usize]) { @@ -5790,8 +5945,30 @@ impl Host { LINE_MOVED.notify_one(); } drop(submitted); - let _landing = crate::timeline::span("landed lists reset and given back"); - land(); + if relay() && land_off_submit() { + let (overflow, wake) = { + let mut l = line(); + let lag = bury_lag() as usize; + let len = l.landed.len(); + if len > lag + 128 { + (true, false) + } else if len > lag { + l.poke = true; + (false, true) + } else { + (false, false) + } + }; + if overflow { + let _landing = crate::timeline::span("landed lists reset and given back"); + land(); + } else if wake { + LINE_MOVED.notify_one(); + } + } else { + let _landing = crate::timeline::span("landed lists reset and given back"); + land(); + } AFTER_SEND.fetch_add(after.elapsed().as_nanos() as u64, Ordering::Relaxed); } @@ -5981,7 +6158,16 @@ impl Host { FINISHED.store(last, Ordering::Release); bury(last); } - line().landed.extend(landed); + let added = !landed.is_empty(); + if added { + let mut l = line(); + l.landed.extend(landed); + if why == WHY_CARD_DONE && relay() && land_off_submit() { + l.poke = true; + drop(l); + LINE_MOVED.notify_one(); + } + } } if counted { self.log_messages(); @@ -6143,7 +6329,7 @@ impl Host { } sweep(); SWEPT.store(now_ms(), Ordering::Relaxed); - } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 { + } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + self.sweep_every_ms() { // With the present sent ahead nothing else brings a moment // with nothing in the air: one is made for the sweep. self.settle(&mut submitted, WHY_SYNC); @@ -7359,6 +7545,39 @@ impl HostList { } } + /// A draw or dispatch that wrote depth planes' twins was just recorded + /// (`VICTORY_DEPTH_PLANE_NOW=1`, [`depth_plane_now`]): each such plane + /// is drawn from its twin here, as the list closing does + /// (`twins_to_depth`), and its stencil plane copied, so that the + /// commands after it see what the shader wrote. + pub(crate) fn planes_now(&self) -> bool { + if !depth_plane_now() { + return false; + } + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + let written: Vec<_> = twins + .values_mut() + .filter(|u| u.twin.plane.is_some() && (u.behind[0] == Some(true) || u.late)) + .map(|u| { + let copy = u.behind[0] == Some(true); + u.behind[0] = Some(false); + u.late = false; + (u.depth.clone(), u.twin.clone(), copy) + }) + .collect(); + drop(twins); + for (depth, twin, copy) in &written { + if *copy { + self.twin_copy(depth, twin, false); + } + self.pass_plane(depth, twin); + } + if !written.is_empty() { + crate::resource::PLANES[3].fetch_add(written.len() as u64, Ordering::Relaxed); + } + !written.is_empty() + } + /// The draw or dispatch just prepared is recorded: the twins it writes /// now hold what their depth textures lack. pub(crate) fn twins_written(&self) { @@ -7760,11 +7979,33 @@ impl HostList { len: usize, ) { let mut deferred = self.deferred(); - let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); + let deferred = &mut *deferred; + let ptr = std::sync::Arc::as_ptr(shadow) as usize; + let end = address.saturating_add(len); + if let Some(&mut (idx, ref mut from, ref mut to)) = deferred.refreshed_span.get_mut(&ptr) + && address <= *to + && end >= *from + { + if *from <= address && end <= *to { + return; + } + let new_from = (*from).min(address); + let new_to = (*to).max(end); + if let Some(Step::Refresh(_, a, l)) = deferred.copies.get_mut(idx) { + *a = new_from; + *l = new_to - new_from; + *from = new_from; + *to = new_to; + return; + } + } + let key = (ptr, address, len); if deferred.refreshed.insert(key) { + let idx = deferred.copies.len(); deferred .copies .push(Step::Refresh(shadow.clone(), address, len)); + deferred.refreshed_span.insert(ptr, (idx, address, end)); } } @@ -7780,7 +8021,9 @@ impl HostList { len: usize, ) { let mut deferred = self.deferred(); - let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); + let ptr = std::sync::Arc::as_ptr(shadow) as usize; + deferred.refreshed_span.remove(&ptr); + let key = (ptr, address, len); if deferred.gpu_written.insert(key) || !declare_once() { deferred.has_gpu_write = true; deferred.copies.push(Step::GpuWrite(shadow.clone(), address, len)); @@ -7922,7 +8165,7 @@ impl HostList { return None; } self.list.cast::().ok()?; - let buffer = host()?.uav_buffer(256)?; + let buffer = host()?.uav_buffer_for_list(256)?; name(&buffer, || "indirect budget".to_owned()); Some(buffer) } @@ -8004,7 +8247,7 @@ impl HostList { .saturating_mul(2) .max(needed) .next_multiple_of(64 << 10); - let buffer = host()?.uav_buffer(alloc)?; + let buffer = host()?.uav_buffer_for_list(alloc)?; name(&buffer, || format!("indirect arguments {alloc:#x}")); let old = slot.replace((buffer.clone(), alloc)); drop(slot); @@ -8026,7 +8269,7 @@ impl HostList { let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES); if buffer == args.0.len() { let size = u64::from(BATCHES * JOBS * SLOT); - let made = host()?.uav_buffer(size)?; + let made = host()?.uav_buffer_for_list(size)?; name(&made, || format!("indirect batches {size:#x}")); args.0.push(made); } @@ -8530,6 +8773,7 @@ fn submit_split_line(frames: f64) { /// More of the preparing, per frame, for the frame-rate line (diagnostics). #[cfg(feature = "diagnostics")] fn split_line(frames: f64) { + refresh_loop::line(frames); let e: Vec = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect(); let a: Vec = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect(); let h: Vec = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); @@ -8546,7 +8790,8 @@ fn split_line(frames: f64) { written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \ bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \ waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \ - as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)", + as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED); kernel_written: calls {:.0} (refused ones \ + among them), pages_walked {:.0} (4 KiB pages in the ranges asked), ms {:.2} (whole calls)", a[0], a[1] / 1024.0, a[11] / 1e6, @@ -8564,6 +8809,9 @@ fn split_line(frames: f64) { s[1] / 1048576.0, s[2] / 1048576.0, s[3], + a[13], + a[14], + a[15] / 1e6, ); tracing::info!( "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures; the \ @@ -9031,9 +9279,15 @@ impl Batch { } let started = std::time::Instant::now(); if !(crate::watch::light() && shadow.nothing_new(from, to - from)) { + #[cfg(feature = "diagnostics")] + let updating = std::time::Instant::now(); Self::update(&shadow, from, to); + #[cfg(feature = "diagnostics")] + refresh_loop::updated(refresh_loop::ONE, updating, 1, 0); } let ns = started.elapsed().as_nanos() as u64; + #[cfg(feature = "diagnostics")] + refresh_loop::ran(refresh_loop::ONE, ns); SPLIT[6].fetch_add(ns, Ordering::Relaxed); SPLIT[9].fetch_add(ns, Ordering::Relaxed); SPLIT[10].fetch_add(1, Ordering::Relaxed); @@ -9123,6 +9377,8 @@ impl Batch { const FEW: usize = 256; const CHUNK: usize = 64; let spans = std::sync::Arc::new(spans); + #[cfg(feature = "diagnostics")] + let checking = std::time::Instant::now(); let dirty: Vec = if spans.len() <= FEW { let j = crate::watch::read_journal(); let mut keep = Vec::with_capacity(spans.len()); @@ -9163,6 +9419,8 @@ impl Batch { .filter_map(|(i, f)| f.load(Ordering::Relaxed).then_some(i)) .collect() }; + #[cfg(feature = "diagnostics")] + refresh_loop::checked(refresh_loop::FRONT, spans.len() > FEW, checking, spans.len()); let ahead = dirty.len() > 1 && !crate::watch::kept_active(); if ahead { let ranges: Vec<(usize, usize)> = dirty @@ -9175,8 +9433,12 @@ impl Batch { } FLUSHES[3].fetch_add(spans.len() as u64, Ordering::Relaxed); let work = dirty.len() + due.len(); + #[cfg(feature = "diagnostics")] + let (updating, updates, textures) = (std::time::Instant::now(), dirty.len(), due.len()); if work > 0 { crate::shadow::wide_each(work, move |i| { + #[cfg(feature = "diagnostics")] + let _timed = refresh_loop::OnThread::new(refresh_loop::FRONT, i < due.len()); // The textures first: they are the longer pieces. let Some(i) = i.checked_sub(due.len()) else { due[i].refresh(); @@ -9186,6 +9448,8 @@ impl Batch { Self::update(shadow, *from, *to); }); } + #[cfg(feature = "diagnostics")] + refresh_loop::updated(refresh_loop::FRONT, updating, updates, textures); if ahead { crate::watch::ask_ahead_done(); } @@ -9196,6 +9460,8 @@ impl Batch { PREPARING[0].fetch_sub(summed[0], Ordering::Relaxed); PREPARING[0].fetch_add(took, Ordering::Relaxed); SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + refresh_loop::ran(refresh_loop::FRONT, started.elapsed().as_nanos() as u64); } /// Before the steps of `runs` ([`ahead_of_writes`]); copies and fills @@ -9230,16 +9496,46 @@ impl Batch { } let started = std::time::Instant::now(); let before = PREPARING[0].load(Ordering::Relaxed); - crate::shadow::wide_each(due.len(), move |i| { - let (shadow, from, to) = &due[i]; - if !shadow.nothing_new(*from, *to - *from) { - Self::update(shadow, *from, *to); + const CHUNK: usize = 32; + let chunks = due.len().div_ceil(CHUNK); + crate::shadow::wide_each(chunks, move |c| { + let start = c * CHUNK; + let end = (start + CHUNK).min(due.len()); + let mut dirty = [false; CHUNK]; + let mut any = false; + #[cfg(feature = "diagnostics")] + let checking = std::time::Instant::now(); + { + let j = crate::watch::read_journal(); + for i in start..end { + let (shadow, from, to) = &due[i]; + if !shadow.nothing_new_in(&j, *from, *to - *from) { + dirty[i - start] = true; + any = true; + } + } + } + #[cfg(feature = "diagnostics")] + refresh_loop::thread_checked(refresh_loop::AHEAD, checking, end - start); + if any { + #[cfg(feature = "diagnostics")] + let updating = std::time::Instant::now(); + for i in start..end { + if dirty[i - start] { + let (shadow, from, to) = &due[i]; + Self::update(shadow, *from, *to); + } + } + #[cfg(feature = "diagnostics")] + refresh_loop::thread_updated(refresh_loop::AHEAD, updating, dirty.iter().filter(|&&d| d).count()); } }); // The time counted is the time it took, not the threads' sum. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before); PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed); let ns = started.elapsed().as_nanos() as u64; + #[cfg(feature = "diagnostics")] + refresh_loop::ran(refresh_loop::AHEAD, ns); SPLIT[6].fetch_add(ns, Ordering::Relaxed); SPLIT[9].fetch_add(ns, Ordering::Relaxed); } @@ -9318,6 +9614,8 @@ impl Batch { let _flush = crate::timeline::span("refreshes of copies"); self.flush_all(); SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + refresh_loop::ran(refresh_loop::FLUSH, began.elapsed().as_nanos() as u64); FLUSHES[0].fetch_add(1, Ordering::Relaxed); FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed); } @@ -9337,6 +9635,8 @@ impl Batch { self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new_in(&j, *from, *to - *from)); drop(j); PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + refresh_loop::checked(refresh_loop::FLUSH, false, started, all); FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed); if self.refreshes.is_empty() { return; @@ -9373,6 +9673,8 @@ impl Batch { let chunks = refreshes.len().div_ceil(CHUNK); let r_ref = refreshes.clone(); let f_ref = flags.clone(); + #[cfg(feature = "diagnostics")] + let checking = std::time::Instant::now(); crate::shadow::wide_each(chunks, move |c| { let start = c * CHUNK; let end = (start + CHUNK).min(r_ref.len()); @@ -9390,22 +9692,32 @@ impl Batch { FLUSHES[2].fetch_add(skipped, Ordering::Relaxed); } }); + #[cfg(feature = "diagnostics")] + refresh_loop::checked(refresh_loop::FLUSH, true, checking, refreshes.len()); let dirty: Vec = flags .iter() .enumerate() .filter_map(|(i, f)| f.load(Ordering::Relaxed).then_some(i)) .collect(); if !dirty.is_empty() { + #[cfg(feature = "diagnostics")] + let (updating, updates) = (std::time::Instant::now(), dirty.len()); crate::shadow::wide_each(dirty.len(), move |i| { let (shadow, from, to) = &refreshes[dirty[i]]; Self::update(shadow, *from, *to); }); + #[cfg(feature = "diagnostics")] + refresh_loop::updated(refresh_loop::FLUSH, updating, updates, 0); } } else { + #[cfg(feature = "diagnostics")] + let (updating, updates) = (std::time::Instant::now(), refreshes.len()); crate::shadow::wide_each(refreshes.len(), move |i| { let (shadow, from, to) = &refreshes[i]; Self::update(shadow, *from, *to); }); + #[cfg(feature = "diagnostics")] + refresh_loop::updated(refresh_loop::FLUSH, updating, updates, 0); } } else { let jobs: Vec> = self @@ -9413,14 +9725,22 @@ impl Batch { .drain(..) .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box) .collect(); + #[cfg(feature = "diagnostics")] + let (updating, updates) = (std::time::Instant::now(), jobs.len()); crate::shadow::wide_run(jobs); + #[cfg(feature = "diagnostics")] + refresh_loop::updated(refresh_loop::FLUSH, updating, updates, 0); } let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before); PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed); } else { + #[cfg(feature = "diagnostics")] + let (updating, updates) = (std::time::Instant::now(), self.refreshes.len()); for (shadow, from, to) in self.refreshes.drain(..) { Self::update(&shadow, from, to); } + #[cfg(feature = "diagnostics")] + refresh_loop::updated(refresh_loop::FLUSH, updating, updates, 0); } if ahead { crate::watch::ask_ahead_done(); @@ -9747,6 +10067,9 @@ fn read(src: *const u8, dst: *mut u8, len: usize) -> bool { fn read_plain(src: *const u8, dst: *mut u8, len: usize) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; + // Timed and counted by the faults taken meanwhile, until it returns. + #[cfg(feature = "diagnostics")] + let _call = crate::copystat::ReadCall::begin(); if crate::safecopy::on() { // SAFETY: the destination is mapped writable memory of `len` bytes; // a source page that is not there fails the copy. @@ -10153,11 +10476,13 @@ impl Meter { { let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); let wc_left = crate::shadow::WC_LEFT.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames; - if passes + compares + wc_left > 0.0 { + let gpu_ro_left = crate::shadow::GPU_RO_LEFT.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames; + if passes + compares + wc_left + gpu_ro_left > 0.0 { tracing::info!( "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \ ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes; \ - {wc_left:.1} MB declared written in write-combined memory left on the card (VICTORY_WC_NO_BACK)", + {wc_left:.1} MB declared written in write-combined memory left on the card (VICTORY_WC_NO_BACK); \ + {gpu_ro_left:.1} MB declared written in GPU-read-only memory left out (VICTORY_GPU_RO_SKIP=1)", if rehash_runs() { "on" } else { "off" } ); } @@ -10457,6 +10782,13 @@ impl Meter { per_frame(6) / 1e3 ); } + let [bg_kept, bg_skipped] = + [0, 1].map(|i| crate::list::BARRIER_GROUPS_STATS[i].swap(0, Ordering::Relaxed)); + if bg_kept + bg_skipped > 0 { + tracing::info!( + "enhanced barrier groups (VICTORY_SMART_BARRIERS): {bg_kept} kept, {bg_skipped} skipped in the last 5 seconds" + ); + } let [raw_srv, raw_uav] = crate::descriptor::host::raw_view_counts(); tracing::info!( "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ @@ -10477,13 +10809,14 @@ impl Meter { du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed), du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed), refused = format!( - "{} ({} copies made of views off their buffer's elements); depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass", + "{} ({} copies made of views off their buffer's elements); depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass, {} drawn right after their shader (VICTORY_DEPTH_PLANE_NOW)", crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed), crate::shadow::OWN_MADE.load(Ordering::Relaxed), crate::resource::TWINS[0].load(Ordering::Relaxed), crate::resource::TWINS[1].load(Ordering::Relaxed), crate::resource::PLANES[1].load(Ordering::Relaxed), - crate::resource::PLANES[2].load(Ordering::Relaxed) + crate::resource::PLANES[2].load(Ordering::Relaxed), + crate::resource::PLANES[3].load(Ordering::Relaxed) ), making = crate::pipeline::making(), placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed), @@ -11100,6 +11433,44 @@ impl Host { /// bytes: the budget and the use of the card's own memory, then of the /// PC's memory shared with the card (where the system moves what does /// not fit on the card). + /// How long between sweeps made behind flights (`VICTORY_SWEEP_EVERY_MS`, + /// 15,000 ms while neither host nor card memory is pressed; 1,500 ms while + /// pressed so idle textures still evict promptly). + fn sweep_every_ms(&self) -> u64 { + const PRESSED_MS: u64 = 1500; + static EVERY: OnceLock = OnceLock::new(); + let every = *EVERY.get_or_init(|| { + std::env::var("VICTORY_SWEEP_EVERY_MS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(15_000) + }); + if every <= PRESSED_MS { + return every; + } + static LOOKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + static PRESSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + let now = now_ms(); + if now >= LOOKED.load(Ordering::Relaxed) + 500 { + LOOKED.store(now, Ordering::Relaxed); + crate::residency::refresh(); + let card = self + .video_memory() + .is_none_or(|[budget, used, ..]| { + used.saturating_sub(crate::pool::texture_room()) >= crate::resource::room_line(budget) + }); + let pressed = crate::residency::pressured() || card; + if PRESSED.swap(pressed, Ordering::Relaxed) != pressed { + tracing::info!( + pressed, + every_ms = if pressed { PRESSED_MS } else { every }, + "sweeps behind flights" + ); + } + } + if PRESSED.load(Ordering::Relaxed) { PRESSED_MS } else { every } + } + pub(crate) fn video_memory(&self) -> Option<[u64; 4]> { let adapter = self.adapter.as_ref()?; let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); @@ -11199,6 +11570,12 @@ impl Host { self.shared_buffer_impl(size, true) } + /// [`Host::shared_buffer`], made now without blocking on the copy-queue + /// `mapped()` fence wait (for buffers only used by lists submitted later). + pub(crate) fn shared_buffer_now_unmapped(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + self.shared_buffer_impl(size, false) + } + /// [`Host::shared_buffer`] for a command list upload without blocking on the /// copy-queue `mapped()` fence wait. pub(crate) fn shared_buffer_for_list(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { @@ -11356,6 +11733,18 @@ impl Host { /// A device-local buffer shaders may write (unordered access) and indirect /// execution may read, starting in the common state. pub(crate) fn uav_buffer(&self, size: u64) -> Option { + self.uav_buffer_impl(size, true) + } + + /// [`Host::uav_buffer`] for command-list-owned scratch buffers (indirect + /// argument batches, clamp budgets, card hash buffers) that are only read + /// by lists submitted after creation, skipping the global copy-queue + /// `mapped()` fence wait. + pub(crate) fn uav_buffer_for_list(&self, size: u64) -> Option { + self.uav_buffer_impl(size, false) + } + + fn uav_buffer_impl(&self, size: u64, wait_mapped: bool) -> Option { MADE[4].fetch_add(1, Ordering::Relaxed); MADE[5].fetch_add(size, Ordering::Relaxed); let heap = D3D12_HEAP_PROPERTIES { @@ -11392,7 +11781,8 @@ impl Host { if let Some(b) = &buffer { crate::book::made(b, || "an unordered access buffer".into()); } - let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| resident(&self.device, b))).and_then(|()| mapped(&self.device)); + let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| resident(&self.device, b))); + let made = if wait_mapped { made.and_then(|()| mapped(&self.device)) } else { made }; match made { Ok(()) => buffer, Err(e) => { diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 32435ad..67e1fc6 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -422,12 +422,18 @@ pub(crate) fn recycle(lists: Vec, ran: &[usize]) { #[cfg(windows)] pub(crate) fn trim_idle() { const PRESSURED_KEEP: usize = 64; + // Under physical-RAM pressure (VICTORY_RAM_PRESSURE_MB) keep a tighter + // but still generous idle pool so loose allocators are shed, without + // cutting below what a steady frame reuses. Unchanged (64) when the + // feature is off, since `ram_critical()` is then always false. + const RAM_CRITICAL_KEEP: usize = 24; + let keep = if crate::residency::ram_critical() { RAM_CRITICAL_KEEP } else { PRESSURED_KEEP }; let freed: Vec = { let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); - if idle.0.len() <= PRESSURED_KEEP { + if idle.0.len() <= keep { return; } - let dropped = idle.0.split_off(PRESSURED_KEEP); + let dropped = idle.0.split_off(keep); let dropped_bytes: u64 = dropped.iter().map(|Idle(_, b, _)| *b).sum(); idle.1 = idle.1.saturating_sub(dropped_bytes); dropped @@ -2344,12 +2350,113 @@ extern "system" fn wait_value64(this: This, address: u64, comparison: u32, refer wait_for(this, address, comparison, reference, true); } +/// Whether enhanced barrier groups are inspected before emitting a full +/// global UAV barrier (`VICTORY_SMART_BARRIERS=1`, off by default: skipping +/// non-UAV barriers can omit state syncs for render targets/lighting buffers). +#[cfg(windows)] +fn smart_barriers() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SMART_BARRIERS").is_some_and(|v| v == "1")) +} + +/// Enhanced barrier groups `[kept, skipped]` since the last log interval. +#[cfg(windows)] +pub(crate) static BARRIER_GROUPS_STATS: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Returns `true` if the enhanced barrier groups in `groups[0..count]` require +/// a global UAV synchronization barrier (ordering a prior shader UAV write), +/// or `false` if they are purely non-UAV transitions (e.g. RT/DSV/copy texture +/// layout transitions that our texture state tracker already emits explicitly, +/// or `SYNC_NONE` / `NO_ACCESS` barriers). +#[cfg(windows)] +pub(crate) fn barrier_groups_needs_uav(count: u32, groups: *const u8) -> bool { + use windows::Win32::Graphics::Direct3D12::*; + if count == 0 { + return false; + } + if !smart_barriers() || groups.is_null() || count > 64 { + BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + let needs_access = |sync_before: D3D12_BARRIER_SYNC, access_before: D3D12_BARRIER_ACCESS| -> bool { + if sync_before == D3D12_BARRIER_SYNC_NONE { + return false; + } + // `COMMON` (0) or `UNORDERED_ACCESS` (0x80) may order a prior UAV write; + // pure RT/DSV/copy/SRV/no-access transitions do not need a global UAV drain. + access_before == D3D12_BARRIER_ACCESS_COMMON + || (access_before.0 & D3D12_BARRIER_ACCESS_UNORDERED_ACCESS.0) != 0 + }; + // SAFETY: the title passes `count` valid `D3D12_BARRIER_GROUP` entries + // whose inner barrier arrays are valid for the duration of the call. + let slice = unsafe { std::slice::from_raw_parts(groups.cast::(), count as usize) }; + for g in slice { + let n = g.NumBarriers as usize; + if n == 0 { + continue; + } + if n > 4096 { + BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + match g.Type { + D3D12_BARRIER_TYPE_GLOBAL => { + let p = unsafe { g.Anonymous.pGlobalBarriers }; + if p.is_null() { + BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + let bs = unsafe { std::slice::from_raw_parts(p, n) }; + if bs.iter().any(|b| needs_access(b.SyncBefore, b.AccessBefore)) { + BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + } + D3D12_BARRIER_TYPE_BUFFER => { + let p = unsafe { g.Anonymous.pBufferBarriers }; + if p.is_null() { + BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + let bs = unsafe { std::slice::from_raw_parts(p, n) }; + if bs.iter().any(|b| needs_access(b.SyncBefore, b.AccessBefore)) { + BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + } + D3D12_BARRIER_TYPE_TEXTURE => { + let p = unsafe { g.Anonymous.pTextureBarriers }; + if p.is_null() { + BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + let bs = unsafe { std::slice::from_raw_parts(p, n) }; + if bs.iter().any(|b| needs_access(b.SyncBefore, b.AccessBefore)) { + BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + } + _ => { + BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + } + } + BARRIER_GROUPS_STATS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + false +} + /// The enhanced barriers `(group count, groups)`: buffer, texture and /// global barriers with layouts instead of states. Every host use of a /// title texture (clears, copies) moves its host copy to the state it needs /// first, so only their ordering matters: one barrier on every shader /// write (the title's buffer barriers order compute passes). -extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { +extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { + #[cfg(windows)] + if count == 0 || (!groups.is_null() && !barrier_groups_needs_uav(count, groups)) { + return; + } // Diagnostics: counted, and left out under `VICTORY_BARRIER_TEST=groups`. #[cfg(all(windows, feature = "diagnostics"))] if count > 0 { @@ -2370,7 +2477,7 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { unsafe { list.list.ResourceBarrier(&[barrier]) }; } #[cfg(not(windows))] - let _ = (this, count); + let _ = (this, count, groups); } /// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and diff --git a/crates/victory-gpu/src/residency.rs b/crates/victory-gpu/src/residency.rs index cb7b3bf..496058c 100644 --- a/crates/victory-gpu/src/residency.rs +++ b/crates/victory-gpu/src/residency.rs @@ -7,6 +7,11 @@ const MIB: u64 = 1 << 20; const GIB: u64 = 1 << 30; static PRESSURED: AtomicBool = AtomicBool::new(false); static HEADROOM: AtomicU64 = AtomicU64::new(u64::MAX); +/// Last physical available RAM sampled by [`refresh`] (bytes). `u64::MAX` +/// until the first sample, so [`ram_critical`] stays off before then. +static AVAIL_PHYS: AtomicU64 = AtomicU64::new(u64::MAX); +/// Latched RAM-pressure state for [`ram_critical`]'s hysteresis. +static RAM_CRITICAL: AtomicBool = AtomicBool::new(false); fn memory_status() -> Option { // SAFETY: the API initializes the fields of a correctly sized structure. @@ -15,6 +20,144 @@ fn memory_status() -> Option { (unsafe { GlobalMemoryStatusEx(&mut status) } != 0).then_some(status) } +/// What is left to commit, as the layer's decisions count it: what is left +/// under the system's commit limit now, plus what its pagefiles may still +/// grow by ([`commit_growth`]). +fn available_commit(status: &MEMORYSTATUSEX) -> u64 { + status.ullAvailPageFile.saturating_add(commit_growth(status)) +} + +/// How much more the system's commit limit can grow: Windows grows a +/// system-managed pagefile when commit reaches the limit, up to three times +/// RAM (at least 4 GB) and an eighth of its volume, and a custom one up to its +/// maximum, capped by free volume space less 8 GB. +/// `VICTORY_COMMIT_GROWTH=0`: the limit of the moment alone, as before. +fn commit_growth(status: &MEMORYSTATUSEX) -> u64 { + static OFF: OnceLock = OnceLock::new(); + if *OFF.get_or_init(|| std::env::var_os("VICTORY_COMMIT_GROWTH").is_some_and(|v| v == "0")) { + return 0; + } + static FILES: OnceLock> = OnceLock::new(); + let files = FILES.get_or_init(|| { + let files = pagefiles(); + let said: Vec = files + .iter() + .map(|f| match f.max_mb { + Some(mb) => format!("{} up to {mb} MB", f.root), + None => format!("{} system-managed", f.root), + }) + .collect(); + tracing::info!( + pagefiles = ?said, + commit_limit_mib = status.ullTotalPageFile >> 20, + "pagefiles: commit can grow beyond the limit of the moment (VICTORY_COMMIT_GROWTH=0: not counted)" + ); + files + }); + if files.is_empty() { + return 0; + } + static NEXT: AtomicU64 = AtomicU64::new(0); + static GROWTH: AtomicU64 = AtomicU64::new(0); + let now = crate::host::coarse_ms(); + let next = NEXT.load(Ordering::Relaxed); + if now >= next + && NEXT + .compare_exchange(next, now.saturating_add(5000), Ordering::Relaxed, Ordering::Relaxed) + .is_ok() + { + let size_now = status.ullTotalPageFile.saturating_sub(status.ullTotalPhys); + let mut most = 0u64; + let mut room = 0u64; + let mut roots: Vec<&str> = Vec::new(); + for file in files { + let Some((total, free)) = volume_space(&file.root) else { continue }; + most += match file.max_mb { + Some(mb) => mb * MIB, + None => (3 * status.ullTotalPhys).max(4 * GIB).min(total / 8), + }; + if !roots.contains(&file.root.as_str()) { + roots.push(&file.root); + room += free.saturating_sub(8 * GIB); + } + } + GROWTH.store(most.saturating_sub(size_now).min(room), Ordering::Relaxed); + } + GROWTH.load(Ordering::Relaxed) +} + +struct Pagefile { + root: String, + max_mb: Option, +} + +fn pagefiles() -> Vec { + use windows_sys::Win32::System::Registry::{HKEY_LOCAL_MACHINE, RRF_RT_REG_MULTI_SZ, RegGetValueW}; + let wide = |s: &str| s.encode_utf16().chain([0]).collect::>(); + let key = wide(r"SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management"); + let value = wide("PagingFiles"); + let mut bytes = 0u32; + // SAFETY: a size query, then the read into a buffer of that size. + let sized = unsafe { + RegGetValueW( + HKEY_LOCAL_MACHINE, + key.as_ptr(), + value.as_ptr(), + RRF_RT_REG_MULTI_SZ, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut bytes, + ) + }; + if sized != 0 || bytes == 0 { + return Vec::new(); + } + let mut buffer = vec![0u16; (bytes as usize).div_ceil(2)]; + // SAFETY: as above; the buffer holds `bytes` bytes. + let read = unsafe { + RegGetValueW( + HKEY_LOCAL_MACHINE, + key.as_ptr(), + value.as_ptr(), + RRF_RT_REG_MULTI_SZ, + std::ptr::null_mut(), + buffer.as_mut_ptr().cast(), + &mut bytes, + ) + }; + if read != 0 { + return Vec::new(); + } + let system_drive = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".into()); + let len = (bytes as usize / 2).min(buffer.len()); + String::from_utf16_lossy(&buffer[..len]) + .split('\0') + .filter_map(|entry| parse_pagefile(entry, &system_drive)) + .collect() +} + +fn parse_pagefile(entry: &str, system_drive: &str) -> Option { + let mut parts = entry.split_whitespace(); + let path = parts.next()?; + let drive = path.get(..2).filter(|d| d.ends_with(':'))?; + let drive = if drive.starts_with('?') { system_drive.get(..2)? } else { drive }; + let sizes: Vec = parts.filter_map(|p| p.parse().ok()).collect(); + let max_mb = match sizes.as_slice() { + [_, max] if *max > 0 => Some(*max), + _ => None, + }; + Some(Pagefile { root: format!(r"{}\", drive.to_ascii_uppercase()), max_mb }) +} + +fn volume_space(root: &str) -> Option<(u64, u64)> { + use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW; + let wide: Vec = root.encode_utf16().chain([0]).collect(); + let (mut free, mut total, mut total_free) = (0u64, 0u64, 0u64); + // SAFETY: a path and three out-values of ours. + let ok = unsafe { GetDiskFreeSpaceExW(wide.as_ptr(), &mut free, &mut total, &mut total_free) } != 0; + ok.then_some((total, free)) +} + // The texture sweep may run for seconds inside a single submitted frame. static NEXT_COMMIT_SAMPLE: AtomicU64 = AtomicU64::new(0); static AVAILABLE_COMMIT: AtomicU64 = AtomicU64::new(u64::MAX); @@ -50,7 +193,7 @@ fn sample_commit(now: u64) -> u64 { .is_ok() && let Some(status) = memory_status() { - AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed); + AVAILABLE_COMMIT.store(available_commit(&status), Ordering::Relaxed); } AVAILABLE_COMMIT.load(Ordering::Relaxed) } @@ -114,8 +257,10 @@ fn next_pressure(was: bool, physical: u64, commit: u64) -> bool { /// Called by the once-per-second submission sweep. A failed sample keeps the last good state. pub(crate) fn refresh() { let Some(status) = memory_status() else { return }; - let (physical, commit) = (status.ullAvailPhys, status.ullAvailPageFile); + let (physical, commit) = (status.ullAvailPhys, available_commit(&status)); HEADROOM.store(physical.min(commit), Ordering::Relaxed); + AVAIL_PHYS.store(physical, Ordering::Relaxed); + refresh_ram_critical(physical); let was = pressured(); let pressure = next_pressure(was, physical, commit); if pressure != was { @@ -147,6 +292,45 @@ pub(crate) fn pressured() -> bool { PRESSURED.load(Ordering::Relaxed) } +/// How long host copies of placed textures whose title memory is no longer +/// mapped may stay cached when host memory is tight: 5 s below a quarter of +/// RAM (at most 16 GiB left), 1 s below 8 GiB. `VICTORY_HOST_TEXTURE_SWEEP=0` +/// restores the card-only rule. +pub(crate) fn host_texture_idle_ms() -> Option { + static ON: OnceLock = OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_HOST_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { + return None; + } + host_texture_idle_for(headroom()?, total_physical()) +} + +pub(crate) fn host_room_low() -> bool { + host_texture_idle_ms().is_some() +} + +fn total_physical() -> u64 { + static TOTAL: OnceLock = OnceLock::new(); + *TOTAL.get_or_init(|| memory_status().map_or(0, |s| s.ullTotalPhys)) +} + +fn host_texture_idle_for(head: u64, total: u64) -> Option { + // Only engage the unmapped host-texture sweep on >20 GiB RAM hosts where + // large system-RAM caches can accumulate without triggering VRAM eviction. + // On 16 GiB / 6 GiB VRAM hosts, physical headroom is routinely <8 GiB and + // overriding the card's VRAM sweep starves GPU texture blocks. + if total <= 20 * GIB { + return None; + } + let line = (total / 4).min(16 * GIB); + if head < 8 * GIB { + Some(1_000) + } else if head < line { + Some(5_000) + } else { + None + } +} + /// True when OS commit headroom is critically low (< 1.5 GiB) or an allocation /// just failed with `E_OUTOFMEMORY`, requiring emergency throttling. pub(crate) fn critical_commit() -> bool { @@ -154,6 +338,51 @@ pub(crate) fn critical_commit() -> bool { now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) || sample_commit(now) < 1536 * MIB } +/// `VICTORY_RAM_PRESSURE_MB`: when set to N > 0, the physical-RAM threshold +/// (in MiB) below which the once-a-second host sweep also runs the heavy +/// fence-safe trims that are otherwise gated on OS commit headroom +/// ([`critical_commit`]). On a 16 GB box the pagefile keeps commit headroom +/// wide while physical RAM is exhausted, so those trims never fire; this +/// re-points them at physical RAM. Parsed once; unset or 0 leaves the whole +/// feature inert (no new sample, no new branch taken anywhere). +fn ram_pressure_bytes() -> Option { + static THRESHOLD: OnceLock> = OnceLock::new(); + *THRESHOLD.get_or_init(|| { + let mb: u64 = std::env::var("VICTORY_RAM_PRESSURE_MB").ok()?.trim().parse().ok()?; + (mb > 0).then(|| mb * MIB) + }) +} + +/// Recompute the latched RAM-pressure state from a fresh physical-RAM +/// sample, with hysteresis: enter below the threshold, leave only once free +/// RAM climbs past the threshold plus a margin, so it does not flap around +/// the line. A no-op when the feature is off. Called from [`refresh`]. +fn refresh_ram_critical(physical: u64) { + let Some(threshold) = ram_pressure_bytes() else { return }; + const MARGIN: u64 = 256 * MIB; + let was = RAM_CRITICAL.load(Ordering::Relaxed); + let now = if was { physical <= threshold + MARGIN } else { physical < threshold }; + if now != was { + RAM_CRITICAL.store(now, Ordering::Relaxed); + } +} + +/// True only when `VICTORY_RAM_PRESSURE_MB` is set to N > 0 and the last +/// sampled physical available RAM is under N MiB (with hysteresis). Reads a +/// cached atomic, so it is cheap to call from the hot path; it is always +/// false when the feature is unset, which keeps today's behavior unchanged. +pub(crate) fn ram_critical() -> bool { + ram_pressure_bytes().is_some() && RAM_CRITICAL.load(Ordering::Relaxed) +} + +/// Last physical available RAM sampled by [`refresh`], in bytes, if the +/// RAM-pressure feature is on and a sample has been taken. For the sweep's +/// one-line pressure log. +pub(crate) fn avail_phys_mib() -> Option { + let bytes = AVAIL_PHYS.load(Ordering::Relaxed); + (bytes != u64::MAX).then(|| bytes >> 20) +} + /// A soft per-frame admission limit. A single texture can cross it. The /// queue retains unserved slots so they can be retried on later frames. pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, critical: bool, limited: bool, staging: u64) -> u64 { @@ -206,4 +435,28 @@ mod tests { assert_eq!(prefetch_limit(512 << 20, true, true, false, 0), 16 << 20); assert_eq!(prefetch_limit(192 << 20, false, false, false, 0), 192 << 20); } + + #[test] + fn pagefile_entries_say_their_volume_and_largest_size() { + let f = parse_pagefile(r"?:\pagefile.sys", "C:").unwrap(); + assert_eq!((f.root.as_str(), f.max_mb), (r"C:\", None)); + let f = parse_pagefile(r"d:\pagefile.sys 0 0", "C:").unwrap(); + assert_eq!((f.root.as_str(), f.max_mb), (r"D:\", None)); + let f = parse_pagefile(r"C:\pagefile.sys 16384 49152", "C:").unwrap(); + assert_eq!((f.root.as_str(), f.max_mb), (r"C:\", Some(49152))); + assert!(parse_pagefile("", "C:").is_none()); + } + + #[test] + fn host_texture_idle_follows_host_commit_not_only_the_card() { + assert_eq!(host_texture_idle_for(20 * GIB, 64 * GIB), None); + assert_eq!(host_texture_idle_for(16 * GIB, 64 * GIB), None); + assert_eq!(host_texture_idle_for(15 * GIB, 64 * GIB), Some(5_000)); + assert_eq!(host_texture_idle_for(8 * GIB, 64 * GIB), Some(5_000)); + assert_eq!(host_texture_idle_for(7 * GIB, 64 * GIB), Some(1_000)); + assert_eq!(host_texture_idle_for(9 * GIB, 32 * GIB), None); + assert_eq!(host_texture_idle_for(7 * GIB, 32 * GIB), Some(1_000)); + assert_eq!(host_texture_idle_for(3 * GIB, 16 * GIB), None); + assert_eq!(host_texture_idle_for(1 * GIB, 0), None); + } } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 5638f35..3d92035 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -391,10 +391,12 @@ pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 4] = /// frame-rate line; and since the start, how often a depth plane's twin /// lacked what was written to the plane (not given to it), and how often a /// depth plane was used in the list that had written its twin, before the -/// pass (which runs when the list closes). +/// pass (which runs when the list closes); and since the start, the +/// planes drawn right after the shader that wrote their twin +/// (`crate::host::depth_plane_now`). #[cfg(windows)] -pub(crate) static PLANES: [std::sync::atomic::AtomicU64; 3] = - [const { std::sync::atomic::AtomicU64::new(0) }; 3]; +pub(crate) static PLANES: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; /// The colour twin of title texture `this`, if it has one. #[cfg(windows)] @@ -1298,6 +1300,10 @@ struct Hosted { used: std::sync::atomic::AtomicU64, /// The host refused to make it: not tried again. refused: std::sync::atomic::AtomicBool, + /// When the card last had no room for it (`crate::host::moment`; 0: + /// never): it is tried again on a use after [`NO_ROOM_AGAIN_MS`] + /// ([`NoTexture::ForNow`]). + no_room: std::sync::atomic::AtomicU64, /// Its host copy was let go as idle once. gone: std::sync::atomic::AtomicBool, /// A texture of [`PLACED_TEXTURES`]. @@ -1571,6 +1577,7 @@ pub(crate) fn want_level(this: This, first: u32) { HELD[2].fetch_add(1, Relaxed); if let Some(old) = made.take() { REPLACED.lock().unwrap_or_else(|e| e.into_inner()).push((crate::host::moment(), old)); + crate::descriptor::host::invalidate_list_views(); } } @@ -1831,6 +1838,12 @@ fn hosted(this: This, make: bool) -> Option { if !make || r.host.refused.load(Relaxed) { return None; } + // The card had no room for it a moment ago: not asked again on + // every use (`NO_ROOM_AGAIN_MS`). + let no_room = r.host.no_room.load(Relaxed); + if no_room != 0 && !crate::host::long_ago(no_room, NO_ROOM_AGAIN_MS, 0) { + return None; + } let clear = r .host .clear @@ -1862,7 +1875,7 @@ fn hosted(this: This, make: bool) -> Option { && (!crate::texture::committed(r.data().cast_const(), bytes as usize) || crate::descriptor::host::next_start(start, start.saturating_add(bytes)).is_some() || crate::descriptor::host::first_viewed(start).is_some_and(|first| first > 0)); - let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true) } else { None }; + let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true).ok() } else { None }; let cut = reserved .as_ref() .zip(crate::host::host()) @@ -1892,13 +1905,30 @@ fn hosted(this: This, make: bool) -> Option { } } let texture = match texture { - Some(texture) => Some(texture), + Some(texture) => Ok(texture), None => host_texture(&r.desc.levels_from(base), r.host.state, clear), }; - let Some(texture) = texture else { - r.host.refused.store(true, Relaxed); - return None; + let texture = match texture { + Ok(texture) => texture, + Err(NoTexture::Refused) => { + r.host.refused.store(true, Relaxed); + return None; + } + // Upstream VIctory #3198 / sagouindupm/Mandy 94fa12a: a texture + // whose host texture could not be made kept that answer for the + // run, so a texture first asked for while the card was full read + // black to the end. Out of room is not a refusal: retry later. + Err(NoTexture::ForNow) => { + r.host.no_room.store(crate::host::moment().max(1), Relaxed); + #[cfg(feature = "diagnostics")] + NOT_MADE_FOR_NOW.fetch_add(1, Relaxed); + return None; + } }; + if r.host.no_room.swap(0, Relaxed) != 0 { + #[cfg(feature = "diagnostics")] + MADE_AFTER_NO_ROOM.fetch_add(1, Relaxed); + } let twin = twin_texture(&r.desc, &texture); // One line per depth texture with unordered access: its address is // the one target dumps and the captured frame's list of commands @@ -2014,7 +2044,7 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { // world makes in its first frame ([`targets_room_kept`]) counts as // used. Some([budget, used, ..]) => { - used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() + targets_room_kept() + used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() + targets_room_kept(budget) < room_line(budget) } None => filled < WITHOUT_BUDGET, @@ -2049,15 +2079,16 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { /// for targets against a line of 9,527 MB). The reserve comes back when /// the targets grow by 64 MiB again (a new scene's), for as long again. #[cfg(windows)] -pub(crate) fn targets_room_kept() -> u64 { +pub(crate) fn targets_room_kept(budget: u64) -> u64 { use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; - static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); - let most = *MOST.get_or_init(|| { + static ASKED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let asked = *ASKED.get_or_init(|| { std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_MB") .ok() .and_then(|v| v.trim().parse::().ok()) - .map_or(3072 << 20, |mb| mb.min(8192) << 20) + .map(|mb| mb.min(8192) << 20) }); + let most = targets_most(asked, budget); static SETTLE: std::sync::OnceLock = std::sync::OnceLock::new(); let settle = *SETTLE.get_or_init(|| { std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS") @@ -2067,6 +2098,8 @@ pub(crate) fn targets_room_kept() -> u64 { }); // Every host texture's bytes less those of the copies the title fills. let targets = HOST_TEXTURES[1].load(Relaxed).saturating_sub(KINDS[1].load(Relaxed)); + static PEAK: AtomicU64 = AtomicU64::new(0); + let peak = PEAK.fetch_max(targets, Relaxed).max(targets); // The targets' bytes at their last change of 64 MiB or more, and when // they last grew by that much. static GREW: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; @@ -2075,7 +2108,21 @@ pub(crate) fn targets_room_kept() -> u64 { let (last, since) = targets_seen(last, since, targets, now); GREW[0].store(last, Relaxed); GREW[1].store(since, Relaxed); - targets_kept(most, targets, now.saturating_sub(since), settle) + static FLAT: std::sync::OnceLock = std::sync::OnceLock::new(); + if *FLAT.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_TARGETS_MB").is_some()) { + return targets_kept(most, targets, now.saturating_sub(since), settle); + } + targets_kept_from_peak(most, targets, peak) +} + +#[cfg(any(windows, test))] +fn targets_most(asked: Option, budget: u64) -> u64 { + const MOST: u64 = 3072 << 20; + match asked { + Some(asked) => asked, + None if budget == 0 => MOST, + None => MOST.min(budget / 10 * 3), + } } /// [`targets_room_kept`]'s record of the targets' bytes (`last`) and of @@ -2106,6 +2153,14 @@ fn targets_kept(most: u64, targets: u64, still_ms: u64, settle: u64) -> u64 { } } +/// Room kept for render targets without the flat switch: half as much again as +/// their peak (at least 256 MiB, capped at `most`), less what they hold now. +#[cfg(any(windows, test))] +fn targets_kept_from_peak(most: u64, targets: u64, peak: u64) -> u64 { + const LEAST: u64 = 256 << 20; + peak.saturating_add(peak / 2).max(LEAST).min(most).saturating_sub(targets) +} + /// What [`room`] weighs now, in MB, for the log: the card's budget, its /// use, the free part of the texture blocks, what is kept for card copies /// of title buffers and for render targets, and the line. `None` without @@ -2123,7 +2178,7 @@ pub(crate) fn room_terms(memory: Option<[u64; 4]>) -> Option<[u64; 6]> { used, crate::pool::texture_room(), crate::shadow::card_room_kept(), - targets_room_kept(), + targets_room_kept(budget), room_line(budget), ] .map(|bytes| bytes >> 20), @@ -2202,7 +2257,7 @@ pub(crate) fn placed_known(address: u64, desc: &[u32; 14]) -> Option { let mut key = *desc; key[1] = 0; key[13] = 0; - let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + let map = PLACED_TEXTURES.read().unwrap_or_else(|e| e.into_inner()); map.get(&(address, key)).or_else(|| map.get(&(address, *desc))).map(|&r| r as This) } @@ -2456,14 +2511,18 @@ pub(crate) fn let_go_idle() { static KEEP: std::sync::OnceLock = std::sync::OnceLock::new(); let keep = *KEEP .get_or_init(|| !matches!(std::env::var("VICTORY_TEXTURE_KEEP").as_deref(), Ok("0") | Ok("1"))); - let (idle_ms, most) = match memory { - Some([budget, used, ..]) if keep => { - let used = used.saturating_sub(crate::pool::texture_room()) - + crate::shadow::card_room_kept() - + targets_room_kept(); - crate::host::vram_keep_below(budget, used, room_line(budget)) - } - _ => (crate::host::vram_idle_ms(memory), u64::MAX), + let host_idle = crate::residency::host_texture_idle_ms(); + let (idle_ms, most) = match host_idle { + Some(ms) => (ms, u64::MAX), + None => match memory { + Some([budget, used, ..]) if keep => { + let used = used.saturating_sub(crate::pool::texture_room()) + + crate::shadow::card_room_kept() + + targets_room_kept(budget); + crate::host::vram_keep_below(budget, used, room_line(budget)) + } + _ => (crate::host::vram_idle_ms(memory), u64::MAX), + }, }; // For the trail (`crate::host::trail`): how many went, their bytes, // and the first one. @@ -2491,7 +2550,7 @@ pub(crate) fn let_go_idle() { let whole = *WHOLE.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_some_and(|v| v == "whole")); let part = if most != u64::MAX { 0 - } else if whole || idle_ms < 60_000 { + } else if whole || (idle_ms < 60_000 && host_idle.is_none()) { usize::MAX } else { PART @@ -2515,6 +2574,15 @@ pub(crate) fn let_go_idle() { if used == 0 || !fills(&r.desc) || !crate::host::long_ago(used, idle_ms, IDLE_FRAMES) || crate::texture::host_wrote(at) { continue; } + if host_idle.is_some() { + let unmapped = r.host.placed.load(Relaxed) + && footprint(&r.desc).is_some_and(|f| { + f.size > 0 && crate::texture::mapped_bytes(r.data().cast_const(), f.size as usize) == 0 + }); + if !unmapped { + continue; + } + } let gone = { let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); let idle = made.as_ref().is_some_and(|(host, _)| { @@ -2766,6 +2834,9 @@ fn slot_evict(video: Option<[u64; 4]>, idle_ms: u64, frames: u64) { // SAFETY: as above (the table is held). let r = unsafe { &*(at as *const Resource) }; let reset = crate::descriptor::evict_slots(at, &slots[&at]); + if reset > 0 { + crate::descriptor::host::invalidate_list_views(); + } SLOT_EVICT[2].fetch_add(reset, Relaxed); let gone = { let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); @@ -2932,6 +3003,13 @@ pub(crate) fn census() -> [u64; 10] { pub(crate) static HOST_TEXTURES: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// Bytes of host copies of textures the title fills that are alive now, for +/// the RAM-pressure sweep's before/after freed-bytes measure. +#[cfg(windows)] +pub(crate) fn host_textures_alive_bytes() -> u64 { + HOST_TEXTURES[1].load(std::sync::atomic::Ordering::Relaxed) +} + /// The bytes the host allocates for `texture`. #[cfg(windows)] fn host_bytes(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> u64 { @@ -3016,7 +3094,7 @@ impl Drop for HostTexture { /// (never released), for the memory line. #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn placed_textures() -> u64 { - PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).len() as u64 + PLACED_TEXTURES.read().unwrap_or_else(|e| e.into_inner()).len() as u64 } /// Moves the host texture to `wanted` (a host texture state); the host @@ -3076,6 +3154,36 @@ pub(crate) fn made_copy(this: This) -> Option> { hosted(this, false).map(|made| made.0) } +/// Why [`host_texture`] made no host texture. +#[cfg(windows)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum NoTexture { + /// The host will not make this description: not asked again. + Refused, + /// The card had no room then (`E_OUTOFMEMORY`), or there was no host + /// yet: asked again on a later use (upstream VIctory #3198). + ForNow, +} + +/// How long a texture the card had no room for waits before it is asked +/// for again ([`Hosted::no_room`]): each ask is a `CreateCommittedResource`. +#[cfg(windows)] +const NO_ROOM_AGAIN_MS: u64 = 1000; + +/// Host textures not made for lack of room, and made on a later use after +/// that, since the start (for the memory line). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) static NOT_MADE_FOR_NOW: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) static MADE_AFTER_NO_ROOM: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// What a failed host texture creation means for the texture: only a card +/// out of memory is worth asking again. +#[cfg(windows)] +fn no_texture(code: HRESULT) -> NoTexture { + if code == E_OUTOFMEMORY { NoTexture::ForNow } else { NoTexture::Refused } +} + /// A host texture like the title's: same description, in GPU memory, /// without the console's layout and flags. #[cfg(windows)] @@ -3083,7 +3191,7 @@ fn host_texture( desc: &ResourceDesc, state: u32, clear: *const c_void, -) -> Option { +) -> Result { host_texture_as(desc, state, clear, false) } @@ -3095,13 +3203,13 @@ fn host_texture_as( state: u32, clear: *const c_void, reserved: bool, -) -> Option { +) -> Result { use windows::Win32::Graphics::Direct3D12::*; const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access if desc.dimension == BUFFER { - return None; + return Err(NoTexture::Refused); } - let host = crate::host::host()?; + let host = crate::host::host().ok_or(NoTexture::ForNow)?; let mut d = *desc; d.layout = 0; d.alignment = 0; @@ -3168,7 +3276,7 @@ fn host_texture_as( crate::host::name(&t, || { format!("texture {}x{} f{} flags {:#x} (in a block)", d.width, d.height, d.format, d.flags) }); - return Some(t); + return Ok(t); } let mut texture: Option = None; let made = if reserved { @@ -3203,24 +3311,32 @@ fn host_texture_as( ) } }; + // Out of room may come back each second for many textures: its first + // and then every power-of-two-th line only. + let said = |e: &windows::core::Error, what: &str| { + let why = no_texture(e.code().0); + static NO_ROOM: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = (why == NoTexture::ForNow).then(|| NO_ROOM.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1); + if n.is_none_or(u64::is_power_of_two) { + tracing::warn!(error = %e, desc = ?d, reserved, ?why, times = n, "{what}"); + } + why + }; if let Err(e) = &made { crate::residency::allocation_error(e); - tracing::warn!(error = %e, desc = ?d, reserved, "no host texture"); + return Err(said(e, "no host texture")); } if !reserved - && made.is_ok() && let Some(t) = &texture && let Err(e) = crate::host::resident(&host.device, t).and_then(|()| crate::host::mapped(&host.device)) { - tracing::warn!(error = %e, desc = ?d, "a host texture is not resident"); - texture = None; + return Err(said(&e, "a host texture is not resident")); } - if let Some(t) = &texture { - crate::host::name(t, || { - format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags) - }); - } - texture + let texture = texture.ok_or(NoTexture::Refused)?; + crate::host::name(&texture, || { + format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags) + }); + Ok(texture) } /// The host copy of title texture `this` if it is made and was made @@ -3368,6 +3484,7 @@ fn hand_out_resource( clear: (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read_unaligned() }), used: std::sync::atomic::AtomicU64::new(0), refused: std::sync::atomic::AtomicBool::new(false), + no_room: std::sync::atomic::AtomicU64::new(0), gone: std::sync::atomic::AtomicBool::new(false), placed: std::sync::atomic::AtomicBool::new(false), wanted: std::sync::atomic::AtomicU32::new(u32::MAX), @@ -3619,8 +3736,8 @@ pub(crate) extern "system" fn create_at_address( /// its host texture is let go when nothing names it any more /// ([`let_go_idle`]) and made again on the next use. #[cfg(windows)] -static PLACED_TEXTURES: std::sync::Mutex> = - std::sync::Mutex::new(std::collections::BTreeMap::new()); +static PLACED_TEXTURES: std::sync::RwLock> = + std::sync::RwLock::new(std::collections::BTreeMap::new()); /// The placed textures asked for with filler words set, as asked /// (address and description): for [`PLACED_TWINS`]. Diagnostics builds @@ -3699,7 +3816,7 @@ pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option { let mut key = *desc; key[1] = 0; key[13] = 0; - let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + let map = PLACED_TEXTURES.read().unwrap_or_else(|e| e.into_inner()); let found = map.get(&(address, key)).or_else(|| map.get(&(address, *desc)))?; Some(*found as This) } @@ -3732,7 +3849,13 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { key[13] = 0; } let desc = &key; - let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + // Fast read-only path: 99.9%+ of placed-texture lookups during list + // recording hit an existing resource and need no exclusive lock. + #[cfg(not(feature = "diagnostics"))] + if let Some(&r) = PLACED_TEXTURES.read().unwrap_or_else(|e| e.into_inner()).get(&(address, *desc)) { + return Some(r as This); + } + let mut map = PLACED_TEXTURES.write().unwrap_or_else(|e| e.into_inner()); // How many resources the filler alone would have added (a count for // the log: `placed_filler_twins`). Diagnostics builds only: without // that feature this whole block -- its mutex, its set, and its O(seen @@ -5355,6 +5478,14 @@ float4 lit() : SV_Target { return 1.0; } // `VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS=0`: kept as before. assert_eq!(targets_kept(most, 2432 * MIB, 600_000, 0), 640 * MIB); + const GIB: u64 = 1 << 30; + assert_eq!(targets_most(None, 0), most); + assert_eq!(targets_most(None, 10_600 * MIB), most); + assert_eq!(targets_most(None, 7_256 * MIB), 7_256 * MIB / 10 * 3); + assert_eq!(targets_most(Some(1536 * MIB), 7 * GIB), 1536 * MIB); + assert_eq!(targets_kept_from_peak(most, 390 * MIB, 390 * MIB), 195 * MIB); + assert_eq!(targets_kept_from_peak(most, 0, 0), 256 * MIB); + // Growth of 64 MiB restarts the clock; less does not. assert_eq!(targets_seen(2000 * MIB, 1_000, 2050 * MIB, 9_000), (2000 * MIB, 1_000)); assert_eq!(targets_seen(2000 * MIB, 1_000, 2064 * MIB, 9_000), (2064 * MIB, 9_000));