From 6b07e2e02dc5bf895819c543ea09c734a6e8dc20 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:14:38 -0600 Subject: [PATCH 1/3] Texture uploads wait for no mapping, ask no guards and hash cheaply; the sweep looks at a part; bakes pass once for what is new A bake's uploads waited for the lock the runtime holds while it remaps, and a staging buffer a draw kept waited at every later refresh (29 to 239 ms a frame, all threads, run n04): gone, a read through the kernel gets every page. A staging buffer made for one upload asks neither the write watch nor the guards (VICTORY_TEXTURE_ONCE=0: as before). blake3 makes way for a 128-bit digest (0.035 against 0.2 ms a megabyte). While textures are kept for minutes the sweep looks at 8,192 a time (VICTORY_TEXTURE_SWEEP=whole). The pass before a bake is made again only for something new. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 8 ++ crates/victory-gpu/src/draw.rs | 34 ++++- crates/victory-gpu/src/host.rs | 10 +- crates/victory-gpu/src/resource.rs | 38 ++++- crates/victory-gpu/src/texture.rs | 163 ++++++++++++++++++---- 5 files changed, 215 insertions(+), 38 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index b1b3b28..62777fd 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1358,6 +1358,14 @@ impl HostHeap { (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame)) } + /// A number that changes when a slot is written or made due anew, and + /// whether memory was noted since a pass last took the notes. + pub(crate) fn texture_news(&self) -> (u64, bool) { + let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes; + let noted = |ranges: &Mutex>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty(); + (writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN)) + } + /// Every title slot of the queue that is due at `frame`, and whether /// it was uploaded before (in part, or whole and waiting for another /// look): for the card accounting line diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e5fd151..4bca1ac 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -120,8 +120,14 @@ fn recheck_soon() -> bool { /// Frames ahead the pass before a bake takes slots from that are due only /// then ([`bake_exact`]): those of notices (1 and 2), and the first looks -/// again ([`RECHECK_FRAMES`]). -const BAKE_AHEAD: u64 = 12; +/// again ([`RECHECK_FRAMES`]), these at the frame's first bake alone (a +/// look reads 48 KiB, and a frame bakes up to sixteen times). +const BAKE_AHEAD: [u64; 2] = [12, 2]; + +/// What [`crate::descriptor::host::HostHeap::texture_news`] said when the +/// pass before a bake last served all there was, plus one (0: it did not): +/// until something is new, the next bakes of the frame need no pass. +static BAKE_SERVED: AtomicU64 = AtomicU64::new(0); /// The pixel shaders of the title's decoration bake (the title: /// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the @@ -1844,6 +1850,12 @@ impl State { return; }; let bake = bake && left > 0; + if bake && !first && bake_exact() { + let (writes, noted) = host.texture_news(); + if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 { + return; + } + } let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1; if bake && n.is_power_of_two() { let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); @@ -2027,7 +2039,9 @@ impl State { let on_time = due.len(); if baking { let known: std::collections::HashSet = due.iter().map(|&(index, _)| index).collect(); - let (ahead, _) = host.texture_slots_due(frame + BAKE_AHEAD, 1 << 16); + static AHEAD: AtomicU64 = AtomicU64::new(u64::MAX); + let again = AHEAD.swap(frame, Ordering::Relaxed) == frame; + let (ahead, _) = host.texture_slots_due(frame + BAKE_AHEAD[usize::from(again)], 1 << 16); due.extend(ahead.into_iter().filter(|(index, _)| !known.contains(index))); } HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); @@ -2083,8 +2097,11 @@ impl State { None => (span, per_frame), }; let began = std::time::Instant::now(); + BAKE_SERVED.store(0, Ordering::Relaxed); + let mut served = true; for (index, write) in due { if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span { + served = false; break; } // A placed texture whose memory is not mapped (not streamed in @@ -2149,6 +2166,7 @@ impl State { } } let mut partly = None; + let mut there = None; if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let first = crate::resource::first_mip(&desc); @@ -2162,6 +2180,7 @@ impl State { continue; } host.texture_slot_here(index); + there = Some(mapped); if mapped < len { if mapped <= host.texture_slot_mapped(index) { HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed); @@ -2275,7 +2294,11 @@ impl State { continue; } if let Some(view) = &view { + // (What was found mapped of it a moment ago is not asked + // again, unless the host copy may need more.) + crate::texture::PICKING.set(Some(there.filter(|_| partly.is_none()).unwrap_or(u64::MAX))); readable(list, sampled.kind, view); + crate::texture::PICKING.set(None); } if shows_other && let Some(handle) = heap.handle(index) { host.texture_slot_flip(list, index, handle); @@ -2291,7 +2314,7 @@ impl State { crate::host::log_removal_context(); return; } - let (bytes, whole) = crate::texture::staged(resource).unwrap_or((0, true)); + let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true)); // Not all of it there: looked at again next frame, and from // then on as a slot with nothing new (a placed texture: until // more of it is mapped; a texture object at an address the @@ -2340,6 +2363,9 @@ impl State { None => host.texture_slot_done(index, write, again), } } + if baking && served { + BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed); + } } /// For the frame listing, after a dropped dispatch's line: its group diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 5393d72..a90fb22 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -7531,11 +7531,17 @@ impl Meter { "textures from the first level viewed (VICTORY_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \ levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \ {flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \ - out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free", + out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free; \ + {} looks for textures to let go, {:.2} ms each, the longest {:.1}", bytes >> 20, whole >> 20, crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed), - crate::pool::texture_room() >> 20 + crate::pool::texture_room() >> 20, + crate::resource::SWEPT_US[0].load(Ordering::Relaxed), + crate::resource::SWEPT_US[1].load(Ordering::Relaxed) as f64 + / 1e3 + / crate::resource::SWEPT_US[0].load(Ordering::Relaxed).max(1) as f64, + crate::resource::SWEPT_US[2].load(Ordering::Relaxed) as f64 / 1e3 ); } { diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index b44ba86..c524ba1 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1180,7 +1180,7 @@ pub(crate) struct HostTexture { /// What a host copy was filled with last: the first level of it and the /// hash of the title memory it was read from. #[cfg(windows)] -pub(crate) type Holds = std::sync::Mutex>; +pub(crate) type Holds = std::sync::Mutex>; /// [`HostTexture::serial`] of the last one made. #[cfg(windows)] @@ -2051,15 +2051,37 @@ pub(crate) fn let_go_idle() { } by_age.sort_unstable(); } - let every = all.iter().copied().filter(|_| most == u64::MAX); - for at in every.chain(by_age.iter().map(|&(_, at)| at)) { + // Without one, while textures are kept for minutes, a part of them at + // each look, the next one at the next: a play has over 100,000 + // (`VICTORY_TEXTURE_SWEEP=whole`: all each time, as before). + const PART: usize = 8192; + static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + static WHOLE: std::sync::OnceLock = std::sync::OnceLock::new(); + 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 { + usize::MAX + } else { + PART + }; + let from = if part == PART { FROM.load(Relaxed) } else { 0 }; + let mut looked = 0; + let began = std::time::Instant::now(); + for at in all.range(from..).take(part).copied().chain(by_age.iter().map(|&(_, at)| at)) { if bytes >= most { break; } + looked += 1; + if part == PART { + FROM.store(if looked == PART { at + 1 } else { 0 }, Relaxed); + } // SAFETY: a texture leaves the table before it is freed, under the // lock held here (`Drop for Resource`). let r = unsafe { &*(at as *const Resource) }; - if !fills(&r.desc) || crate::texture::host_wrote(at) { + // (Without its lock first: most were used lately or have none.) + let used = r.host.used.load(Relaxed); + if used == 0 || !fills(&r.desc) || !crate::host::long_ago(used, idle_ms, IDLE_FRAMES) || crate::texture::host_wrote(at) { continue; } let gone = { @@ -2091,6 +2113,9 @@ pub(crate) fn let_go_idle() { crate::host::retire(host); } } + SWEPT_US[0].fetch_add(1, Relaxed); + SWEPT_US[1].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + SWEPT_US[2].fetch_max(began.elapsed().as_micros() as u64, Relaxed); if went > 0 { crate::host::trail(|| { format!( @@ -2102,6 +2127,11 @@ pub(crate) fn let_go_idle() { } } +/// Since the start: looks of [`let_go_idle`], their microseconds, and the +/// longest one's. +#[cfg(windows)] +pub(crate) static SWEPT_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + /// For the memory line: the host copies the sweep never lets go /// ([`let_go_idle`] takes only copies of textures the title fills that the /// host never copied into), by what would say they are dead weight. A diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index f970f70..7ad9915 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -57,9 +57,9 @@ pub(crate) struct Staging { /// Which host copy it uploads into, and what that is told to hold. serial: u64, holds: Arc, - /// Title memory being remapped is waited for whatever [`no_wait`] says: - /// a list that bakes from the texture now recorded the upload. - waits: std::sync::atomic::AtomicBool, + /// Made by the pass over textures picked by index, for one upload + /// ([`once`]): read when the list is submitted, and never looked at again. + once: std::sync::atomic::AtomicBool, /// The staging buffer's bytes (counted in `STAGED` while it lives). bytes: u64, memory: *const u8, @@ -95,7 +95,7 @@ pub(crate) struct Staging { /// (memory not watched), or the write-watch asking it was detiled after. #[derive(Default)] struct Last { - hash: Option, + hash: Option, asked: u64, /// The frame a partly mapped texture was last read in. partial: Option, @@ -648,11 +648,76 @@ pub(crate) fn upload(list: &HostList, resource: This, _texture: &ID3D12Resource) } thread_local! { - /// The thread records uploads for a draw that bakes from them - /// ([`Staging::waits`]). + /// The thread records uploads for a draw that bakes from them. pub(crate) static BAKING: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// The thread records the upload of a texture picked by index, of which + /// that many bytes were found mapped just now (`u64::MAX`: not asked). + pub(crate) static PICKING: std::cell::Cell> = const { std::cell::Cell::new(None) }; } +/// Whether a staging buffer made for one upload of a texture picked by index +/// is filled without asking the write watch and the guards +/// (`VICTORY_TEXTURE_ONCE=0`: with, as before). What they say is for the next +/// refresh, and there is none: the buffer goes with the upload. Asking guards +/// the texture's blocks (a change of protection, under the lock every other +/// refresh wants), and the title's next write there faults to open them. +fn once() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_ONCE").is_none_or(|v| v != "0")) +} + +/// A 128-bit digest of `bytes`, to tell a texture's memory changed: four +/// lanes of folded multiplications over 64 bytes at a time. (Not a +/// cryptographic one, which took 0.27 ms a megabyte, four times the detiling +/// it was to spare; nobody makes up textures to collide.) +pub(crate) fn digest(bytes: &[u8]) -> Digest { + const K: [u64; 8] = [ + 0xa076_1d64_78bd_642f, + 0xe703_7ed1_a0b4_28db, + 0x8ebc_6af0_9c88_c6e3, + 0x5899_65cc_7537_4cc3, + 0x1d8e_4e27_c47d_124f, + 0xeb44_acca_b455_d165, + 0x9e37_79b9_7f4a_7c15, + 0xc2b2_ae3d_27d4_eb4f, + ]; + let fold = |a: u64, b: u64| { + let p = u128::from(a) * u128::from(b); + p as u64 ^ (p >> 64) as u64 + }; + let word = |b: &[u8]| { + let mut w = [0; 8]; + w[..b.len()].copy_from_slice(b); + u64::from_le_bytes(w) + }; + let mut lanes = [K[0], K[1], K[2], K[3]]; + let mut step = |block: &[u8; 64]| { + for (i, lane) in lanes.iter_mut().enumerate() { + let a = word(&block[16 * i..16 * i + 8]); + let b = word(&block[16 * i + 8..16 * i + 16]); + // (What went in is added again: a product with a factor of zero + // forgets neither the lane nor the block.) + *lane = fold(a ^ K[4 + i], b ^ *lane).wrapping_add(a.rotate_left(23) ^ lane.rotate_left(41)) ^ b; + } + }; + let mut blocks = bytes.chunks_exact(64); + for block in &mut blocks { + step(block.try_into().unwrap_or(&[0; 64])); + } + let rest = blocks.remainder(); + let mut last = [0u8; 64]; + last[..rest.len()].copy_from_slice(rest); + step(&last); + let len = bytes.len() as u64; + let low = fold(lanes[0] ^ K[1], lanes[1] ^ len) ^ fold(lanes[2] ^ K[3], lanes[3] ^ K[5]); + let high = fold(lanes[0].rotate_left(32) ^ K[6], lanes[2] ^ len) ^ fold(lanes[1].rotate_left(32) ^ K[7], lanes[3] ^ K[2]); + Digest(u128::from(low) << 64 | u128::from(high)) +} + +/// See [`digest`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Digest(u128); + /// [`upload`] of the levels from `first` on, the ones a view shows: of a /// texture the title placed there may be no memory of the larger ones, and /// what lies there is another texture's. (After victory-amd 4436f8f1.) @@ -684,8 +749,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { return; }; use std::sync::atomic::Ordering::Relaxed; - if BAKING.get() { - staging.waits.store(true, Relaxed); + let picking = PICKING.get(); + if picking.is_none() { + // A draw samples it through a table: kept and checked from here on. + staging.once.store(false, Relaxed); } staging.used.store(crate::host::moment(), Relaxed); // Levels on demand: a view of the texture now starts at another @@ -727,7 +794,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexUploads, 1); if no_wait() && fill_unlocked() { - let there = mapped_bytes(staging.memory, staging.read); + let there = match picking { + Some(there) if there != u64::MAX => there, + _ => mapped_bytes(staging.memory, staging.read), + }; staging.expected.store(there, Relaxed); } const COPY_DEST: u32 = 0x400; @@ -1064,7 +1134,11 @@ impl Staging { let start = self.memory as usize; let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); let last = &mut *last; - if let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) { + let alone = self.once.load(std::sync::atomic::Ordering::Relaxed); + if alone && last.hash.is_some() { + return 0; + } + if !alone && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) { if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { return 0; } @@ -1092,7 +1166,8 @@ impl Staging { static GUARD: std::sync::OnceLock = std::sync::OnceLock::new(); // The guard saw no write: a change the hash finds came another way. let mut blind = false; - if *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) + if !alone + && *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) { const HASH_EVERY: u64 = 8; @@ -1127,7 +1202,7 @@ impl Staging { // stays mapped (see `crate::watch::title_memory_reading`; without // it a page went between the asking and the read in runs 71 and // 74). - let _mapped = if no_wait() && !self.waits.load(std::sync::atomic::Ordering::Relaxed) { + let _mapped = if no_wait() { // Not waited for: while the runtime remaps title memory the // texture is read through the kernel instead, whole or not at // all (`no_wait`). @@ -1155,7 +1230,7 @@ impl Staging { crate::copystat::add(crate::copystat::C::TexHashed, size as u64); let changed = with_read(size, |read| { crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); - let hash = blake3::hash(read); + let hash = digest(read); if last.hash == Some(hash) { return false; } @@ -1177,7 +1252,7 @@ impl Staging { } if through_copy() { return with_title(self.memory, size, |tiled| { - let hash = blake3::hash(tiled); + let hash = digest(tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); if last.hash == Some(hash) { @@ -1194,7 +1269,7 @@ impl Staging { // SAFETY: committed memory of the texture's layout size, and it // stays committed while `_mapped` is held. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; - let hash = blake3::hash(tiled); + let hash = digest(tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); if last.hash == Some(hash) { @@ -1221,7 +1296,7 @@ impl Staging { if !crate::host::read_into(self.memory, read) { return false; } - let hash = blake3::hash(read); + let hash = digest(read); if last.hash != Some(hash) { last.hash = Some(hash); self.detile(read); @@ -1256,14 +1331,14 @@ impl Staging { let mut got = 0; for _ in 0..4 { got = crate::host::read_there(self.memory, read) as u64; - crate::watch::change_over(); there = mapped_bytes(self.memory, size); - if got >= there { + if got >= there.max(self.expected.load(Relaxed)) { break; } + crate::watch::change_over(); } if got != 0 { - last.hash = Some(blake3::hash(read)); + last.hash = Some(digest(read)); self.detile(read); } got @@ -1361,14 +1436,14 @@ pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { static READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } let len = len as usize; - let mut hasher = blake3::Hasher::new(); + let mut print = 0u128; READ.with(|read| { let mut read = read.borrow_mut(); read.resize(3 * WINDOW, 0); let mut take = |from: usize, bytes: usize| { read[..bytes].fill(0); crate::host::copy_mapped(read.as_mut_ptr(), (at as usize + from) as *const u8, bytes, false); - hasher.update(&read[..bytes]); + print = print.rotate_left(37) ^ digest(&read[..bytes]).0; }; if len <= 3 * WINDOW { take(0, len); @@ -1378,9 +1453,7 @@ pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { take(len - WINDOW, WINDOW); } }); - let hash = hasher.finalize(); - let mut first = [0u8; 8]; - first.copy_from_slice(&hash.as_bytes()[..8]); + let first = (print as u64 ^ (print >> 64) as u64).to_le_bytes(); u64::from_le_bytes(first) | 1 } @@ -1436,7 +1509,7 @@ pub(crate) fn unchanged(resource: This, first: u32) -> bool { if crate::host::read_there(memory, read) == 0 { return false; } - blake3::hash(read) == held + digest(read) == held }) } @@ -1456,12 +1529,13 @@ pub(crate) fn is_staged(resource: This) -> bool { /// The bytes of a title texture's memory, and whether all of it is mapped, /// if the texture has been staged for upload. -pub(crate) fn staged(resource: This) -> Option<(u64, bool)> { +/// (Whether it is mapped is asked only if `ask`; else it counts as mapped.) +pub(crate) fn staged(resource: This, ask: bool) -> Option<(u64, bool)> { let s = { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref()?.get(&(resource as usize))?.clone() }; - Some((s.read as u64, committed(s.memory, s.read))) + Some((s.read as u64, !ask || committed(s.memory, s.read))) } /// Whether `[at, at + len)` is committed memory (streamed textures may be @@ -1713,7 +1787,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O read, serial: copy.serial, holds: copy.holds.clone(), - waits: std::sync::atomic::AtomicBool::new(false), + once: std::sync::atomic::AtomicBool::new(once() && !on_demand && PICKING.get().is_some()), bytes: total, memory, last: Mutex::default(), @@ -1932,6 +2006,36 @@ mod allocation_costs { } } + /// The digest tells every length and every changed byte apart, zeros + /// among them. + #[test] + fn a_digest_tells_bytes_apart() { + use super::digest; + let zeros = [0u8; 400]; + let mut seen: Vec = (0..400).map(|n| digest(&zeros[..n])).collect(); + for at in 0..400 { + for value in [1u8, 0x80, 0xff] { + let mut bytes = zeros; + bytes[at] = value; + seen.push(digest(&bytes)); + } + } + let text: Vec = (0..400u32).map(|i| (i * 37 >> 2) as u8).collect(); + for at in 0..399 { + let mut bytes = text.clone(); + bytes.swap(at, at + 1); + if bytes != text { + seen.push(digest(&bytes)); + } + } + seen.push(digest(&text)); + let n = seen.len(); + seen.sort_unstable_by_key(|d| d.0); + seen.dedup(); + assert_eq!(seen.len(), n); + assert_eq!(digest(&text), digest(&text.clone())); + } + /// What a texture met for the first time costs, by step, in /// milliseconds a megabyte on one thread: for whether a store of /// detiled copies on disk could be worth it (its key is a hash of the @@ -1965,6 +2069,9 @@ mod allocation_costs { timed("blake3", &mut || { std::hint::black_box(blake3::hash(&title)); }); + timed("digest", &mut || { + std::hint::black_box(super::digest(&title)); + }); timed("detiled into upload memory", &mut || { let mut at = 0; for (mip, m) in layout.mips.iter().enumerate() { From a0678ad1fa13f97f7a07a1bd0132e03533f28707 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:32:52 -0600 Subject: [PATCH 2/3] Landing goes beside the guards while mappings change; rectangles read without that lock Pieces went through the title's address, guards opened, whenever the runtime was mapping pages, which is most of the time since they are mapped in groups (28 of 1,620 pieces a frame beside the guards in run textures-4, 640 before): 5,000 blocks opened and 7,000 guarded a frame. VICTORY_LAND_ANYTIME=0: as before. The vertices of rectangle lists are read through the kernel at submission, not under the lock the mapping holds. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 13 ++++++++----- crates/victory-gpu/src/land.rs | 25 +++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 4bca1ac..7197f01 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3187,15 +3187,18 @@ impl State { let (from, to, stride) = (from as usize, to as usize, stride as usize); let n = rects as usize; list.defer_host_read(from, n * 3 * stride, move || { - // The vertices are read in place, at submission: no change - // of mapping under the read (see - // `crate::watch::title_memory_reading`). - let _mapped = crate::watch::title_memory_reading(); + // The vertices are read through the kernel, at submission; in + // place only if that fails, with no change of mapping under + // the read (see `crate::watch::title_memory_reading`): while + // the world streams a change is under way most of the time, + // and this is the thread that submits. + let mut read = vec![0u8; n * 3 * stride]; + let held = (!crate::host::read_into(from as *const u8, &mut read)).then(crate::watch::title_memory_reading); // SAFETY: the vertices lie in a title buffer (checked when // recorded) and the scratch memory is the list's. let (src, dst) = unsafe { ( - std::slice::from_raw_parts(from as *const u8, n * 3 * stride), + if held.is_some() { std::slice::from_raw_parts(from as *const u8, n * 3 * stride) } else { &read[..] }, std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride), ) }; diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index f8d1cf9..34c359e 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -419,6 +419,26 @@ impl Had { } } +/// Whether a piece is put through a view of ours while the runtime changes +/// a mapping too (`VICTORY_LAND_ANYTIME=0`: through the title's address, as +/// before). +/// +/// While the world streams a change is under way nearly all the time (pages +/// are mapped in groups, eight threads side by side: 28 of 1,620 pieces a +/// frame went through a view of ours in run textures-4, 630 in run n03). Put +/// through the title's address a piece opens the guards of its blocks, 5,000 +/// changes of protection a frame, which wait for the address-space lock the +/// mapping wants as well, and every refresh guards them again: the frame went +/// from 105 to 140 ms. The record names a run of a section only while it is +/// mapped there (it is taken out before a view goes and put in when one is +/// there), so the change is one of other memory, or one the title makes of +/// memory its shaders are writing at that moment, which it may not (its +/// fences are signalled after the landing). +fn anytime() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_ANYTIME").is_none_or(|v| v != "0")) +} + /// What a job wrote beside the guards, to be noted ([`Notes::flush`]). #[derive(Default)] pub(crate) struct Notes { @@ -528,9 +548,10 @@ unsafe fn piece_at( }; // From here until the piece is put the runtime changes no mapping: our // view's address stays where the title sees `title`. Not waited for: if - // a change is under way, the title's own address does. + // a change is under way, what the record of the views says now does + // ([`anytime`]), or the title's own address. let reading = beside.then(crate::watch::title_memory_reading_now).flatten(); - let beside = reading.as_ref().and_then(|_| crate::inplace::beside(title, end)); + let beside = if reading.is_some() || beside && anytime() { crate::inplace::beside(title, end) } else { None }; count(stat::PIECES, 1); count(if beside.is_some() { stat::BESIDE } else { stat::DIRECT }, 1); // The pages that differ, before any is written: none, and the guard From 2c165e09cd573c266640d7b92d9dd43aac9adaec Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:43:37 -0600 Subject: [PATCH 3/3] The first copy into a texture the title fills goes over zeros VICTORY_COPY_OVER_TITLE=title: over what title memory holds; =0: over whatever the block of the pool held. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/list.rs | 28 ++++++++++++++++------ crates/victory-gpu/src/texture.rs | 40 +++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 84aa3a3..b0a1c33 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1024,19 +1024,33 @@ extern "system" fn copy_texture_region( // source above too). list.twin_use(dst.resource, false, true); // The first copy into a texture of the title's: what it does not - // write is what title memory holds, as on the console. (The host + // write is zeros, as in a texture that was an allocation of its own + // (`VICTORY_COPY_OVER_TITLE=title`: what title memory holds, which + // may be another texture's: specks on the waitress's forehead were + // left in run n04). (The host // copy is cut from a block and held whatever lay there, and no // upload is made once a copy wrote it: the atlas the title copies // its baked decorations into, a 2048x2048 BC3 texture of which a // bake writes 256x256 at most, was drawn over a character's face // with other textures' bytes wherever nothing was baked, runs n01 and // textures-1.) - static OVER: std::sync::OnceLock = std::sync::OnceLock::new(); - if *OVER.get_or_init(|| std::env::var_os("VICTORY_COPY_OVER_TITLE").is_none_or(|v| v != "0")) - && crate::texture::title_written(to) - && !crate::texture::host_wrote(dst.resource as usize) - { - crate::texture::upload(list, dst.resource, to); + static OVER: std::sync::OnceLock = std::sync::OnceLock::new(); + let over = *OVER.get_or_init(|| match std::env::var("VICTORY_COPY_OVER_TITLE").as_deref() { + Ok("0") => 0, + Ok("title") => 1, + _ => 2, + }); + if over != 0 && crate::texture::title_written(to) && !crate::texture::host_wrote(dst.resource as usize) { + // One a list uploaded, or a draw sampled, holds the title's. + if over == 2 && !list.used(dst.resource as usize) && !crate::texture::is_staged(dst.resource) { + if let Some(host) = crate::host::host() { + ensure_state(list, dst.resource, COPY_DEST); + let _ = list.first_use(dst.resource as usize); + crate::texture::zeros(list, host, to); + } + } else { + crate::texture::upload(list, dst.resource, to); + } // (Done before the title's copy writes over it.) if list.used(dst.resource as usize) { ensure_state(list, dst.resource, COPY_SOURCE); diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 7ad9915..dc7bad1 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -937,6 +937,46 @@ impl Drop for Claimed { } } +/// Records copies of zeros into every subresource of `texture`, which is in +/// the copy destination state. +pub(crate) fn zeros(list: &HostList, host: &crate::host::Host, texture: &ID3D12Resource) { + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + let layers = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { u32::from(d.DepthOrArraySize) }; + let count = u32::from(d.MipLevels) * layers; + let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; + let mut bytes = 0u64; + // SAFETY: outputs for `count` subresources. + unsafe { + host.device + .GetCopyableFootprints(&d, 0, count, 0, Some(footprints.as_mut_ptr()), None, None, Some(&mut bytes)); + } + if bytes == 0 || bytes == u64::MAX { + return; + } + let Some((buffer, data)) = list.upload(host, bytes) else { + return; + }; + // SAFETY: a mapped buffer of `bytes` bytes, just made. + unsafe { std::ptr::write_bytes(data, 0, bytes as usize) }; + for (i, footprint) in footprints.iter().enumerate() { + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: i as u32 }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above; the list holds the buffer until it is reset. + pResource: unsafe { std::mem::transmute_copy(&buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } +} + /// Levels on demand (`crate::tiles`): the card itself is about to write /// title texture `resource` in `list` (a copy or a resolve into level /// `level`, or into every level). If its host copy `texture` was made