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, leave >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).
This commit is contained in:
theme613 committed 2026-12-01 00:12:49 +08:00
1 parent 5d62b86f4a
commit f0d1eb7682
4 files changed
+964 -83

No files matched your search

+176 -45
View File
@@ -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<Made> {
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<Made> {
&& (!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<Made> {
}
}
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<u64> = std::sync::OnceLock::new();
let most = *MOST.get_or_init(|| {
static ASKED: std::sync::OnceLock<Option<u64>> = 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::<u64>().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<u64> = 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<bool> = 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<u64>, 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<This> {
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<bool> = 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<std::sync::Arc<HostTexture>> {
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<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
) -> Result<windows::Win32::Graphics::Direct3D12::ID3D12Resource, NoTexture> {
host_texture_as(desc, state, clear, false)
}
@@ -3095,13 +3203,13 @@ fn host_texture_as(
state: u32,
clear: *const c_void,
reserved: bool,
) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
) -> Result<windows::Win32::Graphics::Direct3D12::ID3D12Resource, NoTexture> {
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<ID3D12Resource> = 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::collections::BTreeMap<(u64, [u32; 14]), usize>> =
std::sync::Mutex::new(std::collections::BTreeMap::new());
static PLACED_TEXTURES: std::sync::RwLock<std::collections::BTreeMap<(u64, [u32; 14]), usize>> =
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<This> {
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<This> {
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));