From 0b651fa9a81fe81be0efdd51b24b36f941b801f2 Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:56:37 +0530 Subject: [PATCH 1/4] Texture pass: tell its "rest" apart (5-second line), waits for its locks The pass over textures picked by index logged 846 of 1,408 ms (cutscene, coolfox-20261126-223059) as "the rest". A second line now splits it: telling the queue what came of each slot, reading the slots' records, fingerprints after uploads and same-looks, handing first uploads to the copy queue ahead, slots shown after their upload / flipped / made at once, asking whether a staged texture's memory is all there, other checks; the waits for the queue's and the views table's locks (by the pass and by other threads, counted only when the lock was held: try_lock first); the work before the loops (not in "all"); passes by kind (frame, early, bake) with their time and how many stopped at their time or bytes; and the slots taken by outcome. The existing parts are summed in nanoseconds now: in microseconds each short call lost what it took below the next whole one. The pass reads the slot's view once for its placed and object checks (it read it twice). pass_costs (ignored test, a measurement): on this PC asking whether 1/4/16 MB of resident memory is all there takes 18/23/111 us, 0.9-15 ms when the pages were trimmed from the working set; a fingerprint 3-7 us. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 44 ++++- crates/victory-gpu/src/descriptor/host.rs | 53 ++++-- crates/victory-gpu/src/draw.rs | 219 ++++++++++++++++------ crates/victory-gpu/src/host.rs | 42 ++++- crates/victory-gpu/src/texture.rs | 45 +++++ 5 files changed, 323 insertions(+), 80 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 9c3cc2e..bd9f371 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -13,6 +13,28 @@ use crate::resource::{Memory, PAGEABLE_IIDS}; #[cfg(windows)] pub(crate) mod host; +thread_local! { + /// Set while this thread runs the pass over textures picked by index + /// (`crate::draw::State::heap_textures`): its waits for the locks below + /// are counted apart from other threads' ([`LOCK_WAITS`]). + pub(crate) static IN_TEXTURE_PASS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Nanoseconds threads waited for a lock another thread held, since the +/// last 5-second line: the queue of textures picked by index's +/// (`host::TextureQueue`) by the texture pass's thread and by the others +/// (the threads that note slot writes in it), then the table of views' +/// ([`VIEWS`]) likewise. Only waits are counted: a lock taken at once costs +/// nothing here (`try_lock` first). +pub(crate) static LOCK_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// A wait for lock `which` (0: the texture queue's, 1: the views table's) +/// that began at `started` is over: counted in [`LOCK_WAITS`]. +pub(crate) fn waited(which: usize, started: std::time::Instant) { + let other = usize::from(!IN_TEXTURE_PASS.get()); + LOCK_WAITS[2 * which + other].fetch_add(started.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed); +} + const HEAP_IIDS: [Iid; 4] = [ guid( 0x8efb471d, @@ -1051,11 +1073,29 @@ fn words_for(view: View) -> [u32; 2] { } fn views_read() -> std::sync::RwLockReadGuard<'static, Views> { - VIEWS.read().unwrap_or_else(|e| e.into_inner()) + match VIEWS.try_read() { + Ok(views) => views, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + let started = std::time::Instant::now(); + let views = VIEWS.read().unwrap_or_else(|e| e.into_inner()); + waited(1, started); + views + } + } } fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { - VIEWS.write().unwrap_or_else(|e| e.into_inner()) + match VIEWS.try_write() { + Ok(views) => views, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + let started = std::time::Instant::now(); + let views = VIEWS.write().unwrap_or_else(|e| e.into_inner()); + waited(1, started); + views + } + } } /// For the memory line: the distinct views kept ([`Views`]), those of them diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index c742914..5ceafb3 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1759,6 +1759,21 @@ fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { } impl HostHeap { + /// The queue of textures picked by index, locked; a wait for its lock + /// is counted (`super::LOCK_WAITS`). + fn queue(&self) -> std::sync::MutexGuard<'_, TextureQueue> { + match self.textures.try_lock() { + Ok(queue) => queue, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + let started = std::time::Instant::now(); + let queue = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + super::waited(0, started); + queue + } + } + } + /// `n` consecutive free dynamic slots (view heaps only), taken until /// [`HostHeap::release`]: the first's index. pub(crate) fn dynamic(&self, n: u32) -> Option { @@ -1839,14 +1854,14 @@ impl HostHeap { /// ([`TextureQueue::due`]), and the queue's counts /// ([`TextureQueue::census`]). pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 5]) { - let (due, census) = self.textures.lock().unwrap_or_else(|e| e.into_inner()).due_and_census(frame); + let (due, census) = self.queue().due_and_census(frame); (if max == 0 { Vec::new() } else { due.order(max) }, census) } /// 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 writes = self.queue().writes; let noted = |ranges: &Mutex>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty(); (writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN) || noted(&BAKE_PAGE_WRITTEN)) } @@ -1856,7 +1871,7 @@ impl HostHeap { /// look): for the card accounting line /// (`crate::resource::card_accounting`). pub(crate) fn texture_slots_all_due(&self, frame: u64) -> Vec<(u32, bool)> { - let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let textures = self.queue(); textures .slots .iter() @@ -1870,7 +1885,7 @@ impl HostHeap { /// that many bytes of its memory there, not all), or not until the /// slot is written again. pub(crate) fn texture_slot_done(&self, index: u32, write: u64, again: Option<(u64, u64)>) { - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); match again { Some((frame, mapped)) => textures.partly(index, write, frame, mapped), None => textures.done(index, write), @@ -1889,37 +1904,37 @@ impl HostHeap { looks: u8, uploaded: u64, ) { - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); textures.recheck(index, write, due, at, print, looks, uploaded); } /// See [`TextureQueue::checked`]. pub(crate) fn texture_slot_checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { - self.textures.lock().unwrap_or_else(|e| e.into_inner()).checked(index) + self.queue().checked(index) } /// Nothing to upload at title slot `index` now (its memory is not /// mapped, or no more of it than before): looked at again after 1, 2, /// 4, ... frames, at most `most`. pub(crate) fn texture_slot_later(&self, index: u32, write: u64, frame: u64, most: u64) { - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); textures.later(index, write, frame, most); } /// See [`TextureQueue::hold`]. pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) { - self.textures.lock().unwrap_or_else(|e| e.into_inner()).hold(index, write, due); + self.queue().hold(index, write, due); } /// See [`TextureQueue::room`]. pub(crate) fn texture_slots_room(&self, frame: u64) -> usize { - self.textures.lock().unwrap_or_else(|e| e.into_inner()).room(frame) + self.queue().room(frame) } /// Bytes of title slot `index`'s memory that were mapped when it was /// last uploaded in part (0: not uploaded, or whole). pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 { - self.textures.lock().unwrap_or_else(|e| e.into_inner()).mapped(index) + self.queue().mapped(index) } /// Takes the ranges of title memory the runtime mapped, unmapped or @@ -1947,7 +1962,7 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); for &slot in &slots { textures.changed(slot, frame, frame + 1); } @@ -1972,7 +1987,7 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); for &slot in &slots { textures.changed(slot, frame, frame + 1); } @@ -2032,7 +2047,7 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); for &slot in &slots { textures.changed(slot, frame, frame); @@ -2053,7 +2068,7 @@ impl HostHeap { slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); let held = slots.len(); - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); // Uploaded before: out of the queue, or in it after an upload (in // part, or whole and being looked at again). slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); @@ -2143,7 +2158,7 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); for &slot in &slots { textures.changed(slot, frame, frame + 1); } @@ -2638,7 +2653,7 @@ impl HostHeap { if old != now | TABLED_READ { stamp.store(now | TABLED_READ, Relaxed); if tabled_out() { - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); if textures.slots.remove(&index).is_some() { TABLED_WRITES[1].fetch_add(1, Relaxed); } @@ -2674,7 +2689,7 @@ impl HostHeap { // Made now by a draw of this frame that read it through a table: // up to date. let read_now = seen && stamp == now | TABLED_READ; - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); if texture && !read_now { let due = if lately && !seen { TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -2783,7 +2798,7 @@ impl HostHeap { }; if !stale.is_empty() { STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed); - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); for &(slot, _) in &stale { textures.remove(slot); } @@ -3411,7 +3426,7 @@ impl HostHeap { /// `index` at `frame`, in a few words (diagnostics). #[cfg(feature = "diagnostics")] pub(crate) fn texture_slot_state(&self, index: u32, frame: u64) -> String { - let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let textures = self.queue(); match textures.slots.get(&index) { None => "not queued".into(), Some(w) => format!( diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c87e5ae..be73a6a 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -905,15 +905,73 @@ pub(crate) static HEAP_TEXTURES_PARTLY: [AtomicU64; 3] = [const { AtomicU64::new /// time. The pass stops at `VICTORY_TEXTURE_STAGE_MS` (16 in /// the launcher), and in play it ran 18-20 ms a frame for about 20 /// textures: these say what took the time. -pub(crate) static HEAP_TEXTURE_MICROS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; +/// In nanoseconds: in microseconds each call lost what it took below the +/// next whole one, and a slot asks five or six such short questions. +pub(crate) static HEAP_TEXTURE_NANOS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; -/// `f`'s result, its time added to [`HEAP_TEXTURE_MICROS`]' place `slot`. +/// `f`'s result, its time added to [`HEAP_TEXTURE_NANOS`]' place `slot`. fn timed(slot: usize, f: impl FnOnce() -> T) -> T { let started = std::time::Instant::now(); let out = f(); - HEAP_TEXTURE_MICROS[slot].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + HEAP_TEXTURE_NANOS[slot].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); out } + +/// Nanoseconds of the pass over textures picked by index outside the parts +/// of [`HEAP_TEXTURE_NANOS`], since the last 5-second line (2026-11-26 in a +/// cutscene: 846 of 1,408 ms were none of those): telling the queue what +/// came of each slot (`TextureQueue`, its lock included); reading the slots' +/// records (the view a slot holds, what its host slot was made from); +/// fingerprints made after an upload or a look that found the host copy +/// the same (for the looks again, `RECHECK_FRAMES`); handing first uploads +/// to the copy queue ahead (`texture::ahead`: the staging buffer is made +/// here); slots shown after their upload, flipped, or made at once; asking +/// whether a staged texture's memory is all there (`texture::staged`); the +/// other checks of an upload (the device, the staging map, the commit +/// reserve); and the pass's work before its loop over the slots (not in +/// [`HEAP_TEXTURE_NANOS`]' place 4: what was due made due, the slots due +/// found and ordered, the flips and remade views of earlier uploads). +pub(crate) static HEAP_TEXTURE_REST: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + +/// `f`'s result, its time added to [`HEAP_TEXTURE_REST`]' place `slot`. +fn rest(slot: usize, f: impl FnOnce() -> T) -> T { + let started = std::time::Instant::now(); + let out = f(); + HEAP_TEXTURE_REST[slot].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + out +} + +/// Slots the pass took up since the last 5-second line, and what came of +/// them: looked at again after an upload and found unchanged; memory not +/// mapped; no more of it mapped than at its upload in part; nothing to +/// bring up to date (a texture the host writes, no texture); held back for +/// want of room on the card; the host copy held those bytes; uploaded by +/// the copy queue ahead; uploaded in the pass's list; read through tables +/// (the draws upload it). Places: [`slot_outcome`]. +pub(crate) static HEAP_TEXTURE_SLOTS: [AtomicU64; 10] = [const { AtomicU64::new(0) }; 10]; +/// Places of [`HEAP_TEXTURE_SLOTS`]. +mod slot_outcome { + pub(super) const TAKEN: usize = 0; + pub(super) const UNCHANGED: usize = 1; + pub(super) const AWAY: usize = 2; + pub(super) const NO_MORE: usize = 3; + pub(super) const NOTHING: usize = 4; + pub(super) const HELD: usize = 5; + pub(super) const SAME: usize = 6; + pub(super) const AHEAD: usize = 7; + pub(super) const LISTED: usize = 8; + pub(super) const TABLED: usize = 9; +} + +fn outcome(which: usize) { + HEAP_TEXTURE_SLOTS[which].fetch_add(1, Ordering::Relaxed); +} + +/// Passes since the last 5-second line by kind (the frame's, from +/// [`State::heap_buffers`]; the early one at a frame's first draw; before a +/// bake draw), their loops' nanoseconds by kind, and the passes that stopped +/// at their time and at their bytes. +pub(crate) static HEAP_TEXTURE_PASSES: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; static DROPPED: AtomicU64 = AtomicU64::new(0); /// Marks the last traced draw as not run on the host. @@ -2872,6 +2930,16 @@ impl State { if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) { return true; } + /// Marks this thread as the pass's while it runs + /// (`crate::descriptor::IN_TEXTURE_PASS`). + struct InPass(bool); + impl Drop for InPass { + fn drop(&mut self) { + crate::descriptor::IN_TEXTURE_PASS.set(self.0); + } + } + let _in_pass = InPass(crate::descriptor::IN_TEXTURE_PASS.replace(true)); + let entered = std::time::Instant::now(); let memory = crate::host::host().and_then(|h| h.video_memory()); // `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of // textures (a scene's first minutes) then drains in fewer frames. @@ -3016,15 +3084,26 @@ impl State { }; let began = std::time::Instant::now(); + HEAP_TEXTURE_REST[7].fetch_add(began.duration_since(entered).as_nanos() as u64, Ordering::Relaxed); + // The frame's pass, the early one, or the one before a bake. + let kind = match PASS_BUDGET.get() { + None => 0, + Some((_, _, false)) => 1, + Some((_, _, true)) => 2, + }; + HEAP_TEXTURE_PASSES[kind].fetch_add(1, Ordering::Relaxed); if sync.is_none() { 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 { + let at_time = began.elapsed() > span; + if at_time || SPENT.load(Ordering::Relaxed) >= bytes_at_most { + HEAP_TEXTURE_PASSES[if at_time { 6 } else { 7 }].fetch_add(1, Ordering::Relaxed); served = false; break; } + outcome(slot_outcome::TAKEN); // A placed texture whose memory is not mapped (not streamed in // yet, or streamed out again: the heap keeps tens of thousands // of such views) gets no host texture; looked at again soon (a @@ -3050,16 +3129,17 @@ impl State { // (all their blocks are shown at other addresses too), and each // was shown four frames late, over and over. let mut again_in = RECHECK_FRAMES[0]; - if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) { + if let Some((at, len, print, looks, uploaded)) = rest(0, || host.texture_slot_checked(index)) { let looked = timed(0, || crate::texture::fingerprint(at, len)); if looked == print { HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed); - match RECHECK_FRAMES.get(usize::from(looks) + 1) { + outcome(slot_outcome::UNCHANGED); + rest(0, || match RECHECK_FRAMES.get(usize::from(looks) + 1) { Some(wait) => { host.texture_slot_recheck(index, write, frame + wait, (at, len), print, looks + 1, uploaded) } None => host.texture_slot_done(index, write, None), - } + }); continue; } if recheck_soon() { @@ -3089,24 +3169,30 @@ 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) { + // The view the slot holds now, read once for the looks below. + let held = rest(1, || heap.handle(index).and_then(crate::descriptor::view)); + if let Some(View::Placed(false, resource, desc)) = &held { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; - let first = crate::resource::first_mip(&desc); - let len = crate::resource::placed_bytes_from(&resource, first).unwrap_or(1); + let first = crate::resource::first_mip(desc); + let len = crate::resource::placed_bytes_from(resource, first).unwrap_or(1); let mapped = timed(1, || crate::texture::mapped_bytes(address as *const u8, len as usize)); if mapped == 0 { HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed); + outcome(slot_outcome::AWAY); // Streamed out: what the slot showed is let go. - host.texture_slot_gone(index); - host.texture_slot_later(index, write, frame, most); + rest(0, || { + host.texture_slot_gone(index); + host.texture_slot_later(index, write, frame, most); + }); continue; } - host.texture_slot_here(index); + rest(0, || host.texture_slot_here(index)); there = Some(mapped); if mapped < len { - if mapped <= host.texture_slot_mapped(index) { + if mapped <= rest(0, || host.texture_slot_mapped(index)) { HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed); - host.texture_slot_later(index, write, frame, most); + outcome(slot_outcome::NO_MORE); + rest(0, || host.texture_slot_later(index, write, frame, most)); continue; } if !crate::texture::committed(address as *const u8, 1) { @@ -3119,11 +3205,12 @@ impl State { // host's own contents: nothing to bring up to date, and this // pass is no use of it (its host copy is made when something // uses it, and its slots then: `descriptor::make_waiting`). - if let Some(View::Shader(object, _)) = heap.handle(index).and_then(crate::descriptor::view) + if let Some(View::Shader(object, _)) = held && crate::resource::buffer_bytes(object as This).is_none() && !crate::resource::title_fills(object as This) { - host.texture_slot_done(index, write, None); + outcome(slot_outcome::NOTHING); + rest(0, || host.texture_slot_done(index, write, None)); continue; } // From here on a host texture is made: not without room. The @@ -3141,14 +3228,15 @@ impl State { // before. if !room { let has_its_texture = reupload_when_full() - && heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle)); + && rest(1, || heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle))); if !has_its_texture { refused += 1; + outcome(slot_outcome::HELD); if full_card_pass() { // Held back for the frames of about four seconds // (`most`), or until the card has room; the pass // goes on, within a count that bounds one pass. - host.texture_slot_held(index, write, frame + most); + rest(0, || host.texture_slot_held(index, write, frame + most)); if refused > 1024 { break; } @@ -3169,7 +3257,7 @@ impl State { // Gate new host texture creation / staging on commit reserve after // `mapped == 0` reclamation (`texture_slot_gone`) has run, and // before mirroring a slot to an unuploaded texture. - if !crate::residency::admit_texture_pass(required) { + if !rest(6, || crate::residency::admit_texture_pass(required)) { served = false; break; } @@ -3180,14 +3268,14 @@ impl State { let shows_other = !baking && !sync_bake && crate::resource::held_only() - && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle)); + && rest(1, || heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle))); // A slot that shows nothing of it yet, or something else, shows it // when the upload has run too. let late = !shows_other && !baking && !sync_bake && crate::descriptor::host::show_after() - && heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle)); + && rest(1, || heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle))); let (view, bake_key) = timed(6, || { if sync_bake { match heap.handle(index).and_then(|handle| host.prepare_bake_slot(index, handle)) { @@ -3203,7 +3291,9 @@ impl State { }); let at_once = || { if (late || bake_key.is_some()) && let Some(handle) = heap.handle(index) { - let _ = host.mirror(index, handle, true); + rest(4, || { + let _ = host.mirror(index, handle, true); + }); } }; let placed = timed(6, || view.as_ref().and_then(crate::descriptor::host::placed_texture)); @@ -3215,7 +3305,8 @@ impl State { Some(&View::Shader(resource, _)) => resource as This, _ => { at_once(); - host.texture_slot_done(index, write, None); + outcome(slot_outcome::NOTHING); + rest(0, || host.texture_slot_done(index, write, None)); continue; } }; @@ -3224,17 +3315,18 @@ impl State { served = false; break; } - let title_fills = texture.is_some_and(crate::texture::title_written); + let title_fills = rest(6, || texture.is_some_and(crate::texture::title_written)); if !title_fills { at_once(); // a render target, a depth or unordered access texture: the host's own - host.texture_slot_done(index, write, None); + outcome(slot_outcome::NOTHING); + rest(0, || host.texture_slot_done(index, write, None)); continue; } // A texture that has a staging buffer now is one draws read // through a table: they upload it, and check it at every // submission that samples it. - let tabled = crate::texture::is_staged(resource); + let tabled = rest(6, || crate::texture::is_staged(resource)); // The host copy holds these very bytes: nothing to upload. let first = match (&placed, &view) { (Some(_), Some(View::Placed(_, _, desc))) => crate::resource::first_mip(desc), @@ -3243,6 +3335,7 @@ impl State { let same = !tabled && timed(2, || crate::texture::unchanged(resource, first)); if same { HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed); + outcome(slot_outcome::SAME); if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) { if let Some(copy) = crate::resource::host_copy(resource) { sync.keep.push(copy); @@ -3250,44 +3343,52 @@ impl State { sync.publish.push((index, handle, key)); } else { if shows_other && let Some(handle) = heap.handle(index) { - let _ = host.mirror(index, handle, true); + rest(4, || { + let _ = host.mirror(index, handle, true); + }); } // Its bytes are in, or on the way there in a list before. if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) { if let Some(handle) = heap.handle(index) { - host.texture_slot_show_after(list, index, handle); + rest(4, || host.texture_slot_show_after(list, index, handle)); } } else { at_once(); } } let again = partly.map(|mapped| (frame + 1, mapped)); - let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None }; - match memory { - Some((at, len)) => { - let print = crate::texture::fingerprint(at, len); + let memory = rest(2, || { + let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None }; + memory.map(|(at, len)| (at, len, crate::texture::fingerprint(at, len))) + }); + rest(0, || match memory { + Some((at, len, print)) => { host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame); } None => host.texture_slot_done(index, write, again), - } + }); continue; } // The first upload of a texture no list has used: on a queue of // its own, and the slot shows it as soon as that has run. let ahead = if late && !tabled && texture.is_some_and(crate::pool::fresh) { - crate::texture::ahead::take(resource, first, there.filter(|_| partly.is_none()).unwrap_or(u64::MAX)) + rest(3, || { + crate::texture::ahead::take(resource, first, there.filter(|_| partly.is_none()).unwrap_or(u64::MAX)) + }) } else { None }; if let Some(ahead) = &ahead { use crate::texture::ahead::Taken; let (Taken::New(job) | Taken::Known(job)) = ahead; - if let Some(handle) = heap.handle(index) { - host.texture_slot_show_ahead(job, index, handle); - } - if let Taken::New(job) = ahead { - crate::texture::ahead::send(job); - } + rest(3, || { + if let Some(handle) = heap.handle(index) { + host.texture_slot_show_ahead(job, index, handle); + } + if let Taken::New(job) = ahead { + crate::texture::ahead::send(job); + } + }); } if ahead.is_none() && crate::residency::upload_refused() { served = false; @@ -3320,10 +3421,10 @@ impl State { sync.publish.push((index, handle, key)); } if shows_other && let Some(handle) = heap.handle(index) { - host.texture_slot_flip(list, index, handle); + rest(4, || host.texture_slot_flip(list, index, handle)); } if late && let Some(handle) = heap.handle(index) { - host.texture_slot_show_after(list, index, handle); + rest(4, || host.texture_slot_show_after(list, index, handle)); } #[cfg(feature = "diagnostics")] if crate::book::on() @@ -3345,7 +3446,7 @@ impl State { // A texture view the host refuses removes the device: name it. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !GONE.load(Ordering::Relaxed) - && let Some(why) = crate::descriptor::host::device_removed() + && let Some(why) = rest(6, crate::descriptor::host::device_removed) { GONE.store(true, Ordering::Relaxed); let text: String = format!("{view:?}").chars().take(300).collect(); @@ -3353,7 +3454,7 @@ impl State { crate::host::log_removal_context(); return false; } - let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true)); + let (bytes, whole) = rest(5, || 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 @@ -3371,7 +3472,8 @@ impl State { // next draw that reads the texture through a table stage, // detile and upload all of it once more. HEAP_TEXTURES_TABLED.fetch_add(1, Ordering::Relaxed); - host.texture_slot_done(index, write, again); + outcome(slot_outcome::TABLED); + rest(0, || host.texture_slot_done(index, write, again)); continue; } // Uploaded: the list holds the staging buffer until it has run; @@ -3379,33 +3481,34 @@ impl State { // yet, makes it anew. (Kept for those until now: every partly // streamed texture of the heap held a staging buffer of its full // size for good.) - let memory = if again.is_none() && heap_recheck() { - crate::texture::staged_memory(resource) - } else { - None - }; - crate::texture::unstage(resource); + outcome(if ahead.is_some() { slot_outcome::AHEAD } else { slot_outcome::LISTED }); + let memory = rest(2, || { + let memory = if again.is_none() && heap_recheck() { crate::texture::staged_memory(resource) } else { None }; + memory.map(|(at, len)| (at, len, crate::texture::fingerprint(at, len))) + }); + rest(6, || crate::texture::unstage(resource)); SPENT.fetch_add(bytes, Ordering::Relaxed); since_asked += bytes; if room && since_asked >= 32 << 20 { since_asked = 0; - room = crate::resource::room(crate::host::host().and_then(|h| h.video_memory())); + room = rest(6, || crate::resource::room(crate::host::host().and_then(|h| h.video_memory()))); } HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed); HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed); - match memory { + rest(0, || match memory { // Whole and uploaded: looked at again (see above). - Some((at, len)) => { - let print = crate::texture::fingerprint(at, len); + Some((at, len, print)) => { host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame); } None => host.texture_slot_done(index, write, again), - } + }); } if sync.is_none() && baking && served { BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed); } - HEAP_TEXTURE_MICROS[4].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + let took = began.elapsed().as_nanos() as u64; + HEAP_TEXTURE_NANOS[4].fetch_add(took, Ordering::Relaxed); + HEAP_TEXTURE_PASSES[3 + kind].fetch_add(took, Ordering::Relaxed); served } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index e4a3f59..98d76bb 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -9007,7 +9007,12 @@ impl Meter { ); } let [looks, mapped, same, staged, all, made, views] = - [0, 1, 2, 3, 4, 5, 6].map(|i| crate::draw::HEAP_TEXTURE_MICROS[i].swap(0, Ordering::Relaxed) / 1000); + [0, 1, 2, 3, 4, 5, 6].map(|i| crate::draw::HEAP_TEXTURE_NANOS[i].swap(0, Ordering::Relaxed) / 1_000_000); + let rest = all.saturating_sub(looks + mapped + same + staged + made + views); + let parts = crate::draw::HEAP_TEXTURE_REST.each_ref().map(|n| n.swap(0, Ordering::Relaxed) / 1_000_000); + let waits = crate::descriptor::LOCK_WAITS.each_ref().map(|n| n.swap(0, Ordering::Relaxed) / 1_000_000); + let passes = crate::draw::HEAP_TEXTURE_PASSES.each_ref().map(|n| n.swap(0, Ordering::Relaxed)); + let slots = crate::draw::HEAP_TEXTURE_SLOTS.each_ref().map(|n| n.swap(0, Ordering::Relaxed)); if all > 0 { tracing::info!( "the pass over textures picked by index, in the last 5 seconds: {all} ms in all, of them {looks} ms looking \ @@ -9020,6 +9025,41 @@ impl Meter { crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20 ); } + if all > 0 || parts[7] > 0 { + let [queue, records, prints, ahead, shown, whole, checks, before] = parts; + let [n_frame, n_early, n_bake, t_frame, t_early, t_bake, at_time, at_bytes] = passes; + tracing::info!( + "the pass over textures picked by index, its rest in the last 5 seconds: {queue} ms telling the queue \ + what came of each slot, {records} ms reading the slots' records, {prints} ms fingerprints after uploads \ + and looks that found the host copy the same, {ahead} ms handing first uploads to the copy queue ahead, \ + {shown} ms slots shown after their upload, flipped or made at once, {whole} ms asking whether a staged \ + texture's memory is all there, {checks} ms other checks, {} ms not told apart; waited for locks: the \ + queue's {} ms by the pass ({} ms by other threads), the views' {} ms by the pass ({} ms by other threads); \ + {before} ms before the passes' loops (not in the line above); passes: {n_frame} the frame's ({} ms), \ + {n_early} early ({} ms), {n_bake} before bakes ({} ms), {at_time} stopped at their time, {at_bytes} at their \ + bytes; slots taken {}: {} looked at again and unchanged, {} memory not there, {} no more of it there, \ + {} nothing to bring up to date, {} held back for room, {} the same as their host copy, {} uploaded \ + ahead, {} uploaded in the pass's list, {} read through tables", + rest.saturating_sub(queue + records + prints + ahead + shown + whole + checks), + waits[0], + waits[1], + waits[2], + waits[3], + t_frame / 1_000_000, + t_early / 1_000_000, + t_bake / 1_000_000, + slots[0], + slots[1], + slots[2], + slots[3], + slots[4], + slots[5], + slots[6], + slots[7], + slots[8], + slots[9], + ); + } } if crate::resource::held_only() { let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed)); diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 869454d..08314bb 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -2229,6 +2229,51 @@ mod allocation_costs { } } + /// What the pass over textures picked by index pays per slot outside its + /// timed parts (2026-11-26): asking whether a staged texture's memory is + /// all there (`staged(_, true)`, a question per 256 pages), and the + /// fingerprint of 48 KiB made after each upload and each texture found + /// the same. For `cargo test -p victory-gpu --release --lib pass_costs -- + /// --ignored --nocapture`. + #[test] + #[ignore = "a measurement, not a check"] + fn pass_costs() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + use windows_sys::Win32::System::ProcessStatus::K32EmptyWorkingSet; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + for mb in [1usize, 4, 16] { + let len = mb << 20; + // SAFETY: memory of our own, committed and touched. + let at = unsafe { + let at = VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + std::ptr::write_bytes(at.cast::(), 1, len); + at as usize + }; + const N: u32 = 200; + let began = std::time::Instant::now(); + for _ in 0..N { + assert!(super::committed(at as *const u8, len)); + } + println!("{mb} MB, all in the working set: whether it is all there, {:.1} us", began.elapsed().as_secs_f64() * 1e6 / f64::from(N)); + // Pages out of the working set (trimmed, as Windows does to a + // process under pressure) are asked again by a read of a byte. + let mut worst = 0f64; + for _ in 0..5 { + // SAFETY: our own process. + unsafe { K32EmptyWorkingSet(GetCurrentProcess()) }; + let began = std::time::Instant::now(); + assert!(super::committed(at as *const u8, len)); + worst = worst.max(began.elapsed().as_secs_f64() * 1e6); + } + println!("{mb} MB, just trimmed from the working set: {worst:.1} us"); + let began = std::time::Instant::now(); + for _ in 0..N { + std::hint::black_box(super::fingerprint(at as u64, len as u64)); + } + println!("{mb} MB: a fingerprint, {:.1} us", began.elapsed().as_secs_f64() * 1e6 / f64::from(N)); + } + } + /// The digest tells every length and every changed byte apart, zeros /// among them. #[test] From 36c4c3746c7c022aca433f7b92f01f291015e417 Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:58:37 +0530 Subject: [PATCH 2/4] Texture pass: ask whether a staged texture is all there only at title addresses `texture::staged(_, ask)` asked Windows whether every page of the texture's memory is there (QueryWorkingSetEx per 256 pages, and a one-byte read of each page not in the working set) for every texture object the pass took: 20,000 to 57,000 every 5 seconds, most of them slots read through tables, which the pass only marks done. A whole run found 66 not all there. The pass's unattributed time followed their count: rest = 400 ms + 12.7 us x tabled slots per 5 s over the run's lines (coolfox-20261126-223059, e.g. 17:02:57 57,760 -> 1,136 ms, 17:03:58 17,786 -> 629 ms). Measured here (pass_costs): 18-111 us for 1-16 MB resident, 0.9-15 ms when the pages had been trimmed. Only a resource made at an address the title mapped can lose its memory while it lives; a committed resource's memory and a heap's are allocated and zeroed whole when made. So the question is asked of those alone (`resource::at_title_address`); `VICTORY_STAGED_ASK_ALL=1` asks of every texture, as before. Expected: the cutscene's 846 ms "rest" per 5 s drops by about 13 us x the tabled slots (400-700 ms), gameplay's ~690 ms by ~250 ms. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/resource.rs | 32 ++++++++++++++++++++++++++++++ crates/victory-gpu/src/texture.rs | 14 +++++++++++++ 2 files changed, 46 insertions(+) diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 45c4916..d3d0717 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2859,6 +2859,14 @@ pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> { (r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc)) } +/// Whether resource `this` lies in memory the title mapped itself (made at +/// an address): the only resource memory that can be unmapped while the +/// resource lives. A committed resource's memory and a heap's are ours, +/// allocated and zeroed whole when they were made. +pub(crate) fn at_title_address(this: This) -> bool { + !this.is_null() && matches!(resource(this).backing, Backing::Address(_)) +} + /// A buffer's host memory and size; `None` for textures. pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> { if this.is_null() { @@ -3605,6 +3613,30 @@ mod tests { heap } + /// Only a resource made at an address the title mapped can lose its + /// memory while it lives (`crate::texture::staged` asks only of those). + #[test] + fn only_resources_at_a_title_address_may_lose_their_memory() { + let null = std::ptr::null(); + let committed = test_buffer(256); + assert!(!at_title_address(committed)); + let heap = heap(KIB_64); + let mut placed = null; + assert_eq!(create_placed(null, heap, 0, &texture(64, 64, 28, 1), 0, null.cast(), &RESOURCE_IIDS[0], &mut placed), S_OK); + assert!(!at_title_address(placed)); + let title = vec![0u8; KIB_64 as usize]; + let mut at = null; + assert_eq!( + create_at_address(null, title.as_ptr() as u64, &texture(64, 64, 28, 1), 0, null.cast(), &RESOURCE_IIDS[0], &mut at), + S_OK + ); + assert!(at_title_address(at)); + assert!(!at_title_address(null)); + for r in [committed, placed, at, heap] { + slot::(r, 0x10)(r); + } + } + #[test] fn heaps_are_zeroed_aligned_memory() { let heap = heap(1 << 20); diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 08314bb..ef1831f 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -1742,11 +1742,25 @@ 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. /// (Whether it is mapped is asked only if `ask`; else it counts as mapped.) +/// Only of a texture at an address the title mapped +/// ([`crate::resource::at_title_address`]): the memory of any other is all +/// there while it lives. The pass over textures picked by index asked it of +/// every texture object it took, 20,000-57,000 every 5 seconds, most of them +/// read through tables (a question per 256 pages: 18-111 us for 1-16 MB, +/// milliseconds when the pages had left the working set, and each such page +/// read back into it), for 66 found not all there in a whole run +/// (coolfox-20261126-223059); the pass's unattributed time went with their +/// count, 13 us each. `VICTORY_STAGED_ASK_ALL=1`: asked of every texture, +/// as before. pub(crate) fn staged(resource: This, ask: bool) -> Option<(u64, bool)> { + static ALL: std::sync::OnceLock = std::sync::OnceLock::new(); let s = { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref()?.get(&(resource as usize))?.clone() }; + let ask = ask + && (*ALL.get_or_init(|| std::env::var_os("VICTORY_STAGED_ASK_ALL").is_some_and(|v| v == "1")) + || crate::resource::at_title_address(resource)); Some((s.read as u64, !ask || committed(s.memory, s.read))) } From c1d1b4ee765e30c6db0d2fc6240c0f3a3562a46c Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:03:25 +0530 Subject: [PATCH 3/4] Texture queue census: slots waiting for a look again are not waiting for their memory The census counted a slot uploaded whole and waiting for its looks again (RECHECK_FRAMES 4, 12, 40, 120, 400 frames: in the queue up to 576 frames after its upload) as "waiting for their memory", and its old write as "the oldest". In coolfox-20261126-223059 at 17:02:04 the queue line said 19,277 waiting for their memory when the looks that had found memory not there numbered 1,700 in the whole run (17:01:45: 6,842 vs 104; 17:01:59: 19,023 vs 471): nine in ten or more of them were uploaded textures waiting for a look again, not streaming. They are counted apart now ("uploaded whole and waiting to be looked at again"), and "the oldest" is of slots not uploaded yet. A new 5-second line says how late first uploads are: slots served for the first time at their first look, with the frames they had been due before the pass took them (the pass's own lateness: its time cap), and slots served after their memory was found not there, with the frames since their write (streaming: mapping that came late). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 87 ++++++++++++++++++++--- crates/victory-gpu/src/draw.rs | 5 +- crates/victory-gpu/src/host.rs | 23 ++++-- 3 files changed, 100 insertions(+), 15 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 5ceafb3..456860a 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -997,18 +997,23 @@ impl TextureQueue { /// slots in the first gameplay area kept it 1-5 ms a pass, and the /// title's recording threads, whose every descriptor copy notes its slot /// here, waited that long behind it (run timeline, 2026-11-26). - fn due_and_census(&self, frame: u64) -> (Due, [u64; 5]) { + fn due_and_census(&self, frame: u64) -> (Due, [u64; 6]) { let mut due = Due::default(); - let mut c = [self.slots.len() as u64, 0, 0, 0, 0]; + let mut c = [self.slots.len() as u64, 0, 0, 0, 0, 0]; for (&index, w) in &self.slots { + let again = w.checked.2 != 0; if w.mapped > 0 { c[3] += 1; + } else if again { + c[5] += 1; } else if w.looks > 0 { c[2] += 1; } if w.due <= frame { c[1] += 1; - c[4] = c[4].max(frame.saturating_sub(w.written)); + if !again { + c[4] = c[4].max(frame.saturating_sub(w.written)); + } let class = if w.looks > 0 || w.mapped > 0 { &mut due.again } else { &mut due.fresh }; class.push((w.written, index, w.write)); } @@ -1148,25 +1153,66 @@ impl TextureQueue { /// For the frame line (made with the slots due, by /// [`TextureQueue::due_and_census`]): slots in the queue; of them due at `frame`; /// waiting for their memory (looked at, never uploaded); uploaded in - /// part; and the frames the oldest due one has waited since its write. + /// part; the frames the oldest due one not uploaded yet has waited + /// since its write; and the slots uploaded whole that wait for a look + /// again ([`TextureQueue::recheck`]). (Those were counted as waiting + /// for their memory, and their writes as the oldest: 19,023 of a + /// cutscene's 19,277 "waiting for their memory" were such slots, + /// coolfox-20261126-223059 17:02:04, where 1,700 looks in all had found + /// memory not there.) #[cfg(test)] - fn census(&self, frame: u64) -> [u64; 5] { - let mut c = [self.slots.len() as u64, 0, 0, 0, 0]; + fn census(&self, frame: u64) -> [u64; 6] { + let mut c = [self.slots.len() as u64, 0, 0, 0, 0, 0]; for w in self.slots.values() { + let again = w.checked.2 != 0; if w.mapped > 0 { c[3] += 1; + } else if again { + c[5] += 1; } else if w.looks > 0 { c[2] += 1; } if w.due <= frame { c[1] += 1; - c[4] = c[4].max(frame.saturating_sub(w.written)); + if !again { + c[4] = c[4].max(frame.saturating_sub(w.written)); + } } } c } + + /// The pass serves slot `index` (as handed out with `write`) in + /// `frame`: if it was not served before (not uploaded in part, not + /// waiting for a look again), counted in [`SERVED`]: at its first look, + /// by the frames it was due and not taken; after looks that found its + /// memory not there, by the frames since its write. + fn note_served(&self, index: u32, write: u64, frame: u64) { + use std::sync::atomic::Ordering::Relaxed; + let Some(w) = self.slots.get(&index).filter(|w| w.write == write) else { + return; + }; + if w.mapped > 0 || w.checked.2 != 0 { + return; + } + let (which, frames) = if w.looks == 0 { + (0, frame.saturating_sub(w.due.max(w.written))) + } else { + (3, frame.saturating_sub(w.written)) + }; + SERVED[which].fetch_add(1, Relaxed); + SERVED[which + 1].fetch_add(frames, Relaxed); + SERVED[which + 2].fetch_max(frames, Relaxed); + } } +/// Slots of textures picked by index the pass served for the first time, +/// since the last 5-second line: at their first look, with the frames they +/// had been due before the pass took them (in all, and the most); after +/// looks that found their memory not there, with the frames since their +/// write (in all, and the most). ([`TextureQueue::note_served`].) +pub(crate) static SERVED: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + /// Whether `view` is of a texture the title may fill itself: a texture it /// placed in memory, or a texture object. pub(crate) fn is_texture_view(view: &View) -> bool { @@ -1853,7 +1899,7 @@ impl HostHeap { /// with its write number, in the order to serve them /// ([`TextureQueue::due`]), and the queue's counts /// ([`TextureQueue::census`]). - pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 5]) { + pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 6]) { let (due, census) = self.queue().due_and_census(frame); (if max == 0 { Vec::new() } else { due.order(max) }, census) } @@ -1886,6 +1932,7 @@ impl HostHeap { /// slot is written again. pub(crate) fn texture_slot_done(&self, index: u32, write: u64, again: Option<(u64, u64)>) { let mut textures = self.queue(); + textures.note_served(index, write, crate::frame::current()); match again { Some((frame, mapped)) => textures.partly(index, write, frame, mapped), None => textures.done(index, write), @@ -1905,6 +1952,7 @@ impl HostHeap { uploaded: u64, ) { let mut textures = self.queue(); + textures.note_served(index, write, crate::frame::current()); textures.recheck(index, write, due, at, print, looks, uploaded); } @@ -5372,7 +5420,7 @@ mod tests { // newest, oldest, newest, oldest, and so on assert_eq!(order, [5, 10, 17, 11, 16, 12, 15, 13, 14]); assert_eq!(q.due(9, 2).len(), 2); - assert_eq!(q.census(9), [9, 9, 0, 0, 8]); + assert_eq!(q.census(9), [9, 9, 0, 0, 8, 0]); // Slot 17's memory is not mapped: again next frame, then in 2, 4, 4. let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1; let w17 = write(&q, 17); @@ -5417,6 +5465,27 @@ mod tests { assert!(q.due(16, 100).iter().any(|d| d.0 == 98)); } + /// A slot uploaded whole that waits for a look again is counted apart: + /// not as waiting for its memory, and not as the oldest due slot. + #[test] + fn slots_waiting_for_a_look_again_are_not_waiting_for_their_memory() { + let mut q = TextureQueue::default(); + q.written(1, 1, 0, false); + q.written(2, 5, 0, false); + let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1; + let (w1, w2) = (write(&q, 1), write(&q, 2)); + // Slot 1 uploaded whole at frame 10, looked at again from frame 14; + // slot 2's memory not there at frame 10. + q.recheck(1, w1, 14, (0x1_0000, 4096), 7, 0, 10); + q.later(2, w2, 10, 4); + let c = q.census(20); + assert_eq!((c[2], c[5]), (1, 1)); + assert_eq!(c[4], 15, "the oldest is slot 2's write, not slot 1's"); + for at in [0, 12, 20] { + assert_eq!(q.due_and_census(at).1, q.census(at)); + } + } + /// Slots held back for lack of room on the card are not handed out /// until their frame, keep their place, are not counted as waiting /// for their memory, and all come back at once when the card has room; diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index be73a6a..e4c456c 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -886,8 +886,9 @@ pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0); pub(crate) static HEAP_TEXTURES_TABLED: AtomicU64 = AtomicU64::new(0); /// The queue of textures picked by index at the last pass /// (`TextureQueue::census`): slots in it, due, waiting for their memory, -/// uploaded in part, and the frames the oldest due one has waited. -pub(crate) static HEAP_TEXTURES_QUEUE: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; +/// uploaded in part, the frames the oldest due one has waited, and those +/// uploaded whole that wait for a look again. +pub(crate) static HEAP_TEXTURES_QUEUE: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; /// Since the start: looks at a slot uploaded in part that found no more of /// its memory mapped; uploads of textures not all mapped; and of those, /// the ones whose first page was not there (asked by the first page alone, diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 98d76bb..90ccafb 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -8972,13 +8972,14 @@ impl Meter { ); crate::tiles::status(); { - let [queued, due, away, partly, oldest] = - [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); + let [queued, due, away, partly, oldest, again] = + [0, 1, 2, 3, 4, 5].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); let [same, parts, tails] = [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed)); tracing::info!( - "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \ - {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \ + "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest not uploaded yet written \ + {oldest} frames ago), {away} waiting for their memory, {partly} uploaded in part, {again} uploaded whole and \ + waiting to be looked at again; since the start: {} slots found uploaded already by \ the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \ as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \ {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \ @@ -9025,6 +9026,20 @@ impl Meter { crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20 ); } + let served = crate::descriptor::host::SERVED.each_ref().map(|n| n.swap(0, Ordering::Relaxed)); + if served[0] + served[3] > 0 { + tracing::info!( + "textures picked by index served for the first time in the last 5 seconds: {} at their first look, \ + {:.1} frames after they were due ({} at most: the pass's own lateness), {} after their memory was \ + found not there, {:.1} frames after their write ({} at most)", + served[0], + served[1] as f64 / served[0].max(1) as f64, + served[2], + served[3], + served[4] as f64 / served[3].max(1) as f64, + served[5] + ); + } if all > 0 || parts[7] > 0 { let [queue, records, prints, ahead, shown, whole, checks, before] = parts; let [n_frame, n_early, n_bake, t_frame, t_early, t_bake, at_time, at_bytes] = passes; From 6b3960daf276240f93e80eb296e886897da208a5 Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:06:49 +0530 Subject: [PATCH 4/4] Staged textures at title addresses: whether all is there, from the runtime's views The texture pass's question whether a staged texture's memory is all there is still put to Windows for textures made at an address the title mapped (the console's usual placed textures; a question per 256 pages). The runtime's views of physical pages answer it where they cover the memory, as they already answer `mapped_bytes` for placed views: one look, under a microsecond where Windows took 3 us (350 KB), 135 us (22 MB) and 647 us (22 MB, 1 MB there) (look_costs on this PC). Windows is asked only where no view lies. `VICTORY_MAPPED_BY_VIEWS=0` asks Windows, as for `mapped_bytes`; `VICTORY_STAGED_ASK_ALL=1` still asks Windows of every texture. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/texture.rs | 64 +++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 8 deletions(-) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index ef1831f..77e49d3 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -1750,18 +1750,41 @@ pub(crate) fn is_staged(resource: This) -> bool { /// milliseconds when the pages had left the working set, and each such page /// read back into it), for 66 found not all there in a whole run /// (coolfox-20261126-223059); the pass's unattributed time went with their -/// count, 13 us each. `VICTORY_STAGED_ASK_ALL=1`: asked of every texture, -/// as before. +/// count, 13 us each. Of one at a title address, the runtime's views of +/// physical pages answer where they cover the memory ([`all_there`]: one +/// look, under a microsecond), as they do for placed textures +/// ([`mapped_bytes`]). `VICTORY_STAGED_ASK_ALL=1`: Windows is asked of every +/// texture, as before. pub(crate) fn staged(resource: This, ask: bool) -> Option<(u64, bool)> { static ALL: std::sync::OnceLock = std::sync::OnceLock::new(); let s = { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref()?.get(&(resource as usize))?.clone() }; - let ask = ask - && (*ALL.get_or_init(|| std::env::var_os("VICTORY_STAGED_ASK_ALL").is_some_and(|v| v == "1")) - || crate::resource::at_title_address(resource)); - Some((s.read as u64, !ask || committed(s.memory, s.read))) + let whole = !ask + || if *ALL.get_or_init(|| std::env::var_os("VICTORY_STAGED_ASK_ALL").is_some_and(|v| v == "1")) { + committed(s.memory, s.read) + } else { + !crate::resource::at_title_address(resource) || all_there(s.memory, s.read) + }; + Some((s.read as u64, whole)) +} + +/// Whether all of `[at, at + len)` is mapped: by the runtime's views of +/// physical pages where any lies there (as [`mapped_bytes`] asks), else by +/// asking Windows ([`committed`]). +fn all_there(at: *const u8, len: usize) -> bool { + match by_views().then(|| crate::inplace::shown_bytes(at as usize, len)).flatten() { + Some(there) => there >= len as u64, + None => committed(at, len), + } +} + +/// Whether how much of title memory is mapped is asked of the runtime's +/// views of physical pages first (`VICTORY_MAPPED_BY_VIEWS=0`: of Windows). +fn by_views() -> bool { + static BY_VIEWS: std::sync::OnceLock = std::sync::OnceLock::new(); + *BY_VIEWS.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_VIEWS").is_none_or(|v| v != "0")) } /// Whether `[at, at + len)` is committed memory (streamed textures may be @@ -1875,8 +1898,7 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { // knows which are there: one look, where the host was asked for every // 64 KiB of the texture (and once more for each that is not there). // `VICTORY_MAPPED_BY_VIEWS=0`: the host is asked, as before. - static BY_VIEWS: std::sync::OnceLock = std::sync::OnceLock::new(); - if *BY_VIEWS.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_VIEWS").is_none_or(|v| v != "0")) + if by_views() && let Some(there) = crate::inplace::shown_bytes(start, len) { return there; @@ -2045,6 +2067,32 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O mod title_memory_tests { use super::with_title; + /// Whether memory is all there is answered by the runtime's views of + /// physical pages where they lie, and by Windows where none does. + #[test] + fn all_there_asks_the_views_where_they_lie() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree}; + const BLOCK: usize = 64 << 10; + // SAFETY: a reservation of our own, its first two blocks committed. + let at = unsafe { + let at = VirtualAlloc(std::ptr::null(), 4 * BLOCK, MEM_RESERVE, PAGE_READWRITE); + VirtualAlloc(at, 2 * BLOCK, MEM_COMMIT, PAGE_READWRITE); + at as usize + }; + let there = |len| super::all_there(at as *const u8, len); + assert!(there(2 * BLOCK)); + assert!(!there(3 * BLOCK)); + // The runtime's views of the first two blocks answer for them. + for block in 0..2 { + crate::title_memory_view(at + block * BLOCK, BLOCK, 9, 0); + } + assert!(there(2 * BLOCK)); + assert!(!there(3 * BLOCK)); + crate::inplace::views_gone(at, 4 * BLOCK); + // SAFETY: our reservation, released whole. + unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) }; + } + /// Title memory whose tail is reserved and not committed reads through /// the copy as its bytes and then zeros, without a fault; so does /// memory a page of which is taken away between two reads, and the