Speed and room: draws' own records left to the draws in the heap sync, 2^20 table slots, textures kept while the card has room

- VICTORY_HEAP_SYNC=all mirrors every copied record at once, as before.
- VICTORY_DYNAMIC_SLOTS sets the table slots past the title's.
- Room kept for card copies of buffers is 1 GiB at most (was 5 GiB on 24 GB).
- VICTORY_TEXTURE_KEEP=0 lets idle textures go after 5 s, as before.
- VICTORY_TEXTURE_AWAY_MS: a texture whose memory went is shown 3 s longer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-25 01:52:09 -06:00
1 parent 1c8dd3156d
commit 1f1a433676
5 files changed
+270 -56

No files matched your search

+66 -20
View File
@@ -178,8 +178,11 @@ pub(crate) fn sync_heaps() {
return;
}
let started = std::time::Instant::now();
let (mut pages, mut looked, mut mirrored) = (0u64, 0u64, 0u64);
let (mut pages, mut looked, mut mirrored, mut tabled, mut later) = (0u64, 0u64, 0u64, 0u64, 0u64);
let mut page_bytes: Vec<u8> = Vec::new();
let mut changed: Vec<u32> = Vec::new();
let mut wait: Vec<u32> = Vec::new();
let frame = crate::frame::current();
let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner());
for &(start, end, at) in heaps.iter() {
// SAFETY: registered heaps are live (removed when dropped).
@@ -193,6 +196,16 @@ pub(crate) fn sync_heaps() {
// Capped host heaps have no counterparts for the title slots reserved
// for per-draw tables; raw writes there must not be mirrored.
let mirrored_count = heap.desc.count.min(host.count());
// The records of some frames ago that no draw read through a table
// since: a shader may pick them by index.
for index in host.copied_before(frame) {
if host.copied_tabled(index, frame) {
tabled += 1;
} else {
host.mirror(index, start + u64::from(index) * step, false);
mirrored += 1;
}
}
for (range_from, range_end) in written.take(start as usize, end as usize) {
let mut page = range_from & !(crate::watch::PAGE - 1);
while page < range_end {
@@ -205,54 +218,87 @@ pub(crate) fn sync_heaps() {
if crate::host::read_into(from as *const u8, &mut page_bytes) {
pages += 1;
let slots = changed_slots(from, to, start as usize, step, mirrored_count);
for index in slots {
let handle = start + index * step;
// A record that straddles the range's ends is left
// to the range that holds its first byte.
let Some(at) = (handle as usize).checked_sub(from) else {
continue;
// A record that straddles the range's ends is left
// to the range that holds its first byte.
let first = ((from - start as usize) as u64).div_ceil(step).max(slots.start);
let Some(records) = page_bytes.get((start + first * step) as usize - from..) else {
page += crate::watch::PAGE;
continue;
};
let count = (records.len() as u64 / step).min(slots.end.saturating_sub(first));
looked += count;
// Only the records that are not the ones last seen
// there (`HostHeap::copied_changes`).
changed.clear();
host.copied_changes(first as u32, &records[..(count * step) as usize], step as usize, &mut changed);
for &index in &changed {
let at = (u64::from(index) - first) as usize * step as usize;
let word = |n: usize| {
records
.get(at + 4 * n..at + 4 * n + 4)
.and_then(|b| b.try_into().ok())
.map_or(0, u32::from_le_bytes)
};
let Some(record) = page_bytes.get(at..at + step as usize) else {
continue;
};
looked += 1;
// Only a record that is not the one last seen there
// (`HostHeap::mirror_copied`).
if host.mirror_copied(index as u32, handle, record) {
mirrored += 1;
if !heap.samplers() && word(0) == VIEW_TAG {
// A draw's own table: the draw makes what it
// reads of it (`draw.rs` `tables`).
if host.copied_tabled(index, frame) {
tabled += 1;
continue;
}
// Buffer views and placed textures get no host
// slot from this anyway, they wait for a draw
// or a pass: noted some frames on, unless a
// draw's table turns out to hold them.
if matches!(word(2) >> KIND_SHIFT, CONSTANT | PLACED) && host.copied_waits() {
wait.push(index);
later += 1;
continue;
}
}
host.mirror(index, start + u64::from(index) * step, false);
mirrored += 1;
}
}
page += crate::watch::PAGE;
}
}
if !wait.is_empty() {
host.copied_wait(frame, std::mem::take(&mut wait));
}
}
drop(heaps);
for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, started.elapsed().as_micros() as u64]) {
let micros = started.elapsed().as_micros() as u64;
for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, micros, tabled, later]) {
count.fetch_add(n, Relaxed);
}
}
/// Since the last frame line, of [`sync_heaps`]: changed pages of placed
/// shader-visible heaps looked at, slots on them, slots whose record was
/// not the one last seen (mirrored), and the microseconds it took.
/// not the one last seen and was mirrored, the microseconds it took; then
/// new records left to the draws that read them through a table, and new
/// records that waited for one ([`host::HostHeap::copied_wait`]).
#[cfg(windows)]
pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
/// With the frame line: what [`sync_heaps`] did per frame over `frames`.
/// Nothing while no heap page changed.
#[cfg(windows)]
pub(crate) fn sync_line(frames: f64) {
let [pages, looked, mirrored, micros] = [0, 1, 2, 3].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed));
let [pages, looked, mirrored, micros, tabled, later] = [0, 1, 2, 3, 4, 5].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed));
if pages == 0 {
return;
}
tracing::info!(
"descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \
{:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.2} ms",
{:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.1} new ones of \
draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms",
pages as f64 / frames,
looked as f64 / frames,
mirrored as f64 / frames,
tabled as f64 / frames,
later as f64 / frames,
micros as f64 / 1000.0 / frames
);
}
+157 -33
View File
@@ -26,10 +26,17 @@ pub(crate) struct HostHeap {
sampler: bool,
/// The record (view index and generation) each slot was last made from.
made: Mutex<Vec<u64>>,
/// A fingerprint of the record each slot held when the pass over
/// records copied in as bytes last looked at it
/// ([`HostHeap::mirror_copied`]; 0: never looked at). Made on first use.
copied: Mutex<Vec<u64>>,
/// The records of the title's heap as the pass over records copied in
/// as bytes last saw them ([`HostHeap::copied_changes`]). Made on first
/// use.
copied: Mutex<Vec<u8>>,
/// New ones of them that wait for a draw ([`HostHeap::copied_wait`]),
/// by the frame they were found in.
waiting: Mutex<std::collections::VecDeque<(u64, Vec<u32>)>>,
/// The slots made from a texture whose memory was found away, with what
/// they were made from and when that was
/// ([`HostHeap::texture_slot_gone`]).
away: Mutex<std::collections::HashMap<u32, (u64, u64)>>,
/// The host resource each slot views, held while the slot does: shaders
/// index heaps directly, so a slot the title has not rewritten since it
/// released the resource may still be read, and a freed host resource
@@ -513,6 +520,14 @@ const TABLED_FRAMES: u64 = 240;
/// (435 begun in the 353 s of run 52's, for some 140 presented).
const TABLED_GRACE: u64 = 8;
/// Frames for which a record copied into a slot a draw read through a
/// table is left to such a draw ([`HostHeap::copied_tabled`]).
const COPIED_FRAMES: u32 = 8;
/// Frames a record copied into any other slot waits for one, before it is
/// taken for one shaders pick by index ([`HostHeap::copied_wait`]).
const COPIED_GRACE: u64 = 4;
/// In [`HostHeap::tabled`]: a draw read the slot in that frame.
const TABLED_READ: u32 = 1 << 31;
@@ -940,6 +955,26 @@ pub(crate) fn probe_view_limit() {
/// table past them is made afresh in these slots like any other.
pub(crate) const DYNAMIC: u32 = 1 << 18;
/// [`DYNAMIC`] for a heap of `count` title slots whose null slot is `null`
/// (0: none): up to four times as many where the host heap has the room (a
/// host that takes more than [`PORTABLE_VIEWS`]; `VICTORY_DYNAMIC_SLOTS`
/// sets the most). 2^18 ran out in the title's bigger places (session
/// play-1125-0127: 27,000 to 35,000 tables a frame, up to 3,285 of them
/// refused, with 2,639 indirect draws and dispatches).
fn dynamic_slots(count: u32, null: u32) -> u32 {
static MOST: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
let most = *MOST.get_or_init(|| {
std::env::var("VICTORY_DYNAMIC_SLOTS")
.ok()
.and_then(|v| v.trim().parse().ok())
.unwrap_or(DYNAMIC << 2)
});
if null < PORTABLE_VIEWS {
return DYNAMIC;
}
null.saturating_sub(count).min(most).max(DYNAMIC)
}
impl HostHeap {
pub(crate) fn new(sampler: bool, count: u32) -> Option<Self> {
let host = host()?;
@@ -960,7 +995,6 @@ impl HostHeap {
})
}
};
let extra = if sampler { 0 } else { DYNAMIC };
// A view heap ends at the null slot shaders clamp view indices to
// (`probe_view_limit`), whatever the title's own count: the title's
// slots, then the dynamic ones, then null up to and with that slot.
@@ -972,6 +1006,7 @@ impl HostHeap {
} else {
victory_shader::emit::view_heap_limit()
};
let extra = if sampler { 0 } else { dynamic_slots(count, null) };
let (heap, count, size) = if null == 0 {
match make(count + extra) {
Ok(heap) => (heap, count, count + extra),
@@ -1036,9 +1071,11 @@ impl HostHeap {
sampler,
made: Mutex::new(vec![0; count as usize]),
copied: Mutex::new(Vec::new()),
waiting: Mutex::default(),
away: Mutex::default(),
kept: Mutex::new(vec![None; (count + extra) as usize]),
next: Mutex::new((0, vec![false; DYNAMIC as usize])),
free: std::sync::atomic::AtomicU32::new(DYNAMIC),
next: Mutex::new((0, vec![false; extra as usize])),
free: std::sync::atomic::AtomicU32::new(extra),
too_long: std::sync::atomic::AtomicU32::new(u32::MAX),
strides,
buffers: Mutex::default(),
@@ -1186,7 +1223,7 @@ impl HostHeap {
crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64);
taken[first..first + n].fill(true);
self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed);
*next = ((first + n) % DYNAMIC as usize) as u32;
*next = ((first + n) % end) as u32;
Some(self.count + first as u32)
}
@@ -1520,16 +1557,52 @@ impl HostHeap {
/// (any more): a host slot made from it becomes null again, so that
/// the host copy can be let go (`crate::resource::let_go_idle`; a slot
/// keeps what it views). True if the slot was made.
///
/// Not at the first look: a title that moves a texture in its streaming
/// memory unmaps it before it maps it again, and what was shown went
/// black for the pictures in between (session play-1125-0127: faces,
/// books, posters and sleeves for 0.3 to 2 s). Only when it is still
/// away `AWAY_MS` after it was first found away
/// (`VICTORY_TEXTURE_AWAY_MS`; 0: at once, as before).
pub(crate) fn texture_slot_gone(&self, index: u32) -> bool {
const AWAY_MS: u64 = 3000;
static WAIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
let wait = *WAIT.get_or_init(|| {
std::env::var("VICTORY_TEXTURE_AWAY_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(AWAY_MS)
});
let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
if made.get(index as usize).is_none_or(|&key| key == 0) {
let Some(key) = made.get(index as usize).copied().filter(|&key| key != 0) else {
return false;
};
let now = crate::host::now_ms();
{
let mut away = self.away.lock().unwrap_or_else(|e| e.into_inner());
match away.get(&index) {
Some(&(was, since)) if was == key && now.saturating_sub(since) < wait => return false,
Some(&(was, _)) if was == key => {
away.remove(&index);
}
_ if wait == 0 => {}
_ => {
away.insert(index, (key, now));
return false;
}
}
}
self.unmake(&mut made, index);
STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
true
}
/// The memory of the texture title slot `index` views is there (again):
/// see [`HostHeap::texture_slot_gone`].
pub(crate) fn texture_slot_here(&self, index: u32) {
let mut away = self.away.lock().unwrap_or_else(|e| e.into_inner());
if !away.is_empty() {
away.remove(&index);
}
}
/// Makes host slot `index` null again, as it is before its view is
/// made: a null view of the kind it held.
fn unmake(&self, made: &mut [u64], index: u32) {
@@ -1623,6 +1696,12 @@ impl HostHeap {
}
}
/// Title slot `index` lies in a table a draw reads or had made afresh:
/// what it holds is the draw's to make ([`HostHeap::copied_tabled`]).
pub(crate) fn slot_tabled(&self, index: u32) {
self.tabled_in(index, false, crate::frame::current());
}
/// The title slots that hold buffer views.
pub(crate) fn buffer_slots(&self) -> Vec<u32> {
let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
@@ -1913,10 +1992,10 @@ impl HostHeap {
}
}
/// For a slot on a page of the title's heap that changed with no call
/// For a run of records of the title's heap from slot `first`, `step`
/// bytes each, on a page that changed with no call
/// (`super::sync_heaps`: the title copies records into its heap as
/// bytes): [`HostHeap::mirror`], if the `bytes` bytes of the record at
/// `handle` are not the ones this last saw there. True if it did.
/// bytes): the slots whose record is not the one this last saw there.
///
/// The page says only that something on it was written, and `mirror`
/// by itself would take every buffer or placed-texture record on it for
@@ -1924,32 +2003,77 @@ impl HostHeap {
/// or a pass uses it): the texture queue's entry for the slot would
/// start again, and the buffer pass would look at 2,048 slots for one
/// that changed.
/// `record`: the record's bytes as the caller read them (through the
/// `records`: their bytes as the caller read them (through the
/// kernel, which fails on a page the title unmapped meanwhile where a
/// read in place would fault: the title unmaps heap pages too).
pub(crate) fn mirror_copied(&self, index: u32, handle: u64, record: &[u8]) -> bool {
if index >= self.count {
pub(crate) fn copied_changes(&self, first: u32, records: &[u8], step: usize, out: &mut Vec<u32>) {
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
if copied.is_empty() {
// Nothing there: a slot never looked at that holds nothing is
// as it was.
copied.resize(self.count as usize * step, 0);
}
let at = first as usize * step;
let end = (at + records.len()).min(copied.len());
let Some(last) = copied.get_mut(at..end) else {
return;
};
let records = &records[..last.len()];
if last == records {
return;
}
for (n, (old, new)) in last.chunks_exact_mut(step).zip(records.chunks_exact(step)).enumerate() {
if old != new {
old.copy_from_slice(new);
out.push(first + n as u32);
}
}
}
/// Whether new records of draws' tables are left to the draws
/// (`VICTORY_HEAP_SYNC=all`: every new record is mirrored at once, as
/// it first was).
///
/// The title builds each draw's tables in its heap by copying records
/// there as bytes: 60,000 to 210,000 a frame in its world (session
/// play-1125-0127), 0.9 microseconds each on the submitting thread and
/// 1.4 more in the buffer pass they were all handed to, 120 to 600 ms
/// of every frame, and the draws make what they read of them anyway.
pub(crate) fn copied_waits(&self) -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "all"))
}
/// Whether a draw read title slot `index` through a table within the
/// last few frames before `frame` ([`HostHeap::tabled`]): what it holds
/// is such a draw's to make.
pub(crate) fn copied_tabled(&self, index: u32, frame: u64) -> bool {
if !self.copied_waits() {
return false;
}
let n = record.len();
// Never 0, which is "never looked at".
let print = u64::from_le_bytes(blake3::hash(record).as_bytes()[..8].try_into().unwrap_or([1; 8])) | 1;
{
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
if copied.is_empty() {
copied.resize(self.count as usize, 0);
}
let Some(last) = copied.get_mut(index as usize) else {
return false;
};
// A slot never looked at that holds nothing: as it was.
if *last == print || (*last == 0 && record[..n].iter().all(|&b| b == 0)) {
return false;
}
*last = print;
let stamp = self.tabled_stamp(index) & !TABLED_READ;
let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
stamp != 0 && now.wrapping_sub(stamp) & !TABLED_READ <= COPIED_FRAMES
}
/// New records the title copied into slots `slots` in `frame` wait for
/// the draw that may read them through a table.
pub(crate) fn copied_wait(&self, frame: u64, slots: Vec<u32>) {
self.waiting.lock().unwrap_or_else(|e| e.into_inner()).push_back((frame, slots));
}
/// The slots that have waited long enough at `frame`
/// ([`HostHeap::copied_wait`]), each once.
pub(crate) fn copied_before(&self, frame: u64) -> Vec<u32> {
let mut waiting = self.waiting.lock().unwrap_or_else(|e| e.into_inner());
let mut out = Vec::new();
while waiting.front().is_some_and(|(written, _)| written + COPIED_GRACE <= frame) {
out.extend(waiting.pop_front().into_iter().flat_map(|(_, slots)| slots));
}
self.mirror(index, handle, false);
true
drop(waiting);
out.sort_unstable();
out.dedup();
out
}
/// Makes host slot `index` from the record the title has at `handle`
+15
View File
@@ -1646,6 +1646,10 @@ impl State {
let mut unordered = Vec::new();
for (n, &index) in slots.iter().enumerate() {
ranges.set(index, None);
// A draw's table's: the draw brings what it reads up to date.
if host.copied_tabled(index, frame) {
continue;
}
let Some(handle) = heap.handle(index) else {
continue;
};
@@ -2087,6 +2091,7 @@ impl State {
host.texture_slot_later(index, write, frame, most);
continue;
}
host.texture_slot_here(index);
if mapped < len {
if mapped <= host.texture_slot_mapped(index) {
HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed);
@@ -2697,6 +2702,8 @@ impl State {
// Up to date by this draw: not the texture pass's to make.
if crate::descriptor::host::is_texture_view(&view) {
host.texture_slot_tabled(index, true);
} else {
host.slot_tabled(index);
}
}
}
@@ -2847,6 +2854,14 @@ impl State {
// The title's own slots of this table: what the draw reads of
// them it brings up to date here, in the dynamic slots.
let title_first = heap.index(table).filter(|first| first + n <= host.count());
// They are such a table's, whatever they hold. (Of a big one,
// which may lie over slots shaders pick by index, only the ones
// the shader names.)
if let Some(title) = title_first {
for k in (0..n).filter(|&k| n <= 64 || entries.iter().any(|u| u.table_offset_dwords / 8 == k)) {
host.slot_tabled(title + k);
}
}
// The whole range: a shader may index past the entries its
// used-resource list names (descriptor arrays).
for k in 0..n {
+25 -2
View File
@@ -120,7 +120,20 @@ pub(crate) fn available_physical_ram() -> Option<u64> {
/// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
/// scaled down under VRAM pressure. Never returns less than 1,000 ms so
/// handles not yet recorded into a list or slot remain protected.
///
/// With room on the card nothing has to go: in session play-1125-0127 88,000
/// of them (31 GB) went after 5 s with 7 GB of the card free, and 24,700
/// (12 GB) had to be made and uploaded again.
/// `VICTORY_TEXTURE_KEEP=0`: 5 s there too, as before.
pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
static KEEP: OnceLock<bool> = OnceLock::new();
let keep = *KEEP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_KEEP").is_none_or(|v| v != "0"));
vram_idle_for(video_memory, keep)
}
fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 {
const KEPT_MS: u64 = 600_000;
const LONG_MS: u64 = 30_000;
const NORMAL_MS: u64 = 5_000;
const MODERATE_MS: u64 = 2_500;
const HIGH_MS: u64 = 1_000;
@@ -135,8 +148,12 @@ pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
HIGH_MS
} else if used_pct >= 75 {
MODERATE_MS
} else {
} else if !keep {
NORMAL_MS
} else if used_pct >= 68 {
LONG_MS
} else {
KEPT_MS
}
}
@@ -8852,8 +8869,14 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at
#[test]
fn vram_idle_ms_scales_with_pressure() {
use super::vram_idle_ms;
let vram_idle_ms = |memory| super::vram_idle_for(memory, false);
let keeps = |memory| super::vram_idle_for(memory, true);
let gib = 1024 * 1024 * 1024;
assert_eq!(keeps(Some([100, 67, 0, 0])), 600_000);
assert_eq!(keeps(Some([100, 68, 0, 0])), 30_000);
assert_eq!(keeps(Some([100, 75, 0, 0])), 2_500);
assert_eq!(keeps(Some([100, 85, 0, 0])), 1_000);
assert_eq!(keeps(None), 5_000);
// Normal (< 75%)
assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
+7 -1
View File
@@ -274,7 +274,13 @@ pub(crate) fn card_room_kept() -> u64 {
if !card_room_kept_on() || !cards() {
return 0;
}
card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed))
// Not more than such copies came to in any session, whatever they may
// come to: on a card of 24 GB a quarter of its budget was kept for them,
// 5 GB that never came (941 MB in 97 copies after fifteen minutes), and
// no texture was made any more with 5 GB of the card free (session
// play-1125-0127: 1,453 passes refused, the ground and people black).
const SEEN: u64 = 1 << 30;
card_limits().1.min(SEEN).saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed))
}
/// The copies in the card's memory.