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/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..88bc419 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 @@ -292,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. @@ -908,9 +959,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 @@ -920,6 +972,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 { @@ -943,6 +1017,116 @@ 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); + }); +} + +/// 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). @@ -954,9 +1138,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 +1174,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 @@ -1014,32 +1221,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)); @@ -1050,7 +1290,8 @@ impl Due { } } order.truncate(max); - order + known.resize(order.len(), None); + (order, known) } } @@ -1063,7 +1304,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 +1382,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 +1920,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 +1948,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(), @@ -1804,20 +2047,66 @@ 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 } + } + + /// 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 @@ -1899,15 +2188,65 @@ 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().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) } + /// 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) { - 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 +2256,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 +2270,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 +2290,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 +2349,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 +2374,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 +2434,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 +2455,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 +2545,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); } @@ -2563,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 { @@ -2685,6 +3033,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; @@ -2701,14 +3054,35 @@ impl HostHeap { if old != now | TABLED_READ { stamp.store(now | TABLED_READ, Relaxed); if tabled_out() { - let mut textures = self.queue(); - if textures.slots.remove(&index).is_some() { + // 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.take_out(index) { 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). @@ -2737,8 +3111,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 mut textures = self.queue(); - if texture && !read_now { + 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 keeps { let due = if lately && !seen { TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); frame + TABLED_GRACE @@ -2799,7 +3187,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, }; @@ -2846,9 +3239,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(); - 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); @@ -3415,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" }); @@ -3474,7 +3914,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!( @@ -5797,6 +6237,167 @@ 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(&[])); + } + + /// 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. + #[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. + #[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] diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 289e9df..7b140d8 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -968,6 +968,116 @@ 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 +/// 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 +3093,53 @@ 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 }); + // (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 { - 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 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, 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); for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { @@ -3097,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); @@ -3130,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; } @@ -3181,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)); @@ -3193,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) { @@ -3211,7 +3339,8 @@ impl State { && !crate::resource::title_fills(object as This) { outcome(slot_outcome::NOTHING); - rest(0, || host.texture_slot_done(index, write, None)); + HEAP_TEXTURE_NOTHING[0].fetch_add(1, Ordering::Relaxed); + tells.tell(index, write, Told::Done(None)); continue; } // From here on a host texture is made: not without room. The @@ -3237,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; } @@ -3283,16 +3412,19 @@ 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) } }); - 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,9 +3437,10 @@ 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); - rest(0, || host.texture_slot_done(index, write, None)); + HEAP_TEXTURE_NOTHING[1].fetch_add(1, Ordering::Relaxed); + tells.tell(index, write, Told::Done(None)); continue; } }; @@ -3318,10 +3451,11 @@ 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); - rest(0, || host.texture_slot_done(index, write, None)); + HEAP_TEXTURE_NOTHING[2].fetch_add(1, Ordering::Relaxed); + tells.tell(index, write, Told::Done(None)); continue; } // A texture that has a staging buffer now is one draws read @@ -3344,17 +3478,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)); @@ -3362,11 +3496,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; } @@ -3422,10 +3554,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() @@ -3474,7 +3606,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; @@ -3496,14 +3628,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); } @@ -4286,9 +4418,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 42400ee..3a87b53 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2336,6 +2336,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, @@ -5765,7 +5768,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()); @@ -6828,8 +6833,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); @@ -6884,13 +6893,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 @@ -6905,12 +6946,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); } @@ -7501,6 +7548,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( @@ -9195,6 +9268,75 @@ 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), + ); + } + 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; + 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); since the start, {} slots \ + 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], + 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], + crate::descriptor::host::TABLED_WRITES[2].load(Ordering::Relaxed), + crate::descriptor::host::HOST_TEXTURES_LEFT_OUT.load(Ordering::Relaxed), + ); + } } if crate::resource::held_only() { let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed)); diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index cde4cdb..aadc34d 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()); @@ -471,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. @@ -508,10 +651,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 +699,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)); 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)]