From 4cee21f397cde1449a43aa9190835c27faa626c0 Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:05:09 +0530 Subject: [PATCH 1/9] Texture queue's lock by place, the pass's shown, nothing and before parts (5-second lines) The split line of 7d8d56a found, per run of ~150 s, 3.8-5.2 s of the pass and 33-44 s of other threads waiting for the lock of the queue of textures picked by index, and 5.0-7.0 s in "slots shown after their upload, flipped or made at once" (coolfox-20261126-232343, -233017). Two more 5-second lines say where: - the queue's lock by place (`descriptor::queue_site`: the pass asking of or telling of a slot, taking the slots due, making slots due, noting a slot's record, table reads, stale views, else): the times it was taken, the waits, how long the places that hold it for many slots held it (the slots due, slots made due, stale views), and the times it was not taken (none yet); - the pass's parts: slots made at once, shown after their upload and flipped (time and count); the slots with nothing to bring up to date by why (views of textures the host writes, no texture, the host's own texture) and how many of them the pass made at once; the work before the loops (slots made due, views made again and flips, taking the slots due). A lock taken is counted by one relaxed add under it; hold times are timed only at the places that hold it for many slots. Nothing else changes. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 37 ++++++- crates/victory-gpu/src/descriptor/host.rs | 86 ++++++++++----- crates/victory-gpu/src/draw.rs | 125 ++++++++++++++++------ crates/victory-gpu/src/host.rs | 58 ++++++++++ 4 files changed, 245 insertions(+), 61 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index bd9f371..e0b190e 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -30,11 +30,44 @@ pub(crate) static LOCK_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std:: /// 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) { +pub(crate) fn waited(which: usize, started: std::time::Instant) -> u64 { 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); + let ns = started.elapsed().as_nanos() as u64; + LOCK_WAITS[2 * which + other].fetch_add(ns, std::sync::atomic::Ordering::Relaxed); + ns } +/// The places that take the lock of the queue of textures picked by index +/// (`host::TextureQueue`), counted apart in [`QUEUE_LOCK`]. +pub(crate) mod queue_site { + /// The pass asks what is known of a slot, or tells what came of it. + pub(crate) const TELL: usize = 0; + /// The pass takes the slots due and the queue's counts. + pub(crate) const DUE: usize = 1; + /// Slots made due by memory mapped, unmapped or written, by room on + /// the card again, by levels waiting for it. + pub(crate) const MADE_DUE: usize = 2; + /// A slot's record made, copied in or made by a draw or the pass: the + /// slot queued, kept, or taken out. + pub(crate) const WRITE: usize = 3; + /// A draw read the slot through a table: taken out. + pub(crate) const TABLE: usize = 4; + /// Slots made stale by a newer view of other memory: taken out. + pub(crate) const STALE: usize = 5; + /// Anything else (counts for the lines, the bakes' news). + pub(crate) const OTHER: usize = 6; + pub(crate) const COUNT: usize = 7; +} + +/// Since the last 5-second line, by [`queue_site`]: the times the texture +/// queue's lock was taken; the nanoseconds threads waited for it; the +/// nanoseconds it was held by the places that hold it for many slots at a +/// time (the slots due, slots made due, stale views); and the times it was +/// not taken because what was asked would have changed nothing +/// (`host::QueueMarks`). +pub(crate) static QUEUE_LOCK: [[std::sync::atomic::AtomicU64; queue_site::COUNT]; 4] = + [const { [const { std::sync::atomic::AtomicU64::new(0) }; queue_site::COUNT] }; 4]; + const HEAP_IIDS: [Iid; 4] = [ guid( 0x8efb471d, diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 456860a..fbb5e22 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1804,20 +1804,56 @@ fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { unsafe { host.device.CreateSampler(&desc, at) }; } +/// The queue of textures picked by index, locked by place `site` +/// (`super::queue_site`): for the places that hold it for many slots at a +/// time, how long it was held is counted when it is let go. +struct QueueGuard<'a> { + queue: std::sync::MutexGuard<'a, TextureQueue>, + held: Option<(usize, std::time::Instant)>, +} + +impl std::ops::Deref for QueueGuard<'_> { + type Target = TextureQueue; + fn deref(&self) -> &TextureQueue { + &self.queue + } +} + +impl std::ops::DerefMut for QueueGuard<'_> { + fn deref_mut(&mut self) -> &mut TextureQueue { + &mut self.queue + } +} + +impl Drop for QueueGuard<'_> { + fn drop(&mut self) { + if let Some((site, since)) = self.held { + super::QUEUE_LOCK[2][site].fetch_add(since.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed); + } + } +} + 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() { + /// The queue of textures picked by index, locked by place `site` + /// (`super::queue_site`); the lock taken, a wait for it, and how long + /// the places that hold it for many slots held it are counted + /// (`super::LOCK_WAITS`, `super::QUEUE_LOCK`). + fn queue(&self, site: usize) -> QueueGuard<'_> { + use super::queue_site::{DUE, MADE_DUE, STALE}; + use std::sync::atomic::Ordering::Relaxed; + let queue = 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); + super::QUEUE_LOCK[1][site].fetch_add(super::waited(0, started), Relaxed); queue } - } + }; + super::QUEUE_LOCK[0][site].fetch_add(1, Relaxed); + let held = matches!(site, DUE | MADE_DUE | STALE).then(|| (site, std::time::Instant::now())); + QueueGuard { queue, held } } /// `n` consecutive free dynamic slots (view heaps only), taken until @@ -1900,14 +1936,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; 6]) { - let (due, census) = self.queue().due_and_census(frame); + let (due, census) = self.queue(super::queue_site::DUE).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.queue().writes; + let writes = self.queue(super::queue_site::OTHER).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)) } @@ -1917,7 +1953,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.queue(); + let textures = self.queue(super::queue_site::OTHER); textures .slots .iter() @@ -1931,7 +1967,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.queue(); + let mut textures = self.queue(super::queue_site::TELL); textures.note_served(index, write, crate::frame::current()); match again { Some((frame, mapped)) => textures.partly(index, write, frame, mapped), @@ -1951,38 +1987,38 @@ impl HostHeap { looks: u8, uploaded: u64, ) { - let mut textures = self.queue(); + let mut textures = self.queue(super::queue_site::TELL); textures.note_served(index, write, crate::frame::current()); 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.queue().checked(index) + self.queue(super::queue_site::TELL).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.queue(); + let mut textures = self.queue(super::queue_site::TELL); textures.later(index, write, frame, most); } /// See [`TextureQueue::hold`]. pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) { - self.queue().hold(index, write, due); + self.queue(super::queue_site::TELL).hold(index, write, due); } /// See [`TextureQueue::room`]. pub(crate) fn texture_slots_room(&self, frame: u64) -> usize { - self.queue().room(frame) + self.queue(super::queue_site::MADE_DUE).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.queue().mapped(index) + self.queue(super::queue_site::TELL).mapped(index) } /// Takes the ranges of title memory the runtime mapped, unmapped or @@ -2010,7 +2046,7 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); - let mut textures = self.queue(); + let mut textures = self.queue(super::queue_site::MADE_DUE); for &slot in &slots { textures.changed(slot, frame, frame + 1); } @@ -2035,7 +2071,7 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); - let mut textures = self.queue(); + let mut textures = self.queue(super::queue_site::MADE_DUE); for &slot in &slots { textures.changed(slot, frame, frame + 1); } @@ -2095,7 +2131,7 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); - let mut textures = self.queue(); + let mut textures = self.queue(super::queue_site::MADE_DUE); 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); @@ -2116,7 +2152,7 @@ impl HostHeap { slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); let held = slots.len(); - let mut textures = self.queue(); + let mut textures = self.queue(super::queue_site::MADE_DUE); // 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)); @@ -2206,7 +2242,7 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); - let mut textures = self.queue(); + let mut textures = self.queue(super::queue_site::MADE_DUE); for &slot in &slots { textures.changed(slot, frame, frame + 1); } @@ -2701,7 +2737,7 @@ impl HostHeap { if old != now | TABLED_READ { stamp.store(now | TABLED_READ, Relaxed); if tabled_out() { - let mut textures = self.queue(); + let mut textures = self.queue(super::queue_site::TABLE); if textures.slots.remove(&index).is_some() { TABLED_WRITES[1].fetch_add(1, Relaxed); } @@ -2737,7 +2773,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.queue(); + let mut textures = self.queue(super::queue_site::WRITE); if texture && !read_now { let due = if lately && !seen { TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -2846,7 +2882,7 @@ impl HostHeap { }; if !stale.is_empty() { STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed); - let mut textures = self.queue(); + let mut textures = self.queue(super::queue_site::STALE); for &(slot, _) in &stale { textures.remove(slot); } @@ -3474,7 +3510,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.queue(); + let textures = self.queue(super::queue_site::OTHER); 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 e4c456c..821c6a7 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -968,6 +968,52 @@ fn outcome(which: usize) { HEAP_TEXTURE_SLOTS[which].fetch_add(1, Ordering::Relaxed); } +/// Of [`HEAP_TEXTURE_REST`]' place 4 (slots shown after their upload, +/// flipped or made at once), since the last 5-second line: nanoseconds and +/// calls of slots made at once (`HostHeap::mirror` by the pass), of slots +/// shown after their upload (`texture_slot_show_after`), and of slots +/// flipped (`texture_slot_flip`, or made at once as they show an earlier +/// view of the same texture): [ns made, ns after, ns flipped, made, after, +/// flipped]. +pub(crate) static HEAP_TEXTURE_SHOWN: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + +/// `f`'s result, its time added to [`HEAP_TEXTURE_REST`]' place 4 and to +/// [`HEAP_TEXTURE_SHOWN`]' place `which`. +fn shown(which: usize, f: impl FnOnce() -> T) -> T { + let started = std::time::Instant::now(); + let out = f(); + let ns = started.elapsed().as_nanos() as u64; + HEAP_TEXTURE_REST[4].fetch_add(ns, Ordering::Relaxed); + HEAP_TEXTURE_SHOWN[which].fetch_add(ns, Ordering::Relaxed); + HEAP_TEXTURE_SHOWN[3 + which].fetch_add(1, Ordering::Relaxed); + out +} + +/// Of the slots the pass found nothing to bring up to date for +/// ([`slot_outcome::NOTHING`]), since the last 5-second line: views of a +/// texture object the host renders to or writes (the queue held them for +/// nothing: a host texture is never uploaded); slots with no texture view +/// or no texture the host can make; slots whose host texture is the host's +/// own (a target, depth or unordered access texture placed in title +/// memory); and of all these, the ones the pass made at once. +pub(crate) static HEAP_TEXTURE_NOTHING: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// Of [`HEAP_TEXTURE_REST`]' place 7 (the passes' work before their loops), +/// since the last 5-second line, in nanoseconds: slots made due (room on the +/// card again, memory mapped, unmapped or written, levels waiting); views +/// made again and slots flipped after earlier uploads; the slots due taken +/// from the queue and ordered. (The rest of it: budgets, counts, the card +/// accounting line.) +pub(crate) static HEAP_TEXTURE_BEFORE: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// `f`'s result, its time added to [`HEAP_TEXTURE_BEFORE`]' place `slot`. +fn before(slot: usize, f: impl FnOnce() -> T) -> T { + let started = std::time::Instant::now(); + let out = f(); + HEAP_TEXTURE_BEFORE[slot].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + out +} + /// 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 @@ -2983,40 +3029,46 @@ impl State { once!("textures picked by index: the card has no room for more; they wait"); } let mut refused = 0; - // Room again: the slots held back while the card was full are due - // now (`full_card_pass`). - if room { - host.texture_slots_room(frame); - } - // Slots whose texture's memory the runtime mapped, unmapped or - // wrote since the last pass are due again. - host.texture_slots_remapped(frame); let baking = crate::texture::BAKING.get(); - if baking { - host.texture_slots_bake_written(frame); - } - host.texture_slots_short(frame); - // The slots of textures whose first level with memory (levels on - // demand), or whose host copy for one with more levels, changed since - // the last pass are made again from it; those whose new view's upload - // has run are made from that. - host.texture_views_remade(); - host.texture_slots_flip(); + before(0, || { + // Room again: the slots held back while the card was full are + // due now (`full_card_pass`). + if room { + host.texture_slots_room(frame); + } + // Slots whose texture's memory the runtime mapped, unmapped or + // wrote since the last pass are due again. + host.texture_slots_remapped(frame); + if baking { + host.texture_slots_bake_written(frame); + } + host.texture_slots_short(frame); + }); + before(1, || { + // The slots of textures whose first level with memory (levels + // on demand), or whose host copy for one with more levels, + // changed since the last pass are made again from it; those + // whose new view's upload has run are made from that. + host.texture_views_remade(); + host.texture_slots_flip(); + }); // And with room, the textures whose upload left a held level // without the card's memory are uploaded again. if room { - host.texture_slots_waiting(frame); + before(0, || host.texture_slots_waiting(frame)); } let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake); - let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 }); + let (mut due, census) = before(2, || host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 })); // (Those that are due later after all that are due.) let on_time = due.len(); if baking { - let known: std::collections::HashSet = due.iter().map(|&(index, _)| index).collect(); - 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))); + before(2, || { + let known: std::collections::HashSet = due.iter().map(|&(index, _)| index).collect(); + 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); for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { @@ -3211,6 +3263,7 @@ impl State { && !crate::resource::title_fills(object as This) { outcome(slot_outcome::NOTHING); + HEAP_TEXTURE_NOTHING[0].fetch_add(1, Ordering::Relaxed); rest(0, || host.texture_slot_done(index, write, None)); continue; } @@ -3290,9 +3343,11 @@ impl State { (view, None) } }); - let at_once = || { + // (`nothing`: the slot has nothing to bring up to date.) + let at_once = |nothing: bool| { if (late || bake_key.is_some()) && let Some(handle) = heap.handle(index) { - rest(4, || { + HEAP_TEXTURE_NOTHING[3].fetch_add(u64::from(nothing), Ordering::Relaxed); + shown(0, || { let _ = host.mirror(index, handle, true); }); } @@ -3305,8 +3360,9 @@ impl State { let resource = match placed.as_ref().or(view.as_ref()) { Some(&View::Shader(resource, _)) => resource as This, _ => { - at_once(); + at_once(true); outcome(slot_outcome::NOTHING); + HEAP_TEXTURE_NOTHING[1].fetch_add(1, Ordering::Relaxed); rest(0, || host.texture_slot_done(index, write, None)); continue; } @@ -3318,9 +3374,10 @@ impl State { } let title_fills = rest(6, || texture.is_some_and(crate::texture::title_written)); if !title_fills { - at_once(); + at_once(true); // a render target, a depth or unordered access texture: the host's own outcome(slot_outcome::NOTHING); + HEAP_TEXTURE_NOTHING[2].fetch_add(1, Ordering::Relaxed); rest(0, || host.texture_slot_done(index, write, None)); continue; } @@ -3344,17 +3401,17 @@ impl State { sync.publish.push((index, handle, key)); } else { if shows_other && let Some(handle) = heap.handle(index) { - rest(4, || { + shown(2, || { 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) { - rest(4, || host.texture_slot_show_after(list, index, handle)); + shown(1, || host.texture_slot_show_after(list, index, handle)); } } else { - at_once(); + at_once(false); } } let again = partly.map(|mapped| (frame + 1, mapped)); @@ -3422,10 +3479,10 @@ impl State { sync.publish.push((index, handle, key)); } if shows_other && let Some(handle) = heap.handle(index) { - rest(4, || host.texture_slot_flip(list, index, handle)); + shown(2, || host.texture_slot_flip(list, index, handle)); } if late && let Some(handle) = heap.handle(index) { - rest(4, || host.texture_slot_show_after(list, index, handle)); + shown(1, || host.texture_slot_show_after(list, index, handle)); } #[cfg(feature = "diagnostics")] if crate::book::on() diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 1140960..4e4acef 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -9170,6 +9170,64 @@ impl Meter { slots[9], ); } + let shown = crate::draw::HEAP_TEXTURE_SHOWN.each_ref().map(|n| n.swap(0, Ordering::Relaxed)); + let nothing = crate::draw::HEAP_TEXTURE_NOTHING.each_ref().map(|n| n.swap(0, Ordering::Relaxed)); + let ahead_of = crate::draw::HEAP_TEXTURE_BEFORE.each_ref().map(|n| n.swap(0, Ordering::Relaxed) / 1_000_000); + if all > 0 || parts[7] > 0 { + let [made_ns, after_ns, flipped_ns, made, after, flipped] = shown; + let [due_by_memory, remade, due_list] = ahead_of; + tracing::info!( + "the pass over textures picked by index, its parts in the last 5 seconds: slots shown: {} ms made at \ + once ({made}), {} ms shown after their upload ({after}), {} ms flipped ({flipped}); nothing to bring \ + up to date: {} views of textures the host writes, {} without a texture, {} the host's own texture, {} of \ + them made at once; before the loops: {due_by_memory} ms making slots due, {remade} ms views made again \ + and slots flipped, {due_list} ms taking the slots due, {} ms the rest", + made_ns / 1_000_000, + after_ns / 1_000_000, + flipped_ns / 1_000_000, + nothing[0], + nothing[1], + nothing[2], + nothing[3], + parts[7].saturating_sub(due_by_memory + remade + due_list), + ); + } + // The queue's lock by place (`crate::descriptor::queue_site`). + let lock = crate::descriptor::QUEUE_LOCK.each_ref().map(|row| row.each_ref().map(|n| n.swap(0, Ordering::Relaxed))); + let [taken, waited, held, skipped] = lock; + if taken.iter().sum::() + skipped.iter().sum::() > 0 { + let ms = |ns: u64| ns / 1_000_000; + tracing::info!( + "the texture queue's lock in the last 5 seconds: taken {} times ({} by the pass asking of or telling of a \ + slot, {} taking the slots due, {} making slots due, {} noting a slot's record, {} by table reads, {} for \ + stale views, {} else); waited for {} ms ({}, {}, {}, {}, {}, {}, {} ms by the same places); held {} ms \ + taking the slots due, {} ms making slots due, {} ms for stale views; not taken {} times, as nothing would \ + have changed ({} noting a slot's record, {} by table reads, {} for stale views)", + taken.iter().sum::(), + taken[0], + taken[1], + taken[2], + taken[3], + taken[4], + taken[5], + taken[6], + ms(waited.iter().sum::()), + ms(waited[0]), + ms(waited[1]), + ms(waited[2]), + ms(waited[3]), + ms(waited[4]), + ms(waited[5]), + ms(waited[6]), + ms(held[1]), + ms(held[2]), + ms(held[5]), + skipped.iter().sum::(), + skipped[3], + skipped[4], + skipped[5], + ); + } } if crate::resource::held_only() { let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed)); From 2ad55e65b3832063d524394755310af761ffe1a3 Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:07:27 +0530 Subject: [PATCH 2/9] Texture queue: notes that change nothing leave its lock alone (marks of what it holds) Every slot record a recording thread, the heaps' records thread or a draw makes is noted in the queue of textures picked by index under its one lock (`HostHeap::queue_texture`), and so is every first table read of a slot in a frame (`tabled_in`) and every slot a newer view makes stale. Most of these change nothing: a buffer view, a sampler or a null taken out of a queue that does not hold the slot; a slot a draw or the pass made from the record the queue holds already (`seen`, kept as it is); a table read of a slot not queued. Other threads waited 33-44 s for the lock in a run of 150 s (coolfox-20261126-232343, -233017), up to 3.3 s in 5 s of a cutscene. The queue now marks, per title slot, the write of the entry it holds (0: none; `QueueMarks`, set by the queue itself under its lock). These three places read the mark first and do not take the lock when it says nothing would change. Behaviour-neutral: a mark read while the queue changes it says what the queue held just before or just after, as if the lock had been taken a moment earlier or later, which any of these threads may always do; writes (not `seen`) always take the lock. Counted as "not taken" by place in the lock line (18ff932). On by default; `VICTORY_QUEUE_MARKS=0` takes the lock every time, as before (for comparing). Tests: the queue marks what it holds through writes, makes, looks, uploads in part, memory made due and removals; notes that change nothing leave the queue (and its marks) as they were. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 209 ++++++++++++++++++++-- 1 file changed, 199 insertions(+), 10 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index fbb5e22..edc167f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -194,6 +194,8 @@ pub(crate) struct HostHeap { /// table; one a shader picks by a computed index is brought up to date /// from here ([`HostHeap::texture_slots_due`]). textures: Mutex, + /// What `textures` holds, read without its lock ([`QueueMarks`]). + marks: std::sync::Arc, /// Per title slot, the frame (plus one; 0: never) in which a draw last /// read it through a table, or made a table it lies in (with /// [`TABLED_READ`] set if the draw read it). The draw that @@ -943,6 +945,73 @@ struct Waiting { checked: (u64, u64, u64, u8, u64), } +/// Which title slots the queue of textures picked by index holds, readable +/// without its lock: for each slot the write number of its entry (0: none). +/// Changed only by the queue itself, under its lock; read without it by the +/// places that would change nothing if they took it: a slot's record noted +/// that takes out a slot the queue does not hold, or keeps one it holds +/// (`seen`); a table read or a stale view that takes out a slot it does not +/// hold. Whoever reads a mark while the queue changes it sees the slot as +/// it was just before or just after: as if it had taken the lock a moment +/// earlier or later, which it may always have done. +/// +/// The recording threads, the heaps' records thread and the draws note +/// every slot record they make here: the line split by place (18ff932) says +/// how many of the lock's takings changed nothing, and how long everyone +/// waited for it (33-44 s of other threads in a run of 150 s before, against +/// 3.8-5.2 s of the pass: coolfox-20261126-232343, -233017). +/// `VICTORY_QUEUE_MARKS=0`: the lock is taken every time, as before. +#[derive(Default)] +pub(crate) struct QueueMarks(Box<[std::sync::atomic::AtomicU64]>); + +impl QueueMarks { + fn new(count: usize) -> Self { + QueueMarks((0..count).map(|_| std::sync::atomic::AtomicU64::new(0)).collect()) + } + + /// Under the queue's lock: slot `index` holds the entry of write + /// `write` (0: none). + fn set(&self, index: u32, write: u64) { + if let Some(mark) = self.0.get(index as usize) { + mark.store(write, std::sync::atomic::Ordering::Release); + } + } + + /// The write of slot `index`'s entry (0: none); `None`: not known here + /// (past the marks), the queue knows. + fn get(&self, index: u32) -> Option { + Some(self.0.get(index as usize)?.load(std::sync::atomic::Ordering::Acquire)) + } +} + +/// Whether the queue's marks ([`QueueMarks`]) spare its lock +/// (`VICTORY_QUEUE_MARKS=0`: not). +fn queue_marks() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE_MARKS").is_none_or(|v| v != "0")) +} + +/// The queue's lock was not taken at place `site` (`super::queue_site`), as +/// nothing would have changed: counted in `super::QUEUE_LOCK`, by the +/// thread in batches (these happen hundreds of thousands of times in five +/// seconds, on many threads at once). +fn not_taken(site: usize) { + use super::queue_site::COUNT; + const BATCH: u32 = 64; + thread_local! { + static NOT_TAKEN: std::cell::Cell<[u32; COUNT]> = const { std::cell::Cell::new([0; COUNT]) }; + } + NOT_TAKEN.with(|n| { + let mut counts = n.get(); + counts[site] += 1; + if counts[site] >= BATCH { + super::QUEUE_LOCK[3][site].fetch_add(u64::from(counts[site]), std::sync::atomic::Ordering::Relaxed); + counts[site] = 0; + } + n.set(counts); + }); +} + /// The queue of title slots whose texture view waits to be brought up to /// date for shaders that pick textures by index: which are due, and in /// which order (no host heap needed, so it is tested without one). @@ -954,9 +1023,32 @@ pub(crate) struct TextureQueue { /// they need ([`TextureQueue::hold`]), each with the write it was /// held as. held: std::collections::BTreeMap, + /// What `slots` holds, for reading without the lock (the host heap + /// keeps the same; none in tests made without a heap). + marks: std::sync::Arc, } impl TextureQueue { + /// An empty queue whose marks are `marks`. + fn with_marks(marks: std::sync::Arc) -> Self { + TextureQueue { marks, ..Default::default() } + } + + /// Slot `index` holds `waiting` now. + fn put(&mut self, index: u32, waiting: Waiting) { + self.marks.set(index, waiting.write); + self.slots.insert(index, waiting); + } + + /// Slot `index` leaves the queue; whether it was there. + fn take_out(&mut self, index: u32) -> bool { + let was = self.slots.remove(&index).is_some(); + if was { + self.marks.set(index, 0); + } + was + } + /// A texture view was written into slot `index` in `frame`, due from /// frame `due`. `seen`: it was not written, a draw or the pass made /// the host slot from a view the queue may hold already, which then @@ -967,11 +1059,11 @@ impl TextureQueue { } self.writes += 1; let write = self.writes; - self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); + self.put(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); } fn remove(&mut self, index: u32) { - self.slots.remove(&index); + self.take_out(index); } /// Up to `max` slots due at `frame`, each with its write number, in @@ -1063,7 +1155,7 @@ impl TextureQueue { /// Slot `index` is up to date: out of the queue until written again. fn done(&mut self, index: u32, write: u64) { if self.same(index, write).is_some() { - self.slots.remove(&index); + self.take_out(index); } } @@ -1141,7 +1233,7 @@ impl TextureQueue { self.writes += 1; let write = self.writes; let due = self.slots.get(&index).map_or(due, |w| w.due.min(due)); - self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); + self.put(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); } /// Bytes of slot `index`'s memory that were mapped at its last upload @@ -1679,6 +1771,7 @@ impl HostHeap { Some((buffer, gpu, data as usize)) }) .flatten(); + let marks = std::sync::Arc::new(QueueMarks::new(if sampler { 0 } else { count as usize })); let h = HostHeap { buffer_sweep: Mutex::default(), buffer_frame: std::sync::atomic::AtomicU64::new(u64::MAX), @@ -1706,7 +1799,8 @@ impl HostHeap { strides, buffers: Slots::new(count as usize), changed: Slots::new(count as usize), - textures: Mutex::default(), + textures: Mutex::new(TextureQueue::with_marks(marks.clone())), + marks, tabled: (0..if sampler { 0 } else { count }) .map(|_| std::sync::atomic::AtomicU32::new(0)) .collect(), @@ -1856,6 +1950,16 @@ impl HostHeap { QueueGuard { queue, held } } + /// Whether the queue holds title slot `index`, by its marks + /// ([`QueueMarks`]), without its lock; `None`: ask the queue (the marks + /// are not used, or do not reach the slot). + fn queued(&self, index: u32) -> Option { + if !queue_marks() { + return None; + } + self.marks.get(index).map(|write| write != 0) + } + /// `n` consecutive free dynamic slots (view heaps only), taken until /// [`HostHeap::release`]: the first's index. pub(crate) fn dynamic(&self, n: u32) -> Option { @@ -2737,8 +2841,13 @@ impl HostHeap { if old != now | TABLED_READ { stamp.store(now | TABLED_READ, Relaxed); if tabled_out() { + // Not in the queue: nothing to take out. + if self.queued(index) == Some(false) { + not_taken(super::queue_site::TABLE); + return; + } let mut textures = self.queue(super::queue_site::TABLE); - if textures.slots.remove(&index).is_some() { + if textures.take_out(index) { TABLED_WRITES[1].fetch_add(1, Relaxed); } } @@ -2773,8 +2882,22 @@ 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 keeps = texture && !read_now; + // Nothing changes when a slot made (not written) is one the queue + // holds: it stays as it is (`TextureQueue::written`); or when the + // slot is to leave a queue that does not hold it. (A write always + // changes the queue.) + let unchanged_if_queued = match (keeps, seen) { + (true, true) => Some(true), + (true, false) => None, + (false, _) => Some(false), + }; + if unchanged_if_queued.is_some() && self.queued(index) == unchanged_if_queued { + not_taken(super::queue_site::WRITE); + return; + } let mut textures = self.queue(super::queue_site::WRITE); - if texture && !read_now { + if keeps { let due = if lately && !seen { TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); frame + TABLED_GRACE @@ -2882,9 +3005,15 @@ impl HostHeap { }; if !stale.is_empty() { STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed); - let mut textures = self.queue(super::queue_site::STALE); - for &(slot, _) in &stale { - textures.remove(slot); + // Only the ones the queue may hold. + let queued: Vec = stale.iter().map(|&(slot, _)| slot).filter(|&slot| self.queued(slot) != Some(false)).collect(); + if queued.is_empty() { + not_taken(super::queue_site::STALE); + } else { + let mut textures = self.queue(super::queue_site::STALE); + for slot in queued { + textures.remove(slot); + } } } let (stride, kind) = view.map_or((None, 0), view_stride_and_kind); @@ -5833,6 +5962,66 @@ mod tests { // Long after the last table, a write is due at once. heap.queue_texture(2, true, false, frame + 3 + TABLED_FRAMES); assert_eq!(slots(frame + 3 + TABLED_FRAMES), [2]); + // Notes that change nothing (taken out of a queue that does not + // hold the slot, made as the queue holds it) leave it as it is, + // and its marks say what it holds. + let marks = |heap: &HostHeap| (0..8).map(|i| heap.queued(i)).collect::>(); + let held = |queued: &[u32]| (0..8).map(|i| queue_marks().then_some(queued.contains(&i))).collect::>(); + assert_eq!(marks(&heap), held(&[2])); + heap.queue_texture(5, false, false, frame + 4 + TABLED_FRAMES); + heap.queue_texture(2, true, true, frame + 4 + TABLED_FRAMES); + heap.tabled_in(6, true, frame + 4 + TABLED_FRAMES); + assert_eq!(slots(u64::MAX), [2]); + assert_eq!(marks(&heap), held(&[2])); + heap.queue_texture(2, false, false, frame + 5 + TABLED_FRAMES); + assert_eq!(slots(u64::MAX), []); + assert_eq!(marks(&heap), held(&[])); + } + + /// The queue's marks say which slots it holds, by the write of each + /// entry: set by writes and memory made due, kept by looks, uploads in + /// part and makes of a slot it holds, cleared when the slot leaves. + #[test] + fn the_texture_queue_marks_what_it_holds() { + let marks = std::sync::Arc::new(QueueMarks::new(32)); + let mut q = TextureQueue::with_marks(marks.clone()); + let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1; + q.written(1, 1, 0, false); + q.written(2, 1, 0, false); + let w1 = write(&q, 1); + assert_eq!(marks.get(1), Some(w1)); + // Made as it is held: the entry and its mark stay. + q.written(1, 2, 0, true); + assert_eq!(marks.get(1), Some(w1)); + q.done(1, w1); + assert_eq!(marks.get(1), Some(0)); + // Written again; a done of the old write changes nothing. + q.written(1, 3, 0, false); + let w1b = write(&q, 1); + q.done(1, w1); + assert_eq!(marks.get(1), Some(w1b)); + // Made due by memory: the new write is marked. + q.changed(1, 4, 5); + assert_eq!(marks.get(1), Some(write(&q, 1))); + assert_ne!(marks.get(1), Some(w1b)); + // Looks, uploads in part and looks again keep entry and mark. + let w2 = write(&q, 2); + q.later(2, w2, 4, 4); + q.partly(2, w2, 6, 4096); + q.recheck(2, w2, 8, (0x1000, 4096), 7, 0, 6); + q.hold(2, w2, 9); + assert_eq!(marks.get(2), Some(w2)); + q.remove(2); + assert_eq!(marks.get(2), Some(0)); + assert!(q.take_out(1)); + assert!(!q.take_out(1)); + assert_eq!(marks.get(1), Some(0)); + // Past the marks: not known. + assert_eq!(marks.get(32), None); + // A queue made without marks works as one with them. + let mut plain = TextureQueue::default(); + plain.written(40, 1, 0, false); + assert!(plain.take_out(40)); } #[test] From abf1020d25e46da6974f173bff08c89c990cfc49 Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:11:34 +0530 Subject: [PATCH 3/9] Texture pass: tells the queue a batch at a time, takes what it knows of a slot with the slots due The pass over textures picked by index took the queue's lock once or twice for every slot it took: to ask what is known of the slot (a texture uploaded whole, waiting for a look again) and to tell what came of it. In 5 s of a cutscene it took 90,000-250,000 slots, and its "telling the queue" was 143-400 ms, about all of it waiting for the lock (152-355 ms by the pass; coolfox-20261126-233017 18:02:18-18:02:23). - What it found of a slot (done, uploaded in part, uploaded whole and looked at again, nothing to upload now, held for room) is told 16 slots at a time under one take of the lock (`HostHeap::texture_slots_told`), the rest when the pass ends, on every way out. A slot's entry is told of a few slots' work later, as it would be if the pass's thread were held up for that long; what is told of a write the queue no longer holds is dropped as before (`TextureQueue::same`). - What the queue knows of a slot waiting for a look again is read while the slots due are taken, in the same take of the lock (`HostHeap::texture_slots_due_known`), and used if the queue's marks (b5b7806) say it still holds the write handed out; else it is asked as before. Behaviour-neutral: the queue ends as it would with each slot told at its turn (test), only some microseconds later. On by default; `VICTORY_QUEUE_BATCH=0` tells and asks each slot at its turn, as before. The lock line (18ff932) counts the lock taken by the pass apart. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 173 ++++++++++++++++++++-- crates/victory-gpu/src/draw.rs | 136 +++++++++++++---- 2 files changed, 268 insertions(+), 41 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index edc167f..bc04362 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1106,32 +1106,65 @@ impl TextureQueue { 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)); + if w.looks > 0 || w.mapped > 0 { + // (Only these can wait for a look again: `recheck` + // leaves a look, `partly` some bytes mapped.) + due.again.push((w.written, index, w.write, Some(w.checked).filter(|c| c.2 != 0))); + } else { + due.fresh.push((w.written, index, w.write)); + } } } (due, c) } } +/// What [`TextureQueue::recheck`] noted of a slot uploaded whole: where its +/// memory is (address, bytes), its fingerprint, the looks that found it +/// unchanged, the frame of the upload. +pub(crate) type Checked = (u64, u64, u64, u8, u64); + +/// What the pass over textures picked by index found of a slot it took, as +/// told to the queue ([`HostHeap::texture_slots_told`]). +#[derive(Clone, Copy, Debug)] +pub(crate) enum Told { + /// Up to date ([`HostHeap::texture_slot_done`]): due again from frame + /// `.0` with `.1` bytes of its memory there, or not until written. + Done(Option<(u64, u64)>), + /// Uploaded whole, looked at again ([`HostHeap::texture_slot_recheck`]): + /// from frame, memory (address, bytes), fingerprint, looks, upload frame. + Recheck(u64, (u64, u64), u64, u8, u64), + /// Nothing to upload now ([`HostHeap::texture_slot_later`]): frame, most. + Later(u64, u64), + /// No room on the card ([`HostHeap::texture_slot_held`]): until frame. + Held(u64), +} + /// The slots due, taken from the queue ([`TextureQueue::due_and_census`]): -/// (frame written, slot, write number) of those looked at before and of the -/// others. +/// (frame written, slot, write number) of those looked at before, with what +/// [`TextureQueue::checked`] says of them, and of the others. #[derive(Default)] struct Due { - again: Vec<(u64, u32, u64)>, + again: Vec<(u64, u32, u64, Option)>, fresh: Vec<(u64, u32, u64)>, } impl Due { /// Up to `max` of them, in the order [`TextureQueue::due`] serves them. + #[cfg(test)] fn order(self, max: usize) -> Vec<(u32, u64)> { + self.ordered(max).0 + } + + /// [`Due::order`], and beside it what [`TextureQueue::checked`] said of + /// each when they were taken. + fn ordered(self, max: usize) -> (Vec<(u32, u64)>, Vec>) { let Due { mut again, mut fresh } = self; // By the number of the write, counted over the run. - let newest_first = |a: &(u64, u32, u64), b: &(u64, u32, u64)| b.2.cmp(&a.2); - again.sort_unstable_by(newest_first); - fresh.sort_unstable_by(newest_first); - let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write)| (index, write)).collect(); + again.sort_unstable_by(|a, b| b.2.cmp(&a.2)); + fresh.sort_unstable_by(|a, b| b.2.cmp(&a.2)); + let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write, _)| (index, write)).collect(); + let mut known: Vec> = again.iter().map(|a| a.3).collect(); let (mut new, mut old) = (0, fresh.len()); while new < old && order.len() < max { order.push((fresh[new].1, fresh[new].2)); @@ -1142,7 +1175,8 @@ impl Due { } } order.truncate(max); - order + known.resize(order.len(), None); + (order, known) } } @@ -2039,11 +2073,61 @@ impl HostHeap { /// with its write number, in the order to serve them /// ([`TextureQueue::due`]), and the queue's counts /// ([`TextureQueue::census`]). + #[cfg(test)] pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 6]) { let (due, census) = self.queue(super::queue_site::DUE).due_and_census(frame); (if max == 0 { Vec::new() } else { due.order(max) }, census) } + /// Up to `max` title slots whose texture view is due at `frame`, each + /// with its write number, in the order to serve them + /// ([`TextureQueue::due`]); beside each slot what + /// [`TextureQueue::checked`] said of it then, read in the same take of + /// the lock (the pass asked it slot by slot, under the lock each time); + /// and the queue's counts ([`TextureQueue::census`]). + pub(crate) fn texture_slots_due_known(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, Vec>, [u64; 6]) { + let (due, census) = self.queue(super::queue_site::DUE).due_and_census(frame); + let (order, known) = if max == 0 { (Vec::new(), Vec::new()) } else { due.ordered(max) }; + (order, known, census) + } + + /// The write of the entry the queue holds for title slot `index`, by its + /// marks (0: none; [`QueueMarks`]); `None`: not known so (ask the queue). + pub(crate) fn texture_slot_write(&self, index: u32) -> Option { + if !queue_marks() { + return None; + } + self.marks.get(index) + } + + /// What the pass found of slots it took, each with the write it was + /// handed and the frame it was found in, told under one take of the + /// lock, as [`HostHeap::texture_slot_done`], `_recheck`, `_later` and + /// `_held` tell it one at a time. Leaves `told` empty. + pub(crate) fn texture_slots_told(&self, told: &mut Vec<(u32, u64, u64, Told)>) { + if told.is_empty() { + return; + } + let mut textures = self.queue(super::queue_site::TELL); + for (index, write, frame, what) in told.drain(..) { + match what { + Told::Done(again) => { + textures.note_served(index, write, frame); + match again { + Some((due, mapped)) => textures.partly(index, write, due, mapped), + None => textures.done(index, write), + } + } + Told::Recheck(due, at, print, looks, uploaded) => { + textures.note_served(index, write, frame); + textures.recheck(index, write, due, at, print, looks, uploaded); + } + Told::Later(at, most) => textures.later(index, write, at, most), + Told::Held(due) => textures.hold(index, write, due), + } + } + } + /// 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) { @@ -5978,6 +6062,75 @@ mod tests { assert_eq!(marks(&heap), held(&[])); } + /// The slots due come in their order with what the queue knew of each + /// (a slot uploaded whole and waiting for a look again), as asked slot + /// by slot. + #[test] + fn the_slots_due_come_with_what_is_known_of_them() { + let mut q = TextureQueue::default(); + for i in 0..4u32 { + q.written(30 + i, 1, 0, false); + } + let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1; + let w31 = write(&q, 31); + q.recheck(31, w31, 5, (0x2000, 4096), 9, 0, 2); + let w32 = write(&q, 32); + q.later(32, w32, 2, 4); + let (order, known) = q.due_and_census(u64::MAX).0.ordered(100); + assert_eq!(order, q.due(u64::MAX, 100)); + assert_eq!(known.len(), order.len()); + for (&(index, _), knew) in order.iter().zip(&known) { + assert_eq!(*knew, q.checked(index)); + } + assert_eq!(known.iter().filter(|k| k.is_some()).count(), 1); + let (order, known) = q.due_and_census(u64::MAX).0.ordered(1); + assert_eq!((order.len(), known.len()), (1, 1)); + } + + /// What the pass tells of several slots under one take of the lock ends + /// as told slot by slot. + #[test] + fn slots_told_together_end_as_told_one_at_a_time() { + let (Some(a), Some(b)) = (HostHeap::new(false, 8), HostHeap::new(false, 8)) else { + return; // no host GPU + }; + for heap in [&a, &b] { + for i in 0..6 { + heap.queue_texture(i, true, false, 10); + } + } + let due = |heap: &HostHeap, at: u64| heap.texture_slots_due(at, 8).0; + let handed = due(&a, u64::MAX); + assert_eq!(handed, due(&b, u64::MAX)); + let w = |i: u32| handed.iter().find(|d| d.0 == i).unwrap().1; + let what = [ + (0, Told::Done(None)), + (1, Told::Done(Some((12, 4096)))), + (2, Told::Recheck(14, (0x1000, 64), 7, 0, 10)), + (3, Told::Later(10, 4)), + (4, Told::Held(30)), + // A write the queue does not hold any more: dropped. + (5, Told::Done(None)), + ]; + let mut told: Vec<_> = what.iter().map(|&(i, t)| (i, if i == 5 { 0 } else { w(i) }, 10, t)).collect(); + a.texture_slots_told(&mut told); + assert!(told.is_empty()); + b.texture_slot_done(0, w(0), None); + b.texture_slot_done(1, w(1), Some((12, 4096))); + b.texture_slot_recheck(2, w(2), 14, (0x1000, 64), 7, 0, 10); + b.texture_slot_later(3, w(3), 10, 4); + b.texture_slot_held(4, w(4), 30); + b.texture_slot_done(5, 0, None); + for at in [10, 11, 12, 14, 30, u64::MAX] { + assert_eq!(due(&a, at), due(&b, at), "due at {at}"); + } + for i in 0..6 { + assert_eq!(a.texture_slot_checked(i), b.texture_slot_checked(i)); + assert_eq!(a.texture_slot_mapped(i), b.texture_slot_mapped(i)); + assert_eq!(a.texture_slot_write(i).map(|w| w != 0), b.texture_slot_write(i).map(|w| w != 0)); + } + } + /// The queue's marks say which slots it holds, by the write of each /// entry: set by writes and memory made due, kept by looks, uploads in /// part and makes of a slot it holds, cleared when the slot leaves. diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 821c6a7..4f6ac35 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -968,6 +968,70 @@ fn outcome(which: usize) { HEAP_TEXTURE_SLOTS[which].fetch_add(1, Ordering::Relaxed); } +/// Whether the pass over textures picked by index tells the queue what came +/// of its slots a batch at a time ([`Tells`]), and takes what the queue +/// knows of a slot looked at again with the slots due +/// (`HostHeap::texture_slots_due_known`; `VICTORY_QUEUE_BATCH=0`: each told +/// and asked at its turn, a take of the queue's lock each, as before). +fn queue_batch() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE_BATCH").is_none_or(|v| v != "0")) +} + +/// What the pass over textures picked by index found of its slots, told to +/// the queue [`Tells::BATCH`] slots at a time and when the pass ends +/// (`HostHeap::texture_slots_told`): a take of the queue's lock for a batch, +/// where each slot took it once or twice (90,000-250,000 slots in 5 s of a +/// cutscene, coolfox-20261126-233017, while the recording threads took it for +/// every record they made). A slot's entry is told of after a few more slots' +/// work, as it would be if the pass's thread had been held up for that long; +/// the queue drops what is told of a write that is not the one it holds +/// (`TextureQueue::same`), as before. With [`queue_batch`] off, each at once. +struct Tells<'a> { + host: &'a crate::descriptor::host::HostHeap, + told: Vec<(u32, u64, u64, crate::descriptor::host::Told)>, +} + +impl Tells<'_> { + /// Few slots' work (some microseconds each), so that a pass that takes + /// the slots due meanwhile on another thread finds few of these told + /// late. + const BATCH: usize = 16; + + fn tell(&mut self, index: u32, write: u64, what: crate::descriptor::host::Told) { + use crate::descriptor::host::Told; + let host = self.host; + if !queue_batch() { + rest(0, || match what { + Told::Done(again) => host.texture_slot_done(index, write, again), + Told::Recheck(due, at, print, looks, uploaded) => { + host.texture_slot_recheck(index, write, due, at, print, looks, uploaded); + } + Told::Later(frame, most) => host.texture_slot_later(index, write, frame, most), + Told::Held(due) => host.texture_slot_held(index, write, due), + }); + return; + } + self.told.push((index, write, crate::frame::current(), what)); + if self.told.len() >= Self::BATCH { + self.flush(); + } + } + + fn flush(&mut self) { + if !self.told.is_empty() { + let host = self.host; + rest(0, || host.texture_slots_told(&mut self.told)); + } + } +} + +impl Drop for Tells<'_> { + fn drop(&mut self) { + self.flush(); + } +} + /// Of [`HEAP_TEXTURE_REST`]' place 4 (slots shown after their upload, /// flipped or made at once), since the last 5-second line: nanoseconds and /// calls of slots made at once (`HostHeap::mirror` by the pass), of slots @@ -3058,16 +3122,23 @@ impl State { before(0, || host.texture_slots_waiting(frame)); } let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake); - let (mut due, census) = before(2, || host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 })); + // (And what the queue knew of each, `known`: see `Tells`.) + let (mut due, mut known, census) = + before(2, || host.texture_slots_due_known(frame, if baking { 1 << 16 } else { 4096 })); // (Those that are due later after all that are due.) let on_time = due.len(); if baking { before(2, || { - let known: std::collections::HashSet = due.iter().map(|&(index, _)| index).collect(); + let taken: std::collections::HashSet = due.iter().map(|&(index, _)| index).collect(); 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))); + let (ahead, ahead_known, _) = host.texture_slots_due_known(frame + BAKE_AHEAD[usize::from(again)], 1 << 16); + for (slot, knew) in ahead.into_iter().zip(ahead_known) { + if !taken.contains(&slot.0) { + due.push(slot); + known.push(knew); + } + } }); } HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); @@ -3149,7 +3220,9 @@ impl State { BAKE_SERVED.store(0, Ordering::Relaxed); } let mut served = true; - for (index, write) in due { + let mut tells = Tells { host, told: Vec::with_capacity(Tells::BATCH) }; + use crate::descriptor::host::Told; + for ((index, write), knew) in due.into_iter().zip(known) { 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); @@ -3182,16 +3255,21 @@ 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)) = rest(0, || host.texture_slot_checked(index)) { + // What the queue knew of it when the slots due were taken, while + // its marks say it holds the write handed out still; else (or with + // `VICTORY_QUEUE_BATCH=0`) asked now. + let checked = match knew { + knew if queue_batch() && host.texture_slot_write(index) == Some(write) => knew, + _ => rest(0, || host.texture_slot_checked(index)), + }; + if let Some((at, len, print, looks, uploaded)) = checked { let looked = timed(0, || crate::texture::fingerprint(at, len)); if looked == print { HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed); 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), + tells.tell(index, write, match RECHECK_FRAMES.get(usize::from(looks) + 1) { + Some(wait) => Told::Recheck(frame + wait, (at, len), print, looks + 1, uploaded), + None => Told::Done(None), }); continue; } @@ -3233,10 +3311,8 @@ impl State { HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed); outcome(slot_outcome::AWAY); // Streamed out: what the slot showed is let go. - rest(0, || { - host.texture_slot_gone(index); - host.texture_slot_later(index, write, frame, most); - }); + rest(0, || host.texture_slot_gone(index)); + tells.tell(index, write, Told::Later(frame, most)); continue; } rest(0, || host.texture_slot_here(index)); @@ -3245,7 +3321,7 @@ impl State { if mapped <= rest(0, || host.texture_slot_mapped(index)) { HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed); outcome(slot_outcome::NO_MORE); - rest(0, || host.texture_slot_later(index, write, frame, most)); + tells.tell(index, write, Told::Later(frame, most)); continue; } if !crate::texture::committed(address as *const u8, 1) { @@ -3264,7 +3340,7 @@ impl State { { outcome(slot_outcome::NOTHING); HEAP_TEXTURE_NOTHING[0].fetch_add(1, Ordering::Relaxed); - rest(0, || host.texture_slot_done(index, write, None)); + tells.tell(index, write, Told::Done(None)); continue; } // From here on a host texture is made: not without room. The @@ -3290,7 +3366,7 @@ impl State { // 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. - rest(0, || host.texture_slot_held(index, write, frame + most)); + tells.tell(index, write, Told::Held(frame + most)); if refused > 1024 { break; } @@ -3363,7 +3439,7 @@ impl State { at_once(true); outcome(slot_outcome::NOTHING); HEAP_TEXTURE_NOTHING[1].fetch_add(1, Ordering::Relaxed); - rest(0, || host.texture_slot_done(index, write, None)); + tells.tell(index, write, Told::Done(None)); continue; } }; @@ -3378,7 +3454,7 @@ impl State { // a render target, a depth or unordered access texture: the host's own outcome(slot_outcome::NOTHING); HEAP_TEXTURE_NOTHING[2].fetch_add(1, Ordering::Relaxed); - rest(0, || host.texture_slot_done(index, write, None)); + tells.tell(index, write, Told::Done(None)); continue; } // A texture that has a staging buffer now is one draws read @@ -3419,11 +3495,9 @@ impl State { 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), + tells.tell(index, write, match memory { + Some((at, len, print)) => Told::Recheck(frame + again_in, (at, len), print, 0, frame), + None => Told::Done(again), }); continue; } @@ -3531,7 +3605,7 @@ impl State { // detile and upload all of it once more. HEAP_TEXTURES_TABLED.fetch_add(1, Ordering::Relaxed); outcome(slot_outcome::TABLED); - rest(0, || host.texture_slot_done(index, write, again)); + tells.tell(index, write, Told::Done(again)); continue; } // Uploaded: the list holds the staging buffer until it has run; @@ -3553,14 +3627,14 @@ impl State { } HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed); HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed); - rest(0, || match memory { + tells.tell(index, write, match memory { // Whole and uploaded: looked at again (see above). - 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), + Some((at, len, print)) => Told::Recheck(frame + again_in, (at, len), print, 0, frame), + None => Told::Done(again), }); } + // Told before anything after the loop looks at the queue. + tells.flush(); if sync.is_none() && baking && served { BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed); } From 8625c3a00b61ef1f53c664f03f5958fbada8a1bc Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:13:07 +0530 Subject: [PATCH 4/9] VICTORY_TABLED_REREAD=1: a table read takes out a slot written after its frame's first read (off) A slot draws read through a table leaves the queue of textures picked by index at its first table read of a frame only (`tabled_in`, once per slot and frame; and the draws of a recording tell of a record once, `Listed::tabled`). The title rewrites tables' slots while it records: a slot written after that read is queued due `TABLED_GRACE` (8) frames on, the draws that read it later in the same frame leave it there, and the pass takes it 8 frames later and finds it uploaded by those draws or nothing to do: 17,000-58,000 slots in 5 s of a cutscene (coolfox-20261126-223059, analysis 6.6; "read through tables" and much of "nothing to bring up to date" in the pass's split line). With the switch, such a later read takes the slot out when the queue's marks (b5b7806) say it holds it, a lock-free look (without the marks it does nothing: every read would take the lock), and the recording's gate lets a slot the queue holds through, so the draw also makes the title's slot in place as at a first read (`mirror_after`). Counted in the lock line: slots taken out by a table read after the first of their frame, since the start. Off by default (not behaviour-neutral): a shader that picks such a slot by index then sees what the draw made of it at once, not what the pass makes 8 frames later; that lateness is a candidate of the flicker at scene loads (analysis 6.12). Test: written after its frame's first read, a slot waits for its grace frames; a later read takes it out with the switch only. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 82 ++++++++++++++++++++++- crates/victory-gpu/src/draw.rs | 8 ++- crates/victory-gpu/src/host.rs | 4 +- 3 files changed, 89 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index bc04362..e0194e7 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -910,9 +910,10 @@ const TABLED_READ: u32 = 1 << 31; /// Since the start: writes of texture views into slots that count as a /// table's (due later), and slots that left the queue because a draw read -/// them through a table. -pub(crate) static TABLED_WRITES: [std::sync::atomic::AtomicU64; 2] = - [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// them through a table; of the latter, those a draw read again in the +/// frame of their first read ([`tabled_reread`]). +pub(crate) static TABLED_WRITES: [std::sync::atomic::AtomicU64; 3] = + [const { std::sync::atomic::AtomicU64::new(0) }; 3]; /// Whether slots draws read through tables leave the queue of textures /// picked by index; `VICTORY_TABLED_TEXTURES=1` keeps them in it as @@ -922,6 +923,28 @@ fn tabled_out() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_TABLED_TEXTURES").is_none_or(|v| v != "1")) } +/// Whether a table read of a slot the queue holds leaves it out also when +/// the slot was read through a table before in the same frame +/// (`VICTORY_TABLED_REREAD=1`; off: once a frame, as before). +/// +/// A slot leaves the queue at its first table read of a frame only. The +/// title rewrites tables' slots while it records (a table per draw), so a +/// slot written after that read waits in the queue `TABLED_GRACE` frames +/// for a draw, and the draws that read it in the same frame do not take it +/// out: the pass takes it 8 frames later and finds it uploaded by those +/// draws, or nothing to do (17,000-58,000 slots in 5 s of a cutscene, +/// coolfox-20261126-223059; analysis 6.6). On, such a read takes it out +/// (asked by the queue's marks: needs `VICTORY_QUEUE_MARKS` on), and the +/// draw's gate for records it told of already (`Listed::tabled`) lets a +/// slot the queue holds through. Off by default: what a shader that picks +/// such a slot by index sees then comes from the draw's making of it, not +/// the pass's 8 frames later (a candidate of the flicker at scene loads, +/// analysis 6.12). +pub(crate) fn tabled_reread() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TABLED_REREAD").is_some_and(|v| v == "1")) +} + /// What the queue of textures picked by index knows of a title slot. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Waiting { @@ -2909,6 +2932,11 @@ impl HostHeap { /// [`HostHeap::texture_slot_tabled`] in frame `frame`. fn tabled_in(&self, index: u32, read: bool, frame: u64) { + self.tabled_in_as(index, read, frame, tabled_reread()); + } + + /// [`HostHeap::tabled_in`], with [`tabled_reread`] as `reread` says. + fn tabled_in_as(&self, index: u32, read: bool, frame: u64, reread: bool) { use std::sync::atomic::Ordering::Relaxed; let Some(stamp) = self.tabled.get(index as usize) else { return; @@ -2935,9 +2963,25 @@ impl HostHeap { TABLED_WRITES[1].fetch_add(1, Relaxed); } } + } else if tabled_out() && reread && self.queued(index) == Some(true) { + // Read again in the frame of its first read, and queued since + // that read (the title wrote it again, due `TABLED_GRACE` frames + // on): this draw brought it up to date too. Asked by the marks + // alone (without them, every read would take the lock). + let mut textures = self.queue(super::queue_site::TABLE); + if textures.take_out(index) { + TABLED_WRITES[1].fetch_add(1, Relaxed); + TABLED_WRITES[2].fetch_add(1, Relaxed); + } } } + /// Whether title slot `index` is in the queue of textures picked by + /// index, by its marks ([`QueueMarks`]; false if they are not used). + pub(crate) fn texture_slot_queued(&self, index: u32) -> bool { + self.queued(index) == Some(true) + } + /// Whether title slot `index` was a table's within the last /// [`TABLED_FRAMES`] frames before `frame` (never, if such slots are /// to be queued as any other). @@ -6062,6 +6106,38 @@ mod tests { assert_eq!(marks(&heap), held(&[])); } + /// A slot written after its first table read of a frame waits for its + /// grace frames; a later read in that frame takes it out only with + /// `VICTORY_TABLED_REREAD=1` (`tabled_in_as`'s `reread`). + #[test] + fn a_slot_written_after_its_read_leaves_at_the_next_read_when_asked() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + if !tabled_out() || !queue_marks() { + return; + } + let frame = 200; + let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + heap.tabled_in_as(4, true, frame, true); + heap.queue_texture(4, true, false, frame); + assert_eq!(slots(frame + TABLED_GRACE - 1), []); + assert_eq!(slots(frame + TABLED_GRACE), [4]); + // Read again in that frame, as before: it stays. + heap.tabled_in_as(4, true, frame, false); + assert_eq!(slots(frame + TABLED_GRACE), [4]); + // With the re-read: out, and counted. + let before = TABLED_WRITES[2].load(std::sync::atomic::Ordering::Relaxed); + heap.tabled_in_as(4, true, frame, true); + assert_eq!(slots(u64::MAX), []); + assert!(TABLED_WRITES[2].load(std::sync::atomic::Ordering::Relaxed) > before); + assert!(!heap.texture_slot_queued(4)); + // A slot not queued: nothing to take out. + heap.tabled_in_as(5, true, frame, true); + heap.tabled_in_as(5, true, frame, true); + assert_eq!(slots(u64::MAX), []); + } + /// The slots due come in their order with what the queue knew of each /// (a slot uploaded whole and waiting for a look again), as asked slot /// by slot. diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 4f6ac35..47db346 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -4417,9 +4417,15 @@ impl State { } } } + // (Told once per record and recording; with + // `VICTORY_TABLED_REREAD=1` also of a slot the queue + // holds again since: written after its first read.) if let Some(title) = title_first && listed.texture - && listed.tabled != Some((title + k, kind.is_some())) + && (listed.tabled != Some((title + k, kind.is_some())) + || (crate::descriptor::host::tabled_reread() + && kind.is_some() + && host.texture_slot_queued(title + k))) { listed.tabled = Some((title + k, kind.is_some())); host.texture_slot_tabled(title + k, kind.is_some()); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4e4acef..c8a99e3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -9202,7 +9202,8 @@ impl Meter { slot, {} taking the slots due, {} making slots due, {} noting a slot's record, {} by table reads, {} for \ stale views, {} else); waited for {} ms ({}, {}, {}, {}, {}, {}, {} ms by the same places); held {} ms \ taking the slots due, {} ms making slots due, {} ms for stale views; not taken {} times, as nothing would \ - have changed ({} noting a slot's record, {} by table reads, {} for stale views)", + have changed ({} noting a slot's record, {} by table reads, {} for stale views); since the start, {} slots \ + taken out by a table read after the first of their frame (VICTORY_TABLED_REREAD=1)", taken.iter().sum::(), taken[0], taken[1], @@ -9226,6 +9227,7 @@ impl Meter { skipped[3], skipped[4], skipped[5], + crate::descriptor::host::TABLED_WRITES[2].load(Ordering::Relaxed), ); } } From 5dda41ddff71e3f6052b843c115d2e09e89df41d Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:28:36 +0530 Subject: [PATCH 5/9] VICTORY_QUEUE_HOST_TEXTURES=0: records of textures the host writes are not queued for the texture pass (off) A slot's record of a texture object the host renders to or writes (a target, depth or unordered access texture) is queued for the pass over textures picked by index like any texture. The pass takes such a slot, finds nothing to bring up to date (it makes and uploads nothing for it) and takes it out; the title writes such views into its tables' slots every frame, so they come back, each time a take of the queue's lock, a place among the slots due and a few microseconds of the pass (58,978 of 90,699 slots taken in 5 s of a cutscene found nothing to do, coolfox-20261126-233017 18:02:23; 18ff932 says how many were such views). With the switch, such a record takes the slot out of the queue as a buffer view's does (`note_buffer`; with the queue's marks, without its lock when it is not queued). Counted since the start in the lock line. Off by default (not behaviour-neutral, though the pass did nothing for these slots): fewer slots are due, so a pass reaches others sooner, the catch-up budget (VICTORY_TEXTURE_CATCHUP, started by the count due; off in the launcher) starts less often, and a bake's pass is asked for less often (it runs when the queue's write count changed). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 50 ++++++++++++++++++++++- crates/victory-gpu/src/host.rs | 4 +- 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index e0194e7..7e1968f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1035,6 +1035,49 @@ fn not_taken(site: usize) { }); } +/// Whether a slot's record of a texture object the host renders to or writes +/// (a target, depth or unordered access texture: not `resource::title_fills`) +/// is queued for the pass over textures picked by index, as any texture +/// (`VICTORY_QUEUE_HOST_TEXTURES=0`: it is not; the slot leaves the queue as +/// a buffer view's would). +/// +/// The pass takes such a slot and finds nothing to bring up to date: it +/// neither makes nor uploads anything for it, and takes it out +/// (`draw.rs` `heap_textures`, the first of its "nothing to bring up to +/// date"). The title writes such views into its tables' slots every frame, +/// so they are queued again and again, take the queue's lock, and stand +/// among the slots due (58,978 of 90,699 slots the pass took in 5 s of a +/// cutscene found nothing to do, coolfox-20261126-233017 18:02:23; the line +/// of 18ff932 says how many of those were such views). Off by default: the +/// slots due are fewer, so a pass reaches others sooner, the catch-up budget +/// (`VICTORY_TEXTURE_CATCHUP`, by the count due) starts less often, and a +/// bake's pass is asked less often (the queue's write count). +pub(crate) fn queue_host_textures() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE_HOST_TEXTURES").is_none_or(|v| v != "0")) +} + +/// Records of textures the host writes left out of the queue +/// ([`queue_host_textures`]) since the start, counted by each thread in +/// batches. +pub(crate) static HOST_TEXTURES_LEFT_OUT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +fn host_texture_left_out() { + const BATCH: u32 = 64; + thread_local! { + static N: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + N.with(|n| { + let now = n.get() + 1; + if now >= BATCH { + HOST_TEXTURES_LEFT_OUT.fetch_add(u64::from(now), std::sync::atomic::Ordering::Relaxed); + n.set(0); + } else { + n.set(now); + } + }); +} + /// The queue of title slots whose texture view waits to be brought up to /// date for shaders that pick textures by index: which are due, and in /// which order (no host heap needed, so it is tested without one). @@ -3086,7 +3129,12 @@ impl HostHeap { } Some(View::Shader(r, _)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => { OBJECT_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - true + // A texture the host renders to or writes: nothing for the + // pass to bring up to date ([`queue_host_textures`]). + queue_host_textures() || crate::resource::title_fills(*r as crate::object::This) || { + host_texture_left_out(); + false + } } _ => false, }; diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index c8a99e3..11636df 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -9203,7 +9203,8 @@ impl Meter { stale views, {} else); waited for {} ms ({}, {}, {}, {}, {}, {}, {} ms by the same places); held {} ms \ taking the slots due, {} ms making slots due, {} ms for stale views; not taken {} times, as nothing would \ have changed ({} noting a slot's record, {} by table reads, {} for stale views); since the start, {} slots \ - taken out by a table read after the first of their frame (VICTORY_TABLED_REREAD=1)", + taken out by a table read after the first of their frame (VICTORY_TABLED_REREAD=1), {} records of textures \ + the host writes left out of the queue (VICTORY_QUEUE_HOST_TEXTURES=0)", taken.iter().sum::(), taken[0], taken[1], @@ -9228,6 +9229,7 @@ impl Meter { skipped[4], skipped[5], crate::descriptor::host::TABLED_WRITES[2].load(Ordering::Relaxed), + crate::descriptor::host::HOST_TEXTURES_LEFT_OUT.load(Ordering::Relaxed), ); } } From 13dca45ac6cda9dcda6c0ff8a1e9ac8ebb16bbb3 Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:29:04 +0530 Subject: [PATCH 6/9] Texture pass: a slot shown after its upload or flipped uses the view read at its turn's start The pass reads the view a slot holds at the start of the slot's turn (under the views table's read lock: the record, the view by its number, a copy of it). For a slot shown after its upload (VICTORY_SHOW_AFTER=1, in the launcher) or flipped from an earlier view of the same texture, it read the same record and view again a few microseconds later to make the host texture and its upload. It uses the first read now. Other threads waited 86-383 ms per 5 s of a cutscene for the views table's lock (coolfox-20261126-233017). Behaviour-neutral: the record may change between two reads, and using the first is as if the second had come that much earlier; a write of the slot meanwhile queues it again, as before. Slots made at once (the other path) are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 47db346..bf55930 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3412,11 +3412,12 @@ impl State { Some((view, key)) => (Some(view), Some(key)), None => (None, None), } + } else if shows_other || late { + // The view read at the start of this slot's turn (read + // again, the views' table was asked twice a slot). + (held.clone(), None) } else { - let view = heap.handle(index).and_then(|handle| { - if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) } - }); - (view, None) + (heap.handle(index).and_then(|handle| host.mirror(index, handle, true)), None) } }); // (`nothing`: the slot has nothing to bring up to date.) From 185bc4cc84b3735bc058584c699312086af14f0b Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:20:18 +0530 Subject: [PATCH 7/9] VICTORY_POOL_SMALL=0: pooled textures at 64 KiB multiples (off); diagnostics: a pooled texture read past its piece is said Ported from Belobug/VIctory-Belobug-AMD c278f0d. That fork places pooled textures of 64 KiB and less at 64 KiB multiples by default (4 KiB multiples only with VICTORY_POOL_SMALL=1): its two device losses with the pool on the night of 2026-11-25 faulted in 256x256 block-compressed textures with 7 levels placed at a 4 KiB multiple that is no 64 KiB one, whose descriptor base lay 0xa000 into the piece and whose first level ended 0x2000 past it, read by the card the moment the slot was made. Not proven to be the cause. Here the switch keeps its name and meaning, with our default: unset or 1, 4 KiB multiples where the host allows it, as before; VICTORY_POOL_SMALL=0, 64 KiB multiples (at most 60 KiB more card memory per small texture). Also an A/B switch in diag builds (VICTORY_AB). Diag builds with the address book say loudly when a pooled texture's first level lies past the end of its piece (`where_the_card_reads`, `book::address`), and where the first levels of the first 40 lie. The fork's test of a placed texture's reference to its heap is left out (a measurement of the host; the fork weakened it in 4cd2d13). Off by default: changes where pooled textures lie and how much card memory they take. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/book.rs | 11 ++++ crates/victory-gpu/src/pool.rs | 103 ++++++++++++++++++++++++++++++++- 2 files changed, 112 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/book.rs b/crates/victory-gpu/src/book.rs index 469952d..87de67d 100644 --- a/crates/victory-gpu/src/book.rs +++ b/crates/victory-gpu/src/book.rs @@ -242,6 +242,17 @@ fn viewable(format: i32) -> Option { }) } +/// The address of `texture` as its descriptor has it (its first level's), +/// if the book is kept. +pub(crate) fn address(texture: &ID3D12Resource) -> Option { + if !on() { + return None; + } + // SAFETY: a live resource. + let desc = unsafe { texture.GetDesc() }; + texture_address(texture, &desc) +} + /// The address of a texture: the base its descriptor has. fn texture_address(texture: &ID3D12Resource, desc: &D3D12_RESOURCE_DESC) -> Option { struct Slot(ID3D12DescriptorHeap, usize); diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index cde4cdb..5d3f23e 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -459,6 +459,103 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { } } +/// Whether textures of 64 KiB and less are placed at multiples of 4 KiB in +/// their block, where the host allows it (as before; `VICTORY_POOL_SMALL=0`: +/// at multiples of 64 KiB, as every other texture). +/// +/// Ported from Belobug/VIctory-Belobug-AMD c278f0d, where 64 KiB multiples +/// are the default: the two device losses of the night of 2026-11-25 with +/// the pool in that fork's report (runs steps-ab2 and start-3) faulted in +/// the same kind of texture: 256x256, block-compressed, 7 levels, placed at +/// a 4 KiB multiple that is no 64 KiB one (offsets 0x406000 and 0x3fe6000 of +/// their blocks), never used before, read by the card the moment its slot +/// was made; the descriptor's base of both lies 0xa000 into the piece, on a +/// 64 KiB multiple, and its first level of 32 KiB from there ends 0x2000 +/// past the piece. Why the card faulted there is not proven; textures at +/// 64 KiB multiples have none of that, for some memory (at most 60 KiB a +/// small texture). +fn small_placement() -> bool { + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("VICTORY_POOL_SMALL") { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_POOL_SMALL").is_none_or(|v| v != "0")) +} + +/// Diagnostics: whether the card reads a pooled texture inside the piece it +/// was placed in. A block's address is taken as the lowest of its textures' +/// descriptor bases less their pieces' starts (a texture's first level may +/// lie past its piece's start, never before it); a texture whose first level +/// the card would read from past its piece's end is said loudly. (Ported +/// from Belobug/VIctory-Belobug-AMD c278f0d.) +#[cfg(feature = "diagnostics")] +fn where_the_card_reads(heap: &ID3D12Heap, texture: &ID3D12Resource, piece: Piece) { + static BLOCKS: Mutex> = Mutex::new(Vec::new()); + static SAID: AtomicU64 = AtomicU64::new(0); + let Some(base) = crate::book::address(texture) else { return }; + let Some(seen) = base.checked_sub(piece.start) else { return }; + let raw = heap.as_raw() as usize; + let block = { + let mut blocks = BLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + match blocks.iter_mut().find(|b| b.0 == raw) { + Some(b) => { + b.1 = b.1.min(seen); + b.1 + } + None => { + if blocks.len() >= 4096 { + blocks.remove(0); + } + blocks.push((raw, seen)); + seen + } + } + }; + let into = base - block - piece.start; + // SAFETY: a live texture. + let desc = unsafe { texture.GetDesc() }; + // The first level's bytes, as a copy would have them. + let mut level = 0u64; + if let Some(host) = crate::host::made_host() { + // SAFETY: plain query of a valid description. + unsafe { host.device.GetCopyableFootprints(&desc, 0, 1, 0, None, None, None, Some(&raw mut level)) }; + } + if into + level > piece.len { + let n = SAID.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 50 || n.is_power_of_two() { + tracing::error!( + times = n, + base = format_args!("{base:#x}"), + piece_start = format_args!("{:#x}", piece.start), + piece_len = format_args!("{:#x}", piece.len), + into = format_args!("{into:#x}"), + first_level_bytes = format_args!("{level:#x}"), + width = desc.Width, + height = desc.Height, + levels = desc.MipLevels, + format = desc.Format.0, + "POOL: the card reads a pooled texture's first level past the end of the piece it was placed in" + ); + } + } + // Every placement offset and where the first level lies, a few of them. + static SHOWN: AtomicU64 = AtomicU64::new(0); + if into > 0 && SHOWN.fetch_add(1, Ordering::Relaxed) < 40 { + tracing::info!( + into = format_args!("{into:#x}"), + piece_start = format_args!("{:#x}", piece.start), + piece_len = format_args!("{:#x}", piece.len), + width = desc.Width, + height = desc.Height, + levels = desc.MipLevels, + format = desc.Format.0, + alignment = desc.Alignment, + "pool: a texture's first level lies past its piece's start" + ); + } +} + /// Textures made in the last second ([`fresh`]), and when. static RECENT: Mutex> = Mutex::new(VecDeque::new()); @@ -508,10 +605,11 @@ pub(crate) unsafe fn texture( return None; } // Small textures lie at multiples of 4 KiB where the host allows it - // (the top mip is 64 KiB at most): 64 KiB each otherwise. + // (the top mip is 64 KiB at most) and [`small_placement`] says so: 64 KiB + // each otherwise. // SAFETY: the caller's description. let mut d = unsafe { *desc }; - d.Alignment = u64::from(D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT); + d.Alignment = if small_placement() { u64::from(D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT) } else { 0 }; // SAFETY: plain queries. let mut info = unsafe { device.GetResourceAllocationInfo(0, &[d]) }; if info.SizeInBytes == u64::MAX || info.Alignment != d.Alignment { @@ -555,6 +653,7 @@ pub(crate) unsafe fn texture( #[cfg(feature = "diagnostics")] { crate::book::made(&made, || "a texture in a block".into()); + where_the_card_reads(&heap, &made, piece); crate::book::block(&heap, &made, piece.start, BLOCK); crate::book::note(made.as_raw() as usize, || { let block = lock(&TEXTURES).blocks.get(piece.block).and_then(Option::as_ref).map(|b| (b.made, b.since)); From ee3fb5201a0371a34537c0306a7065479e71d02d Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:21:47 +0530 Subject: [PATCH 8/9] VICTORY_SHOW_NEW_LATER=1: slots show a texture made while earlier lists run only once those ran (off) Ported from Belobug/VIctory-Belobug-AMD 4cd2d13 and 91018a5, where it is on by default. Every device loss with the texture pool in that fork's report (n08, n11, n15, steps-ab2, start-3, a user's play-1125-2107 without ray tracing) was a page fault at the first byte of a texture in a block made that millisecond, its title slot changed "at once" (`mirror`) while lists sent before read that slot by index; VICTORY_SHOW_AFTER covers only some paths (a draw's table, the texture pass's own uploads). We run the pool. With the switch, `HostHeap::mirror` holds a slot whose new view shows a pooled texture made while a submission begun before it may still run (`pool::begun_before`: the submissions begun when it was made, noted in `pool::made_now`) on what it showed, or the neutral texture if that cannot stand for it (`keep_shown`), and flips it when every such submission has finished (`FLIPS`, `texture_slots_flip`); a slot held back is held once, not again at each draw or pass that reads it (`NEW_PENDING`, 91018a5). A line says how many slots were held back since the start (with the switch on). Also an A/B switch in diag builds (VICTORY_AB). Off by default (not behaviour-neutral: a slot shows its new texture one or more submissions later); with it off, `made_now` notes nothing more than before and nothing else changes. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 99 +++++++++++++++++++++++ crates/victory-gpu/src/host.rs | 7 ++ crates/victory-gpu/src/pool.rs | 54 ++++++++++++- 3 files changed, 156 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 7e1968f..88bc419 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -294,6 +294,55 @@ pub(crate) fn show_after() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_SHOW_AFTER").is_some_and(|v| v != "0")) } +/// Whether a title slot that would show a texture made while submissions +/// begun before it may still run shows it only once those have finished +/// (`VICTORY_SHOW_NEW_LATER=1`; off: at once, as before). Also an A/B switch +/// in diag builds (`VICTORY_AB`). +/// +/// Ported from Belobug/VIctory-Belobug-AMD 4cd2d13 and 91018a5, where it is +/// on by default: [`show_after`] leaves out slots made "at once" from a +/// draw's table, the texture pass's paths that are no upload of theirs, and +/// the heap's own look at buffer views; that fork's device losses with the +/// texture pool (steps-ab2, start-3, a user's play-1125-2107 without ray +/// tracing) were all page faults at the first byte of a texture in a block +/// made that millisecond, its slot changed "at once" while lists sent before +/// read that slot by index. `HostHeap::mirror` then holds such a slot on what +/// it showed (or the neutral texture) and flips it when every submission +/// begun before the texture was made has finished. +pub(crate) fn show_new_later() -> bool { + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("VICTORY_SHOW_NEW_LATER") { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SHOW_NEW_LATER").is_some_and(|v| v == "1")) +} + +/// Slots [`show_new_later`] holds back now: heap, slot, record. (A slot +/// held back is held once, not again at each draw that reads it.) +static NEW_PENDING: std::sync::LazyLock>> = + std::sync::LazyLock::new(Default::default); + +/// Slots held back by [`show_new_later`] since the start. +pub(crate) static NEW_LATER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// The submissions begun when the host texture `view` shows was made, if +/// one begun before that may still run (`crate::pool::begun_before`). The +/// host texture is made here if it is not yet, as [`make`] would. +fn begun_before(view: &View) -> Option { + // (Resolved first: the texture made here, a moment ago, is the case.) + let shader = match view { + View::Placed(false, resource, _) if resource[0] != 1 => placed_texture(view)?, + View::Shader(..) => view.clone(), + _ => return None, + }; + let View::Shader(resource, _) = shader else { + return None; + }; + let texture = crate::resource::host_resource(resource as crate::object::This)?; + crate::pool::begun_before(texture) +} + /// Slots shown late ([`show_after`]), the frames they waited, the longest; /// those that were given the neutral texture meanwhile; those not shown any /// more when their time came. @@ -2853,6 +2902,15 @@ impl HostHeap { *flips = wait; ready }; + // Held back by `show_new_later`: no longer once flipped. + { + let mut pending = NEW_PENDING.lock().unwrap_or_else(|e| e.into_inner()); + if !pending.is_empty() { + for f in &ready { + pending.remove(&(f.heap, f.index, f.key)); + } + } + } let mut flipped = 0; let mut late_flipped = 0; for f in ready { @@ -3756,6 +3814,47 @@ impl HostHeap { } } } + // A texture made while lists sent before it may still run: those + // read this slot by index, and must not find it ([`show_new_later`]). + // The slot shows what it showed (or the neutral texture), and the + // new view when they have all run. + if !later + && !self.sampler + && show_new_later() + && is_texture_view(&view) + && let Some(after) = begun_before(&view) + { + // Asked again (each draw that reads the slot, each pass) + // while it waits: nothing more to do. + let own = (std::ptr::from_ref(self) as usize, index, key); + if !NEW_PENDING.lock().unwrap_or_else(|e| e.into_inner()).insert(own) { + drop(held); + self.unmake_stale(index, stale); + return Some(view); + } + let old = view_at(shown as u32, (shown >> 32) as u32); + let kept = old.is_some_and(|old| match kin(&old, &view) { + Kin::Same => true, + kin => kin.kept(keep_shown()), + }); + if shown == 0 || !kept { + #[cfg(feature = "diagnostics")] + note_before(index, shown, "neutral, new texture"); + self.quick_is(index, 0); + self.made.set(index, 0); + let kept = neutral_for(&view, self.at(index)); + self.put(index); + self.clear_twin(index); + self.keep(index, kept); + } + let late = Some(crate::frame::current()); + let flip = Flip { after, heap: std::ptr::from_ref(self) as usize, index, handle, key, late }; + FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip); + NEW_LATER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + drop(held); + self.unmake_stale(index, stale); + return Some(view); + } #[cfg(feature = "diagnostics")] if !self.sampler && is_texture_view(&view) { note_before(index, shown, if later { "null, waits" } else { "at once" }); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 11636df..82bf19d 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -9192,6 +9192,13 @@ impl Meter { parts[7].saturating_sub(due_by_memory + remade + due_list), ); } + if crate::descriptor::host::show_new_later() { + tracing::info!( + "slots of textures made while lists sent before them ran, shown once those had run \ + (VICTORY_SHOW_NEW_LATER=1), since the start: {}", + crate::descriptor::host::NEW_LATER.load(Ordering::Relaxed) + ); + } // The queue's lock by place (`crate::descriptor::queue_site`). let lock = crate::descriptor::QUEUE_LOCK.each_ref().map(|row| row.each_ref().map(|n| n.swap(0, Ordering::Relaxed))); let [taken, waited, held, skipped] = lock; diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 5d3f23e..aadc34d 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -568,11 +568,57 @@ pub(crate) fn fresh(texture: &ID3D12Resource) -> bool { fn made_now(texture: &ID3D12Resource) { let now = now(); - let mut recent = RECENT.lock().unwrap_or_else(|e| e.into_inner()); - while recent.front().is_some_and(|r| r.1 + 1000 < now) { - recent.pop_front(); + let raw = texture.as_raw() as usize; + { + let mut recent = RECENT.lock().unwrap_or_else(|e| e.into_inner()); + while recent.front().is_some_and(|r| r.1 + 1000 < now) { + recent.pop_front(); + } + recent.push_back((raw, now)); } - recent.push_back((texture.as_raw() as usize, now)); + if !crate::descriptor::host::show_new_later() { + return; + } + let begun = crate::host::submissions().0; + NEWEST_BEGUN.fetch_max(begun, Ordering::Relaxed); + let mut unseen = UNSEEN.lock().unwrap_or_else(|e| e.into_inner()); + let finished = crate::host::submissions().1; + // Those every submission begun before them has left behind are no + // one's concern any more (and a raw pointer may come again). + unseen.retain(|_, b| *b > finished); + unseen.insert(raw, begun); +} + +/// Pooled textures made while submissions begun before them may still run: +/// the submissions begun when each was made (with +/// `crate::descriptor::host::show_new_later` only). Ported from +/// Belobug/VIctory-Belobug-AMD 4cd2d13. +static UNSEEN: std::sync::LazyLock>> = std::sync::LazyLock::new(Default::default); +/// The newest of those numbers (nothing to look up once it has finished). +static NEWEST_BEGUN: AtomicU64 = AtomicU64::new(0); + +/// Whether a texture was made in a block while a submission begun before +/// it may still run ([`begun_before`]). +fn any_unseen() -> bool { + NEWEST_BEGUN.load(Ordering::Relaxed) > crate::host::submissions().1 +} + +/// The submissions begun when `texture` was made in a block, if one of +/// those may still be on the card: lists already sent then must not find it +/// in a slot they read by index (`crate::descriptor::host::show_new_later`). +/// Every device loss with the pool in the report of +/// Belobug/VIctory-Belobug-AMD (runs n08, n11, n15, steps-ab2, start-3 and a +/// user's play-1125-2107) was a page fault at the first byte of a texture +/// made that very millisecond, its title slot changed "at once" while lists +/// sent before it read that slot by index. +pub(crate) fn begun_before(texture: &ID3D12Resource) -> Option { + if !any_unseen() { + return None; + } + let finished = crate::host::submissions().1; + let raw = texture.as_raw() as usize; + let unseen = UNSEEN.lock().unwrap_or_else(|e| e.into_inner()); + unseen.get(&raw).copied().filter(|&begun| begun > finished) } /// Makes `texture` give `piece` back when the last reference to it goes. From 91df493ead7ec759e0197efc92c8b93944a103f9 Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:26:55 +0530 Subject: [PATCH 9/9] VICTORY_PRELUDE_UPLOADS=1: title textures uploaded on the list's prelude, decided at submission after the check (off) Ported from Belobug/VIctory-Belobug-AMD 5d6bd84 ("Upload title textures in submission prelude to fix frame-order & flickering"), where it is the only way. A list records the upload of a title texture it samples only if the staging buffer was changed when the list was recorded; the check at submission may then find the memory changed and detile it, and only the next list that samples the texture uploads that: a frame late when every list of the frame was recorded before the check (a video's ring of buffers shows an older picture, a texture streamed in its last one). A candidate of the flicker at scene loads (analysis 6.12). With the switch, `texture::upload_from` records nothing in the list: it leaves a `PreludeUpload` (staging buffer, host copy, levels on demand) with the list, and its `Step::Texture` as before, so the checks run where they ran. At submission, after the list's steps, the staging buffers left pending are refreshed (`Batch::refresh_textures`), and each texture whose host copy was never uploaded or whose staging buffer was detiled since its last upload is claimed (`claim_upload`; once per change, whichever lists of the submission sample it) and copied on the list's prelude (`HostList::prelude`): aliasing barrier for a pooled texture's first upload, to the copy destination state and from there to the state the list starts with. What the list's own upload did after the copy (a host copy grown, levels on demand given memory, what the host copy holds) is done at the claim. Kept as before: bakes (they record their copies whatever the check finds) and movie planes. Left out of the port: the texture store's prefill (this tree has none), the fork's refreshes before every copy and run step (here `title_written` flushes the textures due already), the fork's change of `Step::Texture`'s payload (the upload is held beside it instead, so the steps' other readers, `card_steps` and `place`, are untouched), and its panel change (unrelated). Off by default (not behaviour-neutral: when textures are uploaded changes). Tests (from the fork): a claim per change, in the same submission; a ring of three buffers never shows an older picture. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 81 +++++++++++- crates/victory-gpu/src/resource.rs | 1 + crates/victory-gpu/src/texture.rs | 194 +++++++++++++++++++++++++++++ 3 files changed, 272 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 82bf19d..915d2ad 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2333,6 +2333,9 @@ struct Deferred { uploads: Vec, /// Standalone upload footprints kept through this list's fence (movie planes). plane_uploads: Vec<(Chunk, u64)>, + /// Title textures whose upload the list's prelude records if the check at + /// submission finds it due (`crate::texture::prelude_uploads`). + prelude_uploads: Vec, /// The bytes of `uploads` (counted in [`ALIVE`] while they are held). upload_bytes: u64, /// Host objects the list's commands name (pipelines, root signatures, @@ -5757,7 +5760,9 @@ impl Host { for list in runs { list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i))); firsts.push(lists.len()); - if let Some(prelude) = list.prelude() { + // (None unless `VICTORY_PRELUDE_UPLOADS=1`.) + let uploads = list.prelude_uploads(&mut batch); + if let Some(prelude) = list.prelude(&uploads) { lists.push(Some(prelude)); } lists.push(list.list.cast().ok()); @@ -6819,8 +6824,12 @@ impl HostList { /// its real state to the one the list starts with; the textures' real /// states become those the list ends with. For depth textures with a /// colour twin it first copies the side the list uses as it finds it - /// from the other, if a list submitted earlier left it behind. - fn prelude(&self) -> Option { + /// from the other, if a list submitted earlier left it behind. Title + /// textures whose upload is decided at submission (`uploads`, + /// `crate::texture::prelude_uploads`) are copied into their host copies + /// here, right before the list runs (Belobug/VIctory-Belobug-AMD + /// 5d6bd84). + fn prelude(&self, uploads: &[(crate::texture::PreludeUpload, bool)]) -> Option { const COPY_DEST: u32 = 0x400; const COPY_SOURCE: u32 = 0x800; let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32); @@ -6875,13 +6884,45 @@ impl HostList { } } } + // The uploads decided at submission: each host copy to the copy + // destination state, and from there to the state the list starts + // with (back to its real state if the list does not use it). + let mut aliasing = Vec::new(); + for (upload, first_upload) in uploads { + let copy = &upload.copy; + let key = std::sync::Arc::as_ptr(copy) as usize; + // A texture cut from a block may lie where another did: what the + // card holds of that one is done with before the first upload + // into this one. + if crate::pool::on() && *first_upload { + aliasing.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::ManuallyDrop::new(None), + // SAFETY: a borrowed pointer the barrier never releases. + pResourceAfter: unsafe { std::mem::transmute_copy(©.texture) }, + }), + }, + }); + } + let real = copying.get(&key).copied().unwrap_or_else(|| copy.state.load(Ordering::Relaxed)); + if real != COPY_DEST { + to_copy.push(transition(©.texture, host_state(real), host_state(COPY_DEST))); + if !states.contains_key(&key) { + barriers.push(transition(©.texture, host_state(COPY_DEST), host_state(real))); + } + } + copying.insert(key, COPY_DEST); + } barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| { let real = copy.state.swap(*last, Ordering::Relaxed); let real = copying.get(key).copied().unwrap_or(real); (real != *first) .then(|| transition(©.texture, host_state(real), host_state(*first))) })); - if barriers.is_empty() && syncs.is_empty() { + if barriers.is_empty() && syncs.is_empty() && uploads.is_empty() { return None; } let Some((allocator, list)) = self @@ -6896,12 +6937,18 @@ impl HostList { let recorded = unsafe { allocator.Reset().and_then(|()| { list.Reset(allocator, None)?; + if !aliasing.is_empty() { + list.ResourceBarrier(&aliasing); + } if !to_copy.is_empty() { list.ResourceBarrier(&to_copy); } for (depth, twin, colour) in &syncs { record_twin_copy(list, &depth.texture, twin, *colour); } + for (upload, _) in uploads { + upload.record(list); + } if !barriers.is_empty() { list.ResourceBarrier(&barriers); } @@ -7476,6 +7523,32 @@ impl HostList { self.deferred().copies.push(Step::Texture(staging)); } + /// [`HostList::defer_texture`] of a texture whose upload the list's + /// prelude records if the check finds it due + /// (`crate::texture::prelude_uploads`; [`HostList::prelude_uploads`]). + pub(crate) fn defer_prelude_upload(&self, upload: crate::texture::PreludeUpload) { + let mut deferred = self.deferred(); + deferred.copies.push(Step::Texture(upload.staging())); + deferred.prelude_uploads.push(upload); + } + + /// At submission, after the list's steps: the textures whose upload its + /// prelude records, each with whether it is the first upload into its + /// host copy. Their staging buffers are refreshed first (those the + /// submission's steps left pending). Ported from + /// Belobug/VIctory-Belobug-AMD 5d6bd84. + fn prelude_uploads(&self, batch: &mut Batch) -> Vec<(crate::texture::PreludeUpload, bool)> { + let waiting = self.deferred().prelude_uploads.clone(); + if waiting.is_empty() { + return Vec::new(); + } + batch.refresh_textures(); + waiting + .into_iter() + .filter_map(|upload| upload.finish_refresh().map(|first| (upload, first))) + .collect() + } + /// A copy source owned exclusively by this list until reset after its /// last execution. A different list can prepare its movie plane concurrently. pub(crate) fn plane_upload( diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index d3d0717..ab2931a 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2804,6 +2804,7 @@ pub(crate) fn first_shown(this: This) -> Option { /// A host copy made without memory of its own (`crate::tiles`), as a /// submission-time step of a list holds it. #[cfg(windows)] +#[derive(Clone)] pub(crate) struct OnDemand(std::sync::Arc); // SAFETY: the host texture is named only in queue calls, which any thread diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 601cdcb..17955a1 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -857,6 +857,21 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { staging.uploaded.store(true, Relaxed); return; } + // With `VICTORY_PRELUDE_UPLOADS=1`: whether to upload is decided when + // the list is submitted, after the check that refreshes the staging + // buffer, and the copy goes on the list's prelude ([`PreludeUpload`]). + if prelude_uploads() && !baking { + if no_wait() && fill_unlocked() { + let there = match picking { + Some(there) if there != u64::MAX => there, + _ => mapped_bytes(staging.memory, staging.read), + }; + staging.expected.store(there, Relaxed); + } + let on_demand = if staging.on_demand { crate::resource::host_tiled(resource) } else { None }; + list.defer_prelude_upload(PreludeUpload { staging, copy, on_demand }); + return; + } // The host texture has the staging buffer's contents: only the check // at submission is left, and what it finds changed the next list that // samples the texture uploads (a frame late where every list of the @@ -922,6 +937,129 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { }); } +/// Whether title textures that lists sample are uploaded on each list's +/// prelude at submission, when the check that refreshes the staging buffer +/// has run, if it changed or was never uploaded (`VICTORY_PRELUDE_UPLOADS=1`; +/// off: the list records the upload when it samples the texture, if the +/// staging buffer was changed then, as before; bakes and movie planes keep +/// that either way). +/// +/// Ported from Belobug/VIctory-Belobug-AMD 5d6bd84 ("Upload title textures +/// in submission prelude to fix frame-order & flickering"), where it is the +/// only way. Recorded when the list samples a texture, an upload is left out +/// if the staging buffer held what the host copy holds at that moment; the +/// check at submission may then find the memory changed and detile it, and +/// only the next list that samples the texture uploads that: a frame late +/// when every list of the frame was recorded before the check (a ring of +/// video buffers then shows an old picture, a texture streamed in shows the +/// last one for a frame). Decided at submission, the copy takes what the +/// check found, in the submission that samples it. A candidate of the +/// flicker at scene loads (analysis 6.12). +pub(crate) fn prelude_uploads() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PRELUDE_UPLOADS").is_some_and(|v| v == "1")) +} + +/// Whether the prelude of the list being submitted records the upload into +/// a host texture ([`PreludeUpload::finish_refresh`]): `Some(first upload)` +/// when it was never uploaded or its staging buffer was detiled since the +/// last upload; `None` when the host texture holds what the staging buffer +/// holds. (Ported from Belobug/VIctory-Belobug-AMD 5d6bd84.) +fn claim_upload(uploaded: &std::sync::atomic::AtomicBool, dirty: &std::sync::atomic::AtomicBool) -> Option { + use std::sync::atomic::Ordering::AcqRel; + let was_uploaded = uploaded.swap(true, AcqRel); + let was_dirty = dirty.swap(false, AcqRel); + (!was_uploaded || was_dirty).then_some(!was_uploaded) +} + +/// A title texture a list samples, its upload decided at the list's +/// submission ([`prelude_uploads`]): its staging buffer, its host copy (both +/// held by the list until it is reset), and its levels on demand. (Ported +/// from Belobug/VIctory-Belobug-AMD 5d6bd84, without its texture store's +/// prefill, which this tree does not have.) +#[derive(Clone)] +pub(crate) struct PreludeUpload { + staging: Arc, + pub(crate) copy: Arc, + on_demand: Option, +} + +impl PreludeUpload { + /// The staging buffer, for the submission's check (`Step::Texture`). + pub(crate) fn staging(&self) -> Arc { + self.staging.clone() + } + + /// On the submitting thread, once the check that refreshes the staging + /// buffer has run for this submission: `Some(first upload)` if the + /// list's prelude records the copy into the host texture, with what the + /// list's own upload noted when it was recorded (a host copy grown, the + /// levels on demand given memory, what the host copy holds). + pub(crate) fn finish_refresh(&self) -> Option { + use std::sync::atomic::Ordering::Relaxed; + let Some(first_upload) = claim_upload(&self.staging.uploaded, &self.staging.dirty) else { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexSkipped, 1); + return None; + }; + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexUploads, 1); + // A host copy that took the place of one with fewer levels: the slots + // that show that one are made again once this upload has run. + if self.staging.first == self.staging.level0 && self.copy.grown.swap(false, Relaxed) { + crate::descriptor::host::levels_changed_after(self.staging.memory as u64); + } + // Levels on demand (`crate::tiles`): the held levels the staging + // buffer holds as the title's are given the card's memory before the + // prelude copies into them; else what the host copy now holds is + // noted. + match &self.on_demand { + Some(on_demand) => { + let waiting = on_demand.uploaded(self.staging.detiled.load(Relaxed), self.staging.memory as u64); + self.staging.waiting.store(if waiting { crate::host::moment().max(1) } else { 0 }, Relaxed); + // A texture picked by index has no staging buffer after this + // upload: its slots are made due again by the texture pass. + if waiting { + crate::descriptor::host::levels_waiting(self.staging.memory as u64); + } + } + None => self.staging.note_held(), + } + Some(first_upload) + } + + /// Records the copy of the staging buffer into the host texture on + /// `list` (the prelude), the host texture in the copy destination state. + pub(crate) fn record(&self, list: &ID3D12GraphicsCommandList) { + let texture = &self.copy.texture; + // The staging buffer lives as long as `self.staging`, which the + // list's steps hold until it is reset. + for (i, footprint) in self.staging.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: self.staging.first - self.staging.level0 + i as u32, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(&self.staging.buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: self.staging.base + footprint.Offset, + ..*footprint + }, + }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + } +} + fn record_upload( list: &HostList, resource: This, @@ -2226,6 +2364,62 @@ mod title_memory_tests { } } +/// [`claim_upload`] (ported from Belobug/VIctory-Belobug-AMD 5d6bd84). +#[cfg(test)] +mod prelude_upload_tests { + use super::claim_upload; + use std::sync::atomic::{AtomicBool, Ordering::Release}; + + /// The first upload is claimed, a second list of the submission skips, + /// an unchanged texture skips, a changed one is claimed in the same + /// submission, every time it changes. + #[test] + fn first_upload_clean_skip_and_immediate_same_frame_reupload() { + let uploaded = AtomicBool::new(false); + let dirty = AtomicBool::new(true); + assert_eq!(claim_upload(&uploaded, &dirty), Some(true)); + assert_eq!(claim_upload(&uploaded, &dirty), None); + assert_eq!(claim_upload(&uploaded, &dirty), None); + dirty.store(true, Release); + assert_eq!(claim_upload(&uploaded, &dirty), Some(false)); + dirty.store(true, Release); + assert_eq!(claim_upload(&uploaded, &dirty), Some(false)); + } + + /// A ring of three buffers written in turn (a video's) never shows a + /// picture older than the one its buffer holds, a held picture + /// included. + #[test] + fn three_buffer_ring_never_displays_stale_frame() { + let ring: [(AtomicBool, AtomicBool); 3] = std::array::from_fn(|_| (AtomicBool::new(false), AtomicBool::new(true))); + let mut shown = [0u32; 3]; + let schedule = [ + (0, 1, true), + (1, 2, true), + (2, 3, true), + (0, 4, true), + (1, 5, true), + (1, 5, false), + (2, 6, true), + (0, 7, true), + (1, 8, true), + (2, 9, true), + (0, 10, true), + (1, 11, true), + ]; + for (slot, picture, changed) in schedule { + let (uploaded, dirty) = &ring[slot]; + if changed { + dirty.store(true, Release); + } + if claim_upload(uploaded, dirty).is_some() { + shown[slot] = picture; + } + assert_eq!(shown[slot], picture, "slot {slot} shows picture {} instead of {picture}", shown[slot]); + } + } +} + /// How long this PC's card takes to make the allocations a staged texture needs, for /// `cargo test -p victory-gpu allocation_costs -- --ignored --nocapture`. #[cfg(test)]