diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 09d6d93546..068cb3b8d9 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3995,7 +3995,20 @@ impl State { let memory = if again.is_none() && heap_recheck() { crate::texture::staged_memory(resource) } else { None }; memory.map(|(at, len)| (at, len, crate::texture::fingerprint(at, len))) }); - rest(6, || crate::texture::unstage(resource)); + let staged = rest(6, || crate::texture::unstage(resource)); + // Read by threads of ours from here, after the fingerprint for + // the later look ([`crate::texture::ahead::read_ahead`]): not a + // bake's, not one taken ahead, not one looked at again by + // mapped bytes alone. + if let Some(staging) = staged + && crate::texture::ahead::read_ahead() + && ahead.is_none() + && sync.is_none() + && !baking + && memory.is_some() + { + crate::texture::ahead::read_soon(staging); + } SPENT.fetch_add(bytes, Ordering::Relaxed); since_asked += bytes; if first_upload || (room && since_asked >= 32 << 20) { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 276173b4c4..082745ed44 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -10357,6 +10357,8 @@ impl Meter { modes.join(", ") ); } + crate::texture::look_once_line(frames); + crate::texture::ahead::read_ahead_line(frames); let [through, left, filled, short] = [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); if through + left + filled > 0.0 { @@ -10474,6 +10476,7 @@ impl Meter { crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20 ); } + crate::texture::staging_zeros_line(); let served = crate::descriptor::host::SERVED.each_ref().map(|n| n.swap(0, Ordering::Relaxed)); if served[0] + served[3] > 0 { tracing::info!( @@ -10644,7 +10647,8 @@ impl Meter { tracing::info!( "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \ {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \ - ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)", + ({:.1} MB) with {:.1} more waits for the card ({:.1} ms); title buffer copies done on the CPU \ + looked for among them {:.1} times ({:.2} ms), {:.1} copies found (VICTORY_SEND_COPIED_FIND)", card[7], card[8] >> 20, card[9] >> 20, @@ -10654,7 +10658,10 @@ impl Meter { per_frame(3), per_frame(4) / 1e6, per_frame(5), - per_frame(6) / 1e3 + per_frame(6) / 1e3, + per_frame(10), + per_frame(11) / 1e6, + per_frame(12) ); } let [raw_srv, raw_uav] = crate::descriptor::host::raw_view_counts(); diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 41ba271d60..d20bf097a3 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -518,6 +518,36 @@ fn shared_budget() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_SHARED").is_none_or(|v| v != "0")) } +/// `VICTORY_PIPELINE_WAIT_BACKLOG=n` (read once, unset by default): past +/// `n` pipelines queued, a draw's pipeline is not waited for at all and the +/// draw is dropped at once, as it is when the budget runs out; it is drawn +/// again in a later frame. Unset, every draw waits as before. +/// +/// With more queued than the workers can make within the budget, the +/// pipeline asked for here will not arrive in time, and waiting only costs +/// the frame (Kemerd/VIctory-NVIDIA-RT rt-test-11, 0549d44c, GPL-3.0: a run +/// spent the whole 500 ms in every frame for two minutes while 470 were +/// queued; another sat at 3 fps with 600 queued). Only graphics: passes over +/// the screen keep their own budget, and a dispatch is never dropped here +/// (it waits unless `VICTORY_PIPELINE_COMPUTE_WAIT=0`, and not by this rule +/// even then). docs/KEMERD-AUDIT.md. +fn backlog() -> Option { + static MOST: OnceLock> = OnceLock::new(); + *MOST.get_or_init(|| { + let most = std::env::var("VICTORY_PIPELINE_WAIT_BACKLOG").ok().and_then(|v| v.trim().parse::().ok()); + if let Some(most) = most { + tracing::info!(most, "host pipelines are not waited for while more than this many are queued"); + } + most + }) +} + +/// Whether a draw's wait is left out for the backlog ([`backlog`]): more +/// than `most` queued. +fn over_backlog(most: Option, queued: u64) -> bool { + most.is_some_and(|most| queued > most) +} + /// Waits for `p` while frame `frame` has budget left. fn wait(p: &Pending, frame: u64) { let screen = p.screen && screens_first(); @@ -525,6 +555,9 @@ fn wait(p: &Pending, frame: u64) { if budget.is_zero() { return; } + if !screen && p.graphics.is_some() && over_backlog(backlog(), WAITING.load(Ordering::Relaxed)) { + return; + } // The frame the budget belongs to, and what was waited of it (or is // taken by a thread waiting now); of the passes over the screen too. static SPENT: [Mutex<(u64, Duration)>; 2] = [const { Mutex::new((u64::MAX, Duration::ZERO)) }; 2]; @@ -829,6 +862,18 @@ fn drained() { #[cfg(test)] mod tests { + /// [`super::over_backlog`]: unset never skips; set, only more queued than + /// asked skips. + #[test] + fn a_wait_is_left_out_only_past_the_backlog() { + use super::over_backlog; + assert!(!over_backlog(None, u64::MAX)); + assert!(!over_backlog(Some(64), 0)); + assert!(!over_backlog(Some(64), 64)); + assert!(over_backlog(Some(64), 65)); + assert!(over_backlog(Some(0), 1)); + } + use super::*; #[test] diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 93d92ae68c..2588776070 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -653,9 +653,33 @@ impl Drop for StagingPiece { } } -/// `bytes` of upload memory, all zeros: the buffer it lies in, where in -/// that buffer, and its mapping. `None`: not pooled. -pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPiece, ID3D12Resource, u64, *mut u8)> { +/// Whether a staging piece the detiling is known to write whole may be +/// handed out as it is, its zeros left to the detiling or to a fill where +/// a copy from it is recorded (`VICTORY_STAGING_NO_ZERO=1`, off by +/// default; see `crate::texture::Staging::zero_if_unwritten`). Without it +/// every piece cut from a part of a block used before is zero-filled when +/// it is handed out, and the detiling then writes the same bytes again: +/// upload memory written twice per texture byte, on the thread that makes +/// the staging buffer. It saves thread time of the texture pass and bytes +/// written, not frame time: judge it by microseconds per upload. +/// +/// Ported from Kemerd/VIctory-NVIDIA-RT `rt-test-11` +/// (0549d44c330bf0a1f808f8b012d8e22168dfad91), GPL-3.0; docs/KEMERD-AUDIT.md. +pub(crate) fn no_zero() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_STAGING_NO_ZERO").is_some_and(|v| v == "1")) +} + +/// `bytes` of upload memory: the buffer it lies in, where in that buffer, +/// its mapping, and whether the piece was used before. All zeros, unless +/// `leave` and it was used before ([`no_zero`]): then it holds what it held, +/// and the caller sees to every byte a copy reads from it. `None`: not +/// pooled. +pub(crate) fn staging( + host: &crate::host::Host, + bytes: u64, + leave: bool, +) -> Option<(StagingPiece, ID3D12Resource, u64, *mut u8, bool)> { if !on() { return None; } @@ -676,13 +700,13 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi let owned = StagingPiece(piece); // SAFETY: the piece lies in the block's mapping. let data = unsafe { memory.1.add(piece.start as usize) }; - if again { + if again && !leave { // What is not detiled into it (an unmapped texture) uploads zeros, // as from a buffer of its own. // SAFETY: the piece is ours alone. unsafe { std::ptr::write_bytes(data, 0, bytes as usize) }; } - Some((owned, memory.0, piece.start, data)) + Some((owned, memory.0, piece.start, data, again)) } /// An object the host texture holds and releases when it goes: its piece @@ -1615,12 +1639,12 @@ mod tests { let stop = std::sync::atomic::AtomicBool::new(false); let mut ms = Vec::new(); let mut keep = Vec::new(); - keep.extend(staging(host, 64 << 10)); + keep.extend(staging(host, 64 << 10, false)); std::thread::scope(|s| { s.spawn(|| { let mut held = std::collections::VecDeque::new(); while !stop.load(Ordering::Relaxed) { - held.extend(staging(host, 8 << 20)); + held.extend(staging(host, 8 << 20, false)); if held.len() > 64 { held.pop_front(); } @@ -1629,7 +1653,7 @@ mod tests { std::thread::sleep(std::time::Duration::from_millis(100)); for _ in 0..1000 { let began = std::time::Instant::now(); - keep.extend(staging(host, 64 << 10)); + keep.extend(staging(host, 64 << 10, false)); ms.push(began.elapsed().as_secs_f64() * 1e3); } stop.store(true, Ordering::Relaxed); @@ -1710,16 +1734,16 @@ mod tests { for t in 0..8u8 { s.spawn(move || { // 8 of 8 MiB a thread: 64 MiB each, so new blocks are made. - let pieces: Vec<_> = (0..8).filter_map(|_| staging(host, BYTES as u64)).collect(); + let pieces: Vec<_> = (0..8).filter_map(|_| staging(host, BYTES as u64, false)).collect(); assert_eq!(pieces.len(), 8); - for (_, _, _, data) in &pieces { + for (_, _, _, data, _) in &pieces { // SAFETY: the piece's mapping, ours alone. unsafe { assert!(looked(*data).all(|b| b == 0), "a piece is not zeros"); std::ptr::write_bytes(*data, t + 1, BYTES); } } - for (_, _, _, data) in &pieces { + for (_, _, _, data, _) in &pieces { assert!(looked(*data).all(|b| b == t + 1), "another thread wrote this piece"); } }); @@ -1754,13 +1778,22 @@ mod tests { assert_eq!(resting(), before + 1); // SAFETY: the piece's mapping, 4096 bytes of it ours. unsafe { - let (piece, _, at, data) = staging(host, 4096).unwrap(); + let (piece, _, at, data, _) = staging(host, 4096, false).unwrap(); assert!(at.is_multiple_of(512)); std::ptr::write_bytes(data, 0xAB, 4096); drop(piece); lock(&STAGING).rested(u64::MAX); - let (_piece, _, _, data) = staging(host, 4096).unwrap(); + let (piece, _, _, data, again) = staging(host, 4096, false).unwrap(); + assert!(again); assert!((0..4096).all(|i| *data.add(i) == 0)); + // Left as it was (`VICTORY_STAGING_NO_ZERO`): what it held, and + // said to have been used before. + std::ptr::write_bytes(data, 0xCD, 4096); + drop(piece); + lock(&STAGING).rested(u64::MAX); + let (_piece, _, _, data, again) = staging(host, 4096, true).unwrap(); + assert!(again); + assert!((0..4096).all(|i| *data.add(i) == 0xCD)); // SAFETY: plain query. assert!(host.device.GetDeviceRemovedReason().is_ok()); } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 215be62bf4..bbe84219d5 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -325,8 +325,60 @@ pub(crate) fn card_room_kept() -> u64 { card_limits().1.min(SEEN).saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed)) } -/// The copies in the card's memory. -static CARDED: Mutex>> = Mutex::new(Vec::new()); +/// The copies in the card's memory, and with [`find_copied`] the same +/// copies by where they start, behind the one lock. +static CARDED: Mutex = Mutex::new(Carded { list: Vec::new(), by_start: BTreeMap::new(), longest: 0 }); + +/// What [`CARDED`] holds. +struct Carded { + list: Vec>, + /// With [`find_copied`]: every copy of `list` by (start, [`Shadow::id`]) + /// (two live copies can start at one address: a tail and a window of + /// the loose copies, a window around a small buffer beside the buffer's + /// own copy, a buffer made again while lists hold the old copy), with + /// where it ends. Empty without the switch. + by_start: BTreeMap<(usize, u64), (usize, std::sync::Weak)>, + /// The longest copy `by_start` ever held: a copy that reaches into an + /// address starts at most so far below it. Never shrinks. + longest: usize, +} + +/// Whether [`send_copied`] finds the copies a title buffer copy touches by +/// where they start (`VICTORY_SEND_COPIED_FIND=1`, off by default), not by +/// upgrading every copy in the card's memory and testing its span: 4,029 +/// copies in the frame of the complaint, of which one or two hold a given +/// destination, and most such copies go to memory no copy holds. +/// +/// It is thread time of the submitting thread, which does every title +/// buffer copy recorded on the CPU: about 0.5 ms a frame at 15 copies and +/// 3 ms at 100, by a bench of the same loop outside the tree (34 us a call +/// over 4,029 copies, warm). No measurable change of a streaming frame is +/// to be expected while that thread stands waiting for translation. The +/// line of the card's copies says what the look costs, in both states. +fn find_copied() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SEND_COPIED_FIND").is_some_and(|v| v == "1")) +} + +/// Of `by_start` (copies by (start, id), each with its end), those that hold +/// some of `[dst, dst + len)`: a copy that does starts below `dst + len` +/// and, being at most `longest` long, at or above `dst - longest`. +fn overlapping( + by_start: &BTreeMap<(usize, u64), (usize, V)>, + longest: usize, + dst: usize, + len: usize, +) -> impl Iterator { + let end = dst.saturating_add(len); + by_start + .range((dst.saturating_sub(longest), 0)..(end, 0)) + .filter(move |&(&(start, _), &(stop, _))| start < end && stop > dst) + .map(|(&(_, id), (_, v))| (id, v)) +} + +/// Since the last frame line, [`send_copied`]'s calls, its nanoseconds and +/// the copies it found holding the destination. +pub(crate) static SEND_COPIED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; /// The copies in the card's memory whose `touched` was set since /// [`card_dirty`] last took them (a copy may be on it twice). Before, each @@ -344,10 +396,18 @@ fn carded(shadow: &Arc) { }; let _ = card.me.set(Arc::downgrade(shadow)); let mut carded = CARDED.lock().unwrap_or_else(|e| e.into_inner()); - carded.push(Arc::downgrade(shadow)); - if carded.len() >= 2 * KEPT.load(Ordering::Relaxed).max(1024) { - carded.retain(|weak| weak.strong_count() > 0); - KEPT.store(carded.len(), Ordering::Relaxed); + let carded = &mut *carded; + carded.list.push(Arc::downgrade(shadow)); + if find_copied() { + // (Start and length are set once, when the copy is made.) + let (start, len) = (shadow.start as usize, shadow.len as usize); + carded.by_start.insert((start, shadow.id), (start + len, Arc::downgrade(shadow))); + carded.longest = carded.longest.max(len); + } + if carded.list.len() >= 2 * KEPT.load(Ordering::Relaxed).max(1024) { + carded.list.retain(|weak| weak.strong_count() > 0); + carded.by_start.retain(|_, (_, weak)| weak.strong_count() > 0); + KEPT.store(carded.list.len(), Ordering::Relaxed); } } @@ -363,13 +423,16 @@ pub(crate) fn live_span_bytes() -> u64 { } /// [`CARD_STATS`], taken; then the copies in the card's memory, their -/// bytes and their "before" twins' bytes. -pub(crate) fn card_stats() -> [u64; 10] { - let mut out = [0u64; 10]; +/// bytes and their "before" twins' bytes; then [`SEND_COPIED`], taken. +pub(crate) fn card_stats() -> [u64; 13] { + let mut out = [0u64; 13]; for (i, stat) in CARD_STATS.iter().enumerate() { out[i] = stat.swap(0, Ordering::Relaxed); } - out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64; + for (i, stat) in SEND_COPIED.iter().enumerate() { + out[10 + i] = stat.swap(0, Ordering::Relaxed); + } + out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).list.iter().filter(|w| w.strong_count() > 0).count() as u64; out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed) + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed); @@ -790,23 +853,103 @@ pub(crate) fn copy_all(copies: Vec<(usize, usize, usize)>) { /// CPU side held the same before or not. Left out is what shaders in the air /// may be writing (such a copy waits for them, or is done on the card). pub(crate) fn send_copied(dst: usize, len: usize) { - for shadow in carded_copies() { + let started = std::time::Instant::now(); + // With the switch the copies are taken under the lock and dealt with + // after it: `carded` is called under the loose copies' and the buffers' + // locks, and the copies may be let go here. + let found = if find_copied() { + let carded = CARDED.lock().unwrap_or_else(|e| e.into_inner()); + let found: Vec> = + overlapping(&carded.by_start, carded.longest, dst, len).filter_map(|(_, weak)| weak.upgrade()).collect(); + // Both ways under one holding of the lock: a copy made between two + // looks would be a false alarm. The list's copies are upgraded here + // and compared after the lock is let go, so one whose last owner went + // meanwhile is not destroyed under it. + #[cfg(feature = "diagnostics")] + let end = dst.saturating_add(len); + #[cfg(feature = "diagnostics")] + let listed: Vec> = carded + .list + .iter() + .filter_map(std::sync::Weak::upgrade) + .filter(|s| (s.start as usize) < end && ((s.start + s.len) as usize) > dst) + .collect(); + drop(carded); + #[cfg(feature = "diagnostics")] + { + let fast: std::collections::BTreeSet = found.iter().map(|s| s.id).collect(); + let slow: std::collections::BTreeSet = listed.iter().map(|s| s.id).collect(); + static SAID: [std::sync::Once; 2] = [const { std::sync::Once::new() }; 2]; + if slow.difference(&fast).next().is_some() { + SAID[0].call_once(|| tracing::warn!(dst, len, "send_copied: the copies by start missed one the list holds")); + } + if fast.difference(&slow).next().is_some() { + SAID[1].call_once(|| tracing::warn!(dst, len, "send_copied: the copies by start found one the list does not hold")); + } + drop(listed); + } + found + } else { + carded_copies() + }; + // the look alone: the bytes of the copies found below are not its cost. + let looked = started.elapsed(); + let mut hits = 0; + for shadow in found { let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize); let (from, to) = (dst.max(start), (dst + len).min(end)); if from >= to { continue; } + hits += 1; let busy: Vec<(usize, usize)> = shadow.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().copied().filter(|&(a, b)| a < to && b > from).collect(); for (a, b) in outside(from, to, busy) { shadow.copy(a, b); } } + SEND_COPIED[0].fetch_add(1, Ordering::Relaxed); + SEND_COPIED[1].fetch_add(looked.as_nanos() as u64, Ordering::Relaxed); + SEND_COPIED[2].fetch_add(hits, Ordering::Relaxed); } /// The copies in the card's memory (diagnostics: `crate::host::upcheck`). pub(crate) fn carded_copies() -> Vec> { - CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter_map(std::sync::Weak::upgrade).collect() + CARDED.lock().unwrap_or_else(|e| e.into_inner()).list.iter().filter_map(std::sync::Weak::upgrade).collect() +} + +/// [`overlapping`]: the copies a title buffer copy touches, by their start. +#[cfg(test)] +mod overlapping_tests { + use super::overlapping; + use std::collections::BTreeMap; + + /// A copy that starts below and reaches in is found, one that ends at + /// the destination or starts at its end is not, two that start at one + /// address are both found, and a destination below the longest copy + /// does not wrap. + #[test] + fn finds_every_copy_that_holds_a_byte() { + let mut tree = BTreeMap::new(); + let mut add = |start: usize, len: usize, id: u64| { + tree.insert((start, id), (start + len, id)); + }; + add(0x1000, 0x800, 1); // ends exactly at 0x1800 + add(0x1400, 0x1000, 2); // starts below, reaches in + add(0x1800, 0x100, 3); // the same start as 4 + add(0x1800, 0x10, 4); + add(0x1900, 0x100, 5); // starts at the end + add(0x10, 0x20, 6); // far below + let longest = 0x1000; + let mut found: Vec = overlapping(&tree, longest, 0x1800, 0x100).map(|(id, _)| id).collect(); + found.sort_unstable(); + assert_eq!(found, [2, 3, 4]); + // Below the longest copy: the walk starts at 0. + let low: Vec = overlapping(&tree, longest, 0x20, 4).map(|(id, _)| id).collect(); + assert_eq!(low, [6]); + assert_eq!(overlapping(&tree, longest, 0x3000, 0x100).count(), 0); + assert_eq!(overlapping(&tree, longest, usize::MAX - 8, 0x100).count(), 0); + } } /// Ranges in order, those that overlap or touch as one. diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 7254d31f1d..41a1f44aab 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -101,6 +101,48 @@ pub(crate) struct Staging { /// (and the levels' mask and the pattern tables after them), and this /// what the card detiles them into and the list copies from. gpu: Option, + /// With `VICTORY_STAGING_NO_ZERO=1` ([`crate::pool::no_zero`]): the + /// piece was used before and was handed out as it was, and nothing has + /// written all of it since. The detiling clears it when it has written + /// every subresource; a copy recorded from the buffer while it is still + /// set zero-fills the buffer first ([`Staging::zero_if_unwritten`]). + unzeroed: std::sync::atomic::AtomicBool, +} + +/// Since the last pass line, with [`crate::pool::no_zero`]: staging pieces +/// handed out without their zero-fill, those zero-filled where a copy from +/// them was recorded (nothing had detiled them whole), and those +/// zero-filled when made because the detiling would not write all a copy +/// reads ([`detile_covers`]). +pub(crate) static STAGING_ZEROS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// The line of [`STAGING_ZEROS`], with the pass's 5-second lines. +pub(crate) fn staging_zeros_line() { + use std::sync::atomic::Ordering::Relaxed; + if !crate::pool::no_zero() { + return; + } + let [left, at_record, at_making] = [0, 1, 2].map(|i| STAGING_ZEROS[i].swap(0, Relaxed)); + if left + at_record + at_making > 0 { + tracing::info!( + "staging pieces used before, in the last 5 seconds (VICTORY_STAGING_NO_ZERO=1): {left} handed out without \ + their zero-fill, {at_record} of them zero-filled where a copy was recorded (nothing had detiled them whole), \ + {at_making} zero-filled when made (the detiling would not write all a copy reads)" + ); + } +} + +/// Whether detiling writes every byte the copies of a staging buffer read: +/// for each subresource, the level's (bytes a row, rows, depth) as the +/// detiling writes them (`victory_formats::texture::Layout::detile` writes +/// `width * element_bytes` bytes of each of `height` rows of each of `depth` +/// slices, or returns before writing), against the copy's (bytes a row, +/// rows, depth) from `GetCopyableFootprints`. A level the layout does not +/// have (`None`) covers nothing. +fn detile_covers(parts: impl IntoIterator, (u64, u32, u32))>) -> bool { + parts.into_iter().all(|(level, (row_bytes, rows, depth))| { + level.is_some_and(|(written, high, deep)| written >= row_bytes && high >= rows && deep >= depth) + }) } /// A texture's detiling on the card ([`Staging::gpu`]). @@ -171,6 +213,16 @@ struct Last { /// first checks, and after the hash found a change the guard had not /// seen ([`hot_textures`]). 0: not checked under the guard yet. hot_until: u64, + /// The frame a guarded texture was last read and digested whole in, as + /// the guard's check read it before the read ([`look_once`]). Noted + /// only where all of it was read: not for a partly mapped texture, a + /// first filling from the pages there, or a kernel read that failed. + looked: Option, + /// A refresh has run for this buffer, read or not. The read-ahead + /// threads ([`Staging::refresh_soon`]) leave a buffer that was tried: + /// the submission came first, and its copy may be in flight. (Kemerd + /// ef8f00c, GPL-3.0.) + tried: bool, } /// Frames a guarded texture is hashed at every check from its first check, @@ -468,6 +520,70 @@ pub(crate) static UNLOCKED: [std::sync::atomic::AtomicU64; 4] = [const { std::sy /// was not there). pub(crate) static EXACT_UNLOCKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// Whether a guarded texture the guard saw no write to is read and +/// digested at most once a frame (`VICTORY_TEXTURE_LOOK_ONCE=1`, off by +/// default). Without it such a texture, while it is hot or on its turn, is +/// read whole at every check: once per submission whose lists sample it, +/// and again after every step of that submission that writes title memory +/// (17-30 submissions a frame). With it, a check in the frame the texture +/// was last read whole in finds nothing to do. A write the guard saw is +/// read as before; exact refreshes (bakes) are never passed over. +/// +/// What it saves is time of the threads that refresh, not frame time: the +/// frame line's "textures" (the submitting thread's wall time) was 0.9 ms +/// of 24 in ordinary frames and 9.75 of 390 while the world streamed in +/// with ray tracing (logs of 2026-11-26), and in streaming the submitting +/// thread stands about 178 ms a frame waiting for translation. How much +/// the hashing of second looks is shows in [`look_once_line`] with the +/// switch off; if it is small the switch has nothing to give. +/// +/// The risk, said plainly: a texture written by a way the guard cannot see +/// (another view of its pages) between two samplings in one frame shows +/// the older bytes to the later one; written so every frame, it stays one +/// write behind for the later sampling as long as that goes on. A texture +/// that is not hot is still found within eight frames, as now. It relies +/// on the frame counter advancing, as the turns of [`Staging::refresh`] +/// already do. +fn look_once() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_LOOK_ONCE").is_some_and(|v| v == "1")) +} + +/// Since the last frame-rate line, guarded textures the guard saw no write +/// to that went to a read anyway (hot or on their turn) and their bytes; +/// of them, those that had been read whole in the same frame already and +/// their bytes; and with [`look_once`], those passed over for that and +/// their bytes. Kept whether the switch is on or not. +pub(crate) static LOOK_ONCE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + +/// Whether a texture last read whole in frame `looked` (`None`: not since +/// it was made or forgotten) was read whole in `frame` already. A frame +/// counter that moved on during the read makes the next look a first one. +fn looked_already(looked: Option, frame: u64) -> bool { + looked == Some(frame) +} + +/// The periodic line of [`LOOK_ONCE`], per frame (`frames` since the last). +pub(crate) fn look_once_line(frames: f64) { + use std::sync::atomic::Ordering::Relaxed; + if frames <= 0.0 { + return; + } + let [looks, bytes, again, again_bytes, skipped, skipped_bytes] = + [0, 1, 2, 3, 4, 5].map(|i| LOOK_ONCE[i].swap(0, Relaxed) as f64 / frames); + if looks + skipped > 0.0 { + tracing::info!( + "guarded textures read with no write told, per frame: {looks:.1} ({:.1} MB), of them {again:.1} ({:.1} MB) \ + read whole in the same frame already; {skipped:.1} ({:.1} MB) passed over for that \ + (VICTORY_TEXTURE_LOOK_ONCE=1: now {})", + bytes / 1e6, + again_bytes / 1e6, + skipped_bytes / 1e6, + if look_once() { "on" } else { "off" } + ); + } +} + /// Whether an exact refresh (the uploads before a bake, `BAKING`) that /// finds the runtime remapping title memory first reads the texture whole /// through the kernel, and waits for the remapping to end only if a page of @@ -1047,6 +1163,25 @@ fn claim_upload(uploaded: &std::sync::atomic::AtomicBool, dirty: &std::sync::ato (!was_uploaded || was_dirty).then_some(!was_uploaded) } +/// Notes a whole read of a guarded texture: the frame it was read in +/// ([`look_once`]) and, for a look the guard told no write of (`blind`: +/// whether it was a second look in its frame), the counts of [`LOOK_ONCE`]. +/// Called only where all of the texture was read, so the line counts reads +/// and not looks that went on to a throttle or a failed read. (Kemerd +/// ef8f00c, GPL-3.0.) +fn note_looked(last: &mut Last, looked: Option, blind: Option, size: usize) { + use std::sync::atomic::Ordering::Relaxed; + last.looked = looked; + if let Some(again) = blind { + LOOK_ONCE[0].fetch_add(1, Relaxed); + LOOK_ONCE[1].fetch_add(size as u64, Relaxed); + if again { + LOOK_ONCE[2].fetch_add(1, Relaxed); + LOOK_ONCE[3].fetch_add(size as u64, Relaxed); + } + } +} + /// 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 @@ -1118,6 +1253,12 @@ impl PreludeUpload { }; #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexUploads, 1); + // A piece handed out without its zeros that nothing detiled whole is + // zero-filled here, before the prelude is recorded under the list's + // states lock: `record` would make the submit thread wait for `last` + // there, with that lock held. A load and nothing more once the flag + // is clear. (Kemerd ef8f00c, GPL-3.0.) + self.staging.zero_if_unwritten(); // 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) { @@ -1145,6 +1286,8 @@ impl PreludeUpload { /// 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) { + // (Done in `finish_refresh` already; kept for any other caller.) + self.staging.zero_if_unwritten(); let texture = &self.copy.texture; // The staging buffer lives as long as `self.staging`, which the // list's steps hold until it is reset. @@ -1184,6 +1327,9 @@ fn record_upload( ) { use std::sync::atomic::Ordering::Relaxed; const COPY_DEST: u32 = 0x400; + // (Recorded before the check that detiles it: its zeros now, if it was + // handed out without them.) + staging.zero_if_unwritten(); // 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 !staging.uploaded.load(Relaxed) && crate::pool::is_pooled(texture) { @@ -1554,6 +1700,39 @@ impl Staging { preparing[3].fetch_add(read as u64, Relaxed); } + /// For the read-ahead threads ([`ahead::read_soon`]), on a thread of + /// theirs: the refresh the submission would do, only for a buffer read + /// once (no draw samples it through a table, which would ask the write + /// watch and guard its pages), not marked exact by a bake (that read + /// belongs to the submission) and not uploaded. None: held back by + /// those, or by a refresh that was tried and read nothing (a submission's: + /// its copy may be in flight, nothing is written to the buffer after it); + /// Some(false): it was filled already, the submission (or another list's) + /// came first; Some(true): read here. Decided and read under one hold of + /// `last`, so a submission cannot come between the look and the read. + pub(crate) fn refresh_soon(&self) -> Option { + use std::sync::atomic::Ordering::Relaxed; + if !self.once.load(Relaxed) || self.exact.load(Relaxed) || self.uploaded.load(Relaxed) { + return None; + } + let started = std::time::Instant::now(); + let _texture = crate::timeline::span("a texture's refresh"); + let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); + if last.hash.is_some() { + return Some(false); + } + if last.tried { + return None; + } + let read = self.refresh_locked(&mut last); + let elapsed = started.elapsed().as_micros() as u64; + REFRESH_WAITS[3].fetch_add(elapsed, Relaxed); + let preparing = &crate::host::PREPARING; + preparing[2].fetch_add(elapsed, Relaxed); + preparing[3].fetch_add(read as u64, Relaxed); + Some(read > 0) + } + fn movie_plane(&self) -> bool { use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UNORM; let desc = &self.layout.desc; @@ -1617,10 +1796,15 @@ impl Staging { } fn refresh_timed(&self) -> usize { + let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); + self.refresh_locked(&mut last) + } + + /// The refresh, `last` (this buffer's) held by the caller. + fn refresh_locked(&self, last: &mut Last) -> usize { let size = self.read; let start = self.memory as usize; - let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); - let last = &mut *last; + last.tried = true; let exact = self.exact.swap(false, std::sync::atomic::Ordering::Relaxed); let alone = self.once.load(std::sync::atomic::Ordering::Relaxed); if alone && !exact && last.hash.is_some() { @@ -1654,6 +1838,13 @@ impl Staging { static GUARD: std::sync::OnceLock = std::sync::OnceLock::new(); // The guard saw no write: a change the hash finds came another way. let mut blind = false; + // The frame the guard's check below read, noted in `last.looked` + // where the texture is then read whole ([`look_once`]). + let mut looked = None; + // With no write told: whether this look is a second one in its frame, + // counted on [`LOOK_ONCE`] only where the texture is then read whole + // ([`note_looked`]). + let mut blind_look = None; if !alone && *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) @@ -1674,6 +1865,19 @@ impl Staging { if !exact && unwritten && !turn && !hot { return 0; } + looked = Some(frame); + // Hot or on its turn with no write told: read whole at every + // such check today, possibly several times in one frame. + if !exact && unwritten { + use std::sync::atomic::Ordering::Relaxed; + let again = looked_already(last.looked, frame); + if again && look_once() { + LOOK_ONCE[4].fetch_add(1, Relaxed); + LOOK_ONCE[5].fetch_add(size as u64, Relaxed); + return 0; + } + blind_look = Some(again); + } blind = unwritten; } // A change the guard did not see: hashed at every check for a while. @@ -1719,13 +1923,13 @@ impl Staging { // texture is read through the kernel instead, whole or not at // all (`no_wait`). let Some(mapped) = crate::watch::title_memory_reading_now() else { - return self.refresh_unlocked(last, size); + return self.refresh_unlocked(last, size, looked, blind_look); }; mapped } else if exact && exact_unlocked() { match crate::watch::title_memory_reading_now() { Some(mapped) => mapped, - None => match self.refresh_exact_unlocked(last, size) { + None => match self.refresh_exact_unlocked(last, size, looked, blind_look) { Some(read) => { if read { found_blind(last); @@ -1782,6 +1986,7 @@ impl Staging { if through_copy() || !crate::watch::soft_runs(start, size).is_empty() { return with_title(self.memory, size, |tiled| { let hash = digest(tiled); + note_looked(last, looked, blind_look, size); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); if last.hash == Some(hash) { @@ -1799,6 +2004,7 @@ impl Staging { // stays committed while `_mapped` is held. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; let hash = digest(tiled); + note_looked(last, looked, blind_look, size); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); if last.hash == Some(hash) { @@ -1819,12 +2025,13 @@ impl Staging { /// next refresh (what was learnt about writes to it is forgotten, so /// that it is not passed over as unwritten); one never filled takes the /// pages that are there ([`Staging::fill`]). Returns the bytes read. - fn refresh_unlocked(&self, last: &mut Last, size: usize) -> usize { + fn refresh_unlocked(&self, last: &mut Last, size: usize, looked: Option, blind_look: Option) -> usize { use std::sync::atomic::Ordering::Relaxed; let read = with_read(size, |read| { if !crate::host::read_into(self.memory, read) { return false; } + note_looked(last, looked, blind_look, size); let hash = digest(read); if last.hash != Some(hash) { last.hash = Some(hash); @@ -1851,13 +2058,20 @@ impl Staging { /// lock would be. `Some(changed)` if read (and detiled if it changed), /// `None` if a page was missing: then the refresh waits for the lock /// as before. - fn refresh_exact_unlocked(&self, last: &mut Last, size: usize) -> Option { + fn refresh_exact_unlocked( + &self, + last: &mut Last, + size: usize, + looked: Option, + blind_look: Option, + ) -> Option { use std::sync::atomic::Ordering::Relaxed; let mut changed = false; let read = with_read(size, |read| { if !crate::host::read_into(self.memory, read) { return false; } + note_looked(last, looked, blind_look, size); let hash = digest(read); if last.hash != Some(hash) { last.hash = Some(hash); @@ -1991,6 +2205,9 @@ impl Staging { DETILED[1].fetch_add(size as u64, Relaxed); DETILED[2].fetch_add(1, Relaxed); let _timed = DetileTimed(started); + // (Never set without `VICTORY_STAGING_NO_ZERO`.) + let unzeroed = self.unzeroed.load(Relaxed); + let mut failed = false; for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { let (mip, slice) = self.part(i); let f = footprint.Footprint; @@ -2009,14 +2226,49 @@ impl Staging { linear.fill(0); continue; } + // A piece handed out as it was (`unzeroed`): after a failure + // this subresource and every later one are zeros, as a piece + // zero-filled when made would hold them. + if failed { + linear.fill(0); + continue; + } if let Err(e) = self.layout .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) { tracing::warn!(?e, mip, slice, "texture not detiled"); - return; + if !unzeroed { + return; + } + linear.fill(0); + failed = true; } } + // Every byte a copy reads is written now ([`detile_covers`]). + if unzeroed { + self.unzeroed.store(false, Relaxed); + } + } + + /// Where a copy from the staging buffer is recorded: a piece handed out + /// without its zero-fill that nothing has detiled whole (the texture's + /// memory was never mapped, or its read failed) is zero-filled now, as + /// it would have been when made, so the copy uploads zeros and not the + /// bytes of the texture that used the piece before. Under `last`'s + /// lock, as the detiling writes. + fn zero_if_unwritten(&self) { + use std::sync::atomic::Ordering::Relaxed; + if !self.unzeroed.load(Relaxed) { + return; + } + let _last = self.last.lock().unwrap_or_else(|e| e.into_inner()); + if self.unzeroed.swap(false, Relaxed) { + // SAFETY: the staging buffer's own bytes of its mapping, written + // only under `last`'s lock, which is held. + unsafe { std::ptr::write_bytes(self.data, 0, self.bytes as usize) }; + STAGING_ZEROS[1].fetch_add(1, Relaxed); + } } } @@ -2033,11 +2285,11 @@ impl Drop for DetileTimed { /// Lets go of a title texture's staging buffer (lists that recorded an /// upload from it hold it until they have run); the next upload makes one /// anew. -pub(crate) fn unstage(resource: This) { +/// Returns the buffer let go of: no later upload finds it, so its flags +/// change no more but by its own refresh ([`ahead::read_soon`]). +pub(crate) fn unstage(resource: This) -> Option> { let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(map) = map.as_mut() { - map.remove(&(resource as usize)); - } + map.as_mut()?.remove(&(resource as usize)) } /// Where a staged title texture's memory is: address and bytes. @@ -2424,6 +2676,9 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; let mut rows = vec![0u32; count as usize]; let mut total = 0; + // With `VICTORY_STAGING_NO_ZERO`, the bytes of each row a copy reads too. + let no_zero = crate::pool::no_zero(); + let mut row_bytes = if no_zero { vec![0u64; count as usize] } else { Vec::new() }; // SAFETY: outputs for `count` subresources. unsafe { host.device.GetCopyableFootprints( @@ -2433,10 +2688,24 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O 0, Some(footprints.as_mut_ptr()), Some(rows.as_mut_ptr()), - None, + if no_zero { Some(row_bytes.as_mut_ptr()) } else { None }, Some(&mut total), ); } + // A pooled piece may be handed out without its zero-fill only where + // the detiling writes all that the copies read; subresources counted + // as `Staging::part` counts them. + let leave = no_zero && { + let levels = mips - first; + detile_covers((0..count as usize).map(|i| { + let mip = first + i as u32 % levels; + let level = layout + .mips + .get(mip as usize) + .map(|m| (u64::from(m.width) * u64::from(layout.desc.element_bytes), m.height, m.depth)); + (level, (row_bytes[i], rows[i], footprints[i].Footprint.Depth)) + })) + }; // On the card's way (`VICTORY_GPU_DETILE`): the dispatches, if every // subresource can be detiled so, and the buffer they write. Only full // textures starting at mip 0 use the GPU path so `footprints` matches @@ -2459,9 +2728,14 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O None }; let upload_bytes = gpu.as_ref().map_or(total, |g| g.raw.bytes); - let pooled_piece = if gpu.is_some() { None } else { crate::pool::staging(host, upload_bytes) }; - let (piece, buffer, base, data) = match pooled_piece { - Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data), + let pooled_piece = if gpu.is_some() { None } else { crate::pool::staging(host, upload_bytes, leave) }; + let (piece, buffer, base, data, unzeroed) = match pooled_piece { + Some((piece, buffer, base, data, again)) => { + if no_zero && again { + STAGING_ZEROS[if leave { 0 } else { 2 }].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + (Some(piece), buffer, base, data, leave && again) + } None => { let speculative = PICKING.get().is_some() && !BAKING.get(); if crate::residency::upload_refused() @@ -2477,7 +2751,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O d.Width, d.Height, d.DepthOrArraySize, d.Format.0 ) }); - (None, buffer, 0, data) + (None, buffer, 0, data, false) } }; if let Some(gpu) = &gpu { @@ -2519,6 +2793,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O waiting: std::sync::atomic::AtomicU64::new(0), exact: std::sync::atomic::AtomicBool::new(BAKING.get()), gpu, + unzeroed: std::sync::atomic::AtomicBool::new(unzeroed), }); map.insert(resource as usize, s.clone()); Some(s) @@ -2661,6 +2936,24 @@ mod title_memory_tests { } } +/// [`looked_already`]: what `VICTORY_TEXTURE_LOOK_ONCE` passes over. +#[cfg(test)] +mod look_once_tests { + use super::{Last, looked_already}; + + /// A texture never read whole, or forgotten, is read at its first look + /// of a frame; one read whole in this frame is passed over; one read in + /// the frame before, or read while the counter moved on, is read again. + #[test] + fn only_a_second_look_in_the_same_frame_is_passed_over() { + assert!(!looked_already(Last::default().looked, 0)); + assert!(!looked_already(None, 7)); + assert!(looked_already(Some(7), 7)); + assert!(!looked_already(Some(6), 7)); + assert!(!looked_already(Some(7), 8)); + } +} + /// [`claim_upload`] (ported from Belobug/VIctory-Belobug-AMD 5d6bd84). #[cfg(test)] mod prelude_upload_tests { @@ -3002,3 +3295,26 @@ mod allocation_costs { } } } + +/// [`detile_covers`]: when a staging piece may keep what it held. +#[cfg(test)] +mod detile_covers_tests { + use super::detile_covers; + + #[test] + fn a_piece_is_left_only_where_the_detiling_writes_every_byte_read() { + // Equal rows, rows and slices: covered. + assert!(detile_covers([(Some((256, 16, 1)), (256, 16, 1)), (Some((128, 8, 1)), (128, 8, 1))])); + // The detiling writing more than the copy reads (a wider level than + // the footprint's rows) still covers. + assert!(detile_covers([(Some((272, 17, 1)), (256, 16, 1))])); + // A row more, fewer bytes a row, or fewer slices than the copy reads: not. + assert!(!detile_covers([(Some((256, 16, 1)), (256, 17, 1))])); + assert!(!detile_covers([(Some((240, 16, 1)), (256, 16, 1))])); + assert!(!detile_covers([(Some((256, 16, 4)), (256, 16, 8))])); + // A level the layout does not have covers nothing. + assert!(!detile_covers([(Some((256, 16, 1)), (256, 16, 1)), (None, (16, 1, 1))])); + // No subresources: nothing read. + assert!(detile_covers([])); + } +} diff --git a/crates/victory-gpu/src/texture/ahead.rs b/crates/victory-gpu/src/texture/ahead.rs index 0d741553aa..3998b3f49c 100644 --- a/crates/victory-gpu/src/texture/ahead.rs +++ b/crates/victory-gpu/src/texture/ahead.rs @@ -355,6 +355,121 @@ pub(crate) fn there(resource: This) -> bool { crate::resource::made_copy(resource).is_some_and(|copy| copy.ahead.load(Relaxed) == DONE) } +/// Whether a buffer staged for one upload of the texture pass is read by +/// threads of ours as soon as the pass lets go of it, not at the list's +/// submission (`VICTORY_TEXTURE_READ_AHEAD=1`, off by default; with it unset +/// nothing is queued and every such buffer is read at its submission, on +/// the wide threads, as before). +/// +/// Where the bytes are: title memory -> the staging buffer (an upload +/// heap, detiled) -> the texture on the card. No hop is added or repeated: +/// the read into the staging buffer moves from the submission to here, and +/// the submission's refresh of a filled buffer returns at once. Only for a +/// buffer the pass took a fingerprint of for a later look (a write between +/// this read and the submission shows there), not one of a bake (exact) +/// nor one a table draw keeps watched. The saving is an upper bound of +/// 12-20 ms a frame of the wide threads' time in ray-traced streaming, +/// 1-5 ms without (bakes' uploads not counted), and it is the submit +/// thread's time, while that thread mostly stands waiting for translation: +/// not frame time. On the frame line "textures" rises by what moves here +/// (refreshes in front no longer subtract it); "copies" and the refreshes' +/// flushes fall; "a texture picked by index changed after its upload" and +/// "waiting for a texture another thread is refreshing" must not rise. +pub(crate) fn read_ahead() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_READ_AHEAD").is_some_and(|v| v == "1")) +} + +/// Bytes of staging buffers queued for reading at most: past it a buffer +/// is read at its submission, as before. +const READ_MOST: u64 = 64 << 20; + +/// The buffers to read and their bytes; the two threads wait on it. +static READS: (Mutex<(VecDeque>, u64)>, Condvar) = (Mutex::new((VecDeque::new(), 0)), Condvar::new()); +/// Since the last line: buffers queued, read here, their MB in bytes, filled +/// first by a submission, held back by the guards, turned away full. +static READ_STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + +/// Queues `staging` for a read ahead of its submission ([`read_ahead`]), +/// on the pass's thread; never waits. Not queued when full, or when the +/// threads could not be started. +pub(crate) fn read_soon(staging: Arc) { + static STARTED: OnceLock = OnceLock::new(); + let started = *STARTED.get_or_init(|| { + (0..2).fold(false, |any, n| { + let spawned = std::thread::Builder::new().name(format!("textures read ahead {n}")).spawn(read_worker).is_ok(); + any | spawned + }) + }); + if !started { + return; + } + let bytes = staging.read as u64; + { + let mut reads = READS.0.lock().unwrap_or_else(|e| e.into_inner()); + if !fits(reads.1, bytes) { + READ_STATS[5].fetch_add(1, Relaxed); + return; + } + reads.1 += bytes; + reads.0.push_back(staging); + } + READ_STATS[0].fetch_add(1, Relaxed); + READS.1.notify_one(); +} + +/// Whether `bytes` more fit beside `queued` ([`READ_MOST`]). +fn fits(queued: u64, bytes: u64) -> bool { + queued.saturating_add(bytes) <= READ_MOST +} + +/// A thread of [`read_soon`]'s: reads one buffer at a time, under the +/// buffer's own lock, as the submission would. +fn read_worker() { + loop { + let staging = { + let mut reads = READS.0.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(staging) = reads.0.pop_front() { + reads.1 = reads.1.saturating_sub(staging.read as u64); + break staging; + } + reads = READS.1.wait(reads).unwrap_or_else(|e| e.into_inner()); + } + }; + match staging.refresh_soon() { + Some(true) => { + READ_STATS[1].fetch_add(1, Relaxed); + READ_STATS[2].fetch_add(staging.read as u64, Relaxed); + } + Some(false) => { + READ_STATS[3].fetch_add(1, Relaxed); + } + None => { + READ_STATS[4].fetch_add(1, Relaxed); + } + } + } +} + +/// The read-ahead numbers since the last line, per frame, with the switch. +pub(crate) fn read_ahead_line(frames: f64) { + if !read_ahead() || frames <= 0.0 { + return; + } + let [queued, read, bytes, first, held, full] = [0, 1, 2, 3, 4, 5].map(|i| READ_STATS[i].swap(0, Relaxed) as f64 / frames); + // like the lines next to it, say nothing in menus and quiet frames + if queued + read + first + held + full == 0.0 { + return; + } + tracing::info!( + "texture uploads of the lists read ahead of their submission (VICTORY_TEXTURE_READ_AHEAD=1), per frame: {queued:.1} queued, \ + {read:.1} read ahead ({:.1} MB), {first:.1} the submission filled first, {held:.1} held back (read once no more, exact \ + or uploaded), {full:.1} left to the submission with the queue full", + bytes / 1e6 + ); +} + /// The state of [`HostTexture::ahead`] of a new host copy. pub(crate) fn fresh() -> AtomicU8 { AtomicU8::new(NONE) @@ -364,6 +479,16 @@ pub(crate) fn fresh() -> AtomicU8 { mod tests { use super::*; + /// The queue for reads ahead holds at most its bytes; a buffer past + /// them is left to its submission. + #[test] + fn reads_ahead_fit_their_bound() { + assert!(fits(0, READ_MOST)); + assert!(fits(READ_MOST - 1, 1)); + assert!(!fits(READ_MOST, 1)); + assert!(!fits(1, u64::MAX)); + } + /// The texels of a placed texture arrive by the copy queue, all levels of /// them, and what waits for them is called then; a second asking finds the /// first on its way, and a later one is the list's. diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index 9acd261667..8a27f2fa1d 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -258,6 +258,133 @@ fn widen(mode: *const c_char) -> Vec { type Handle = *mut c_void; type File = *mut c_void; +/// What `VICTORY_FILES_BUFFERED` asks of the title's opens. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Buffered { + /// `count`: the opens and the title's reads are counted, nothing else. + Count, + /// `1`: counted, and a synchronous read-only open of an existing file + /// on a virtual drive that bypasses the system's file cache reads + /// through it ([`buffered_flags`]). + Clear, +} + +/// `VICTORY_FILES_BUFFERED` (off by default; `count` or `1`). +/// +/// The title opens some of its package files past the system's file cache +/// (the no-buffering flag) and reads them synchronously, one small read +/// after another: through menu and loading the game's disk did 235-1,474 +/// reads a second of 4-8 KB, one at a time (two runs of 2026-11-26), and a +/// second start ten minutes later put the same reads through the disk +/// again, which a cached handle would have served from memory. With `1` +/// such an open reads through the cache: the title's own reads then go +/// disk, system cache, title buffer, one kernel copy more (at most about +/// 7 MB/s before the world), read by the title's CPU. Nothing is claimed +/// for frame time: in the world the disk did 4-13 reads a second. Nothing +/// is gained on the first read after a restart of the PC; the gain is in +/// later starts while the pages stay in standby. An open that reads +/// overlapped is passed through untouched (and counted): the title's opens +/// were not seen to, and on a cached handle such a read can finish inside +/// the call. The DirectStorage files (`super::dstorage`, flags 0) are +/// opened through [`CreateFileW`] too and are in the count. Compiled only, +/// not run. +/// +/// From Kemerd/VIctory-NVIDIA-RT (1053639, in rt-test-11 0549d44c), +/// GPL-3.0; docs/KEMERD-AUDIT.md. +fn buffered() -> Option { + static MODE: std::sync::OnceLock> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_FILES_BUFFERED").as_deref().map(str::trim) { + Ok("count") => Some(Buffered::Count), + Ok("1") => Some(Buffered::Clear), + _ => None, + }) +} + +const GENERIC_READ: u32 = 0x8000_0000; +const OPEN_EXISTING: u32 = 3; +const FILE_FLAG_NO_BUFFERING: u32 = 0x2000_0000; +const FILE_FLAG_OVERLAPPED: u32 = 0x4000_0000; + +/// The flags an open is made with: `flags` without the no-buffering flag +/// when `clear` and the open is of a path on a virtual drive (`rewritten`), +/// for reading only, of a file that exists, and not overlapped; else +/// `flags` as the title gave them. No other bit changes. +fn buffered_flags(access: u32, disposition: u32, flags: u32, rewritten: bool, clear: bool) -> u32 { + if clear + && rewritten + && access == GENERIC_READ + && disposition == OPEN_EXISTING + && flags & FILE_FLAG_NO_BUFFERING != 0 + && flags & FILE_FLAG_OVERLAPPED == 0 + { + flags & !FILE_FLAG_NO_BUFFERING + } else { + flags + } +} + +/// With [`buffered`]: opens; of them those that asked to bypass the cache, +/// those of these that read overlapped (passed through), and those read +/// through the cache now; the title's `ReadFile` calls, their bytes and +/// their microseconds in the host's call. +static FILES_BUFFERED: [std::sync::atomic::AtomicU64; 7] = [const { std::sync::atomic::AtomicU64::new(0) }; 7]; + +/// The (access, flags, on a virtual drive, cleared) kinds of open seen. +static OPEN_KINDS: Mutex>> = Mutex::new(None); + +/// The flags to open with, the open counted ([`buffered`]): a line the +/// first time each kind of open is seen (no path in it). +fn open_flags(access: u32, disposition: u32, flags: u32, rewritten: bool) -> u32 { + use std::sync::atomic::Ordering::Relaxed; + let Some(mode) = buffered() else { + return flags; + }; + let out = buffered_flags(access, disposition, flags, rewritten, mode == Buffered::Clear); + let cleared = out != flags; + let n = FILES_BUFFERED[0].fetch_add(1, Relaxed) + 1; + if flags & FILE_FLAG_NO_BUFFERING != 0 { + FILES_BUFFERED[1].fetch_add(1, Relaxed); + if flags & FILE_FLAG_OVERLAPPED != 0 { + FILES_BUFFERED[2].fetch_add(1, Relaxed); + } + } + if cleared { + FILES_BUFFERED[3].fetch_add(1, Relaxed); + } + let new = OPEN_KINDS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert_with(Default::default) + .insert((access, flags, rewritten, cleared)); + if new { + tracing::info!( + access = format_args!("{access:#x}"), + flags = format_args!("{flags:#x}"), + on_a_virtual_drive = rewritten, + cleared, + "files: a kind of open not seen before (VICTORY_FILES_BUFFERED)" + ); + } + if n.is_power_of_two() { + files_line(); + } + out +} + +/// The totals of [`FILES_BUFFERED`], at powers of two of the opens and of +/// the reads. +fn files_line() { + use std::sync::atomic::Ordering::Relaxed; + let [opens, bypass, overlapped, cleared, reads, bytes, micros] = [0, 1, 2, 3, 4, 5, 6].map(|i| FILES_BUFFERED[i].load(Relaxed)); + tracing::info!( + "files since the start (VICTORY_FILES_BUFFERED): {opens} opens, {bypass} of them past the system's file cache \ + ({overlapped} of these overlapped, passed through), {cleared} read through the cache now; the title's ReadFile: \ + {reads} calls, {} MB, {:.1} ms in the host's call", + bytes >> 20, + micros as f64 / 1e3 + ); +} + // kernel32 and its file API sets. pub extern "system" fn CreateFileW( @@ -270,6 +397,7 @@ pub extern "system" fn CreateFileW( template: Handle, ) -> Handle { let p = wide(path); + let flags = open_flags(access, disposition, flags, p.1.is_some()); host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( p.ptr(), access, @@ -292,6 +420,7 @@ pub extern "system" fn CreateFileA( ) -> Handle { match narrow(path) { Some(p) => { + let flags = open_flags(access, disposition, flags, true); host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( p.as_ptr(), access, @@ -303,6 +432,8 @@ pub extern "system" fn CreateFileA( ) } None => { + // (Counted only: not on a virtual drive.) + let flags = open_flags(access, disposition, flags, false); host!("kernel32.dll", "CreateFileA": extern "system" fn(*const c_char, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( path, access, @@ -536,12 +667,27 @@ pub extern "system" fn ReadFile( overlapped: *mut c_void, ) -> i32 { let writing = victory_gpu::kernel_writing(buffer as usize, len as usize); + // (Timed only with `VICTORY_FILES_BUFFERED`.) + let started = buffered().map(|_| std::time::Instant::now()); let done = host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)( file, buffer, len, read, overlapped, ); // The call's error is the title's to ask for. // SAFETY: plain calls. let error = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + if let Some(started) = started { + use std::sync::atomic::Ordering::Relaxed; + let micros = started.elapsed().as_micros() as u64; + // SAFETY: the title's count, written by the host's call when it + // succeeded (null tolerated). + let got = if done != 0 && !read.is_null() { u64::from(unsafe { read.read_unaligned() }) } else { 0 }; + let n = FILES_BUFFERED[4].fetch_add(1, Relaxed) + 1; + FILES_BUFFERED[5].fetch_add(got, Relaxed); + FILES_BUFFERED[6].fetch_add(micros, Relaxed); + if n >= 1024 && n.is_power_of_two() { + files_line(); + } + } // shortcut: a read that goes on after the call (overlapped) is written // into pages the kernel has locked by now: it lands all the same, but a // refresh that guards its blocks before it does will not see it. @@ -772,6 +918,22 @@ mod tests { s.encode_utf16().chain([0]).collect() } + /// Only a synchronous read-only open of an existing file on a virtual + /// drive loses the no-buffering flag, and only that bit; counting alone + /// changes nothing. + #[test] + fn only_a_plain_read_of_the_package_reads_through_the_cache() { + let past = FILE_FLAG_NO_BUFFERING | 0x80; + assert_eq!(buffered_flags(GENERIC_READ, OPEN_EXISTING, past, true, true), 0x80); + assert_eq!(buffered_flags(GENERIC_READ, OPEN_EXISTING, past, true, false), past); + assert_eq!(buffered_flags(GENERIC_READ, OPEN_EXISTING, past, false, true), past); + assert_eq!(buffered_flags(GENERIC_READ | 0x4000_0000, OPEN_EXISTING, past, true, true), past); + assert_eq!(buffered_flags(GENERIC_READ, 4, past, true, true), past); + let overlapped = past | FILE_FLAG_OVERLAPPED; + assert_eq!(buffered_flags(GENERIC_READ, OPEN_EXISTING, overlapped, true, true), overlapped); + assert_eq!(buffered_flags(GENERIC_READ, OPEN_EXISTING, 0x80, true, true), 0x80); + } + #[test] fn kernel_reads_reach_the_buffer() { use std::os::windows::io::AsRawHandle; diff --git a/docs/KEMERD-AUDIT.md b/docs/KEMERD-AUDIT.md new file mode 100644 index 0000000000..24ed34143b --- /dev/null +++ b/docs/KEMERD-AUDIT.md @@ -0,0 +1,253 @@ +# Audyt Kemerd/VIctory-NVIDIA-RT (RT wyłączony) + +Źródło: https://github.com/Kemerd/VIctory-NVIDIA-RT, tag `rt-test-11` += `0549d44c330bf0a1f808f8b012d8e22168dfad91`. Licencja: GPL-3.0, ta sama co nasza. +Baza porównania: `ampere-sm86-perf-exp1` @ `49f164c66110351f18a22b7f16f694eba605e021`. + +Repozytorium Kemerd ma kilku autorów. Oryginalne commity i ich autorzy: +- `VICTORY_STAGING_NO_ZERO`: `7a166c4`, D Everett Hinton. Nasz `970bcbc` to adaptacja. +- `VICTORY_PIPELINE_WAIT_BACKLOG`: `109f2c8`, Kemerd. Nasz `a376dd7` to adaptacja. +- `VICTORY_FILES_BUFFERED`: `1053639`, D Everett Hinton (nasz `6d39c94`, bez zmian). +- `VICTORY_SEND_COPIED_FIND`: `84d94c5`, D Everett Hinton (nasz `595b8cc`, bez zmian). +- `VICTORY_TEXTURE_LOOK_ONCE`: `35cafeb`, D Everett Hinton (nasz `8fff3e8`). +- `VICTORY_TEXTURE_READ_AHEAD`: `19f0de6`, D Everett Hinton. +- Poprawki z przeglądu: `ef8f00c`, Kemerd (nasze `a5f964a` i poprawka read-ahead, wybrane części). + +Każdy przenoszony mechanizm jest za własnym przełącznikiem, domyślnie wyłączony. +Rollback: nie ustawiać przełącznika albo cofnąć commit (`git revert`). + +## 1. VICTORY_PIPELINE_SAMPLER_TABLE: ALREADY PRESENT (inny mechanizm) + +Problem, który rozwiązuje Kemerd: pipeline'y ze statycznymi samplerami omijają bibliotekę +pipeline'ów (`library::with_static_samplers`), bo sterownik NVIDIA zapisuje w PSO pozycje +samplerów w swojej tabeli, a te pozycje różnią się między procesami. Kemerd podaje, że +około 1100 PSO było kompilowanych od nowa przy każdym starcie. + +Kemerd, `crates/victory-gpu/src/pipeline/host.rs`: `sampler_table()`, `sampler_key()`, +`table_sampler()`, `sampler_block()`. Samplery statyczne zamienia na tablicę w ogonie sterty +samplerów (`SAMPLER_TAIL = 256`), co wymaga zmian w `descriptor/host.rs` (`HostHeap::new`) i +`draw.rs` (`sampler_table`). Gdy w stercie nie ma miejsca, draw jest pomijany +(`sampler_refused`). + +U nas: `crates/victory-gpu/src/pipeline/samplers.rs`, `VICTORY_SAMPLER_ORDER`, domyślnie +WŁĄCZONY. `prime()` (wołane z `host.rs`, tworzenie urządzenia) tworzy wszystkie znane +samplery statyczne w stałej kolejności z pliku `static-samplers.txt`, zanim powstanie +jakikolwiek pipeline. `know()` (`pipeline/host.rs`, `shader_cache.rs`) dopisuje nowe na końcu. +Pozycje w tabeli sterownika są więc takie same w każdym procesie i dysk-cache sterownika +znajduje PSO ponownie. Kolejność wchodzi do odcisku cache (`known.rs`, `samplers::order()`). +Ten moduł powstał w upstreamie (64d4931, 2026-11-27) po rozgałęzieniu Kemerd. W `rt-test-11` +nie ma `pipeline/samplers.rs`. + +Klucz i samplery: +- Kemerd `SamplerKey` = 13 słów (filtr, 3 tryby adresowania, bias, anizotropia, porównanie, + kolor ramki jako 4 floaty RGBA, min/max LOD). +- Nasz `Words` = 10 słów, to samo, ale kolor ramki jako enum `D3D12_STATIC_BORDER_COLOR` + (statyczne samplery mają tylko enum). Dwa samplery różniące się czymkolwiek, co zmienia + obraz, dostają różne słowa. Identyczne trafiają w ten sam wpis. + +Różnica, która zostaje: u nas te PSO nadal idą przez `CreatePipelineState`, ale trafiają w +dysk-cache sterownika, a nie w `LoadGraphicsPipeline` z naszej biblioteki. Pomiar z +`samplers.rs`: 120 PSO w 13,6 s na zimno, potem 0,6 s w tej samej kolejności. Przeniesienie +wersji Kemerd zmieniłoby sterty deskryptorów i dodałoby ryzyko pominiętych drawów. Nie +przenoszę. + +Jak porównać kompilacje: linia logu `host pipeline library saved` (`library.rs`, pola +`made`, `loaded`, `started_early`) oraz `static samplers made in the order of the cache's +list` (`samplers.rs`). + +## 2. VICTORY_STAGING_NO_ZERO: IMPLEMENTED (ten PR) + +Kemerd: `pool.rs` `no_zero()`, `staging(.., leave)`; `texture.rs` `detile_covers()`, +`Staging::unzeroed`, `Staging::zero_if_unwritten()`, `staging_zeros_line()`. +U nas po zmianie: te same nazwy w `crates/victory-gpu/src/pool.rs` i +`crates/victory-gpu/src/texture.rs`, linia logu wołana z `host.rs` (blok 5-sekundowy). +Zależność od RT: brak, to ścieżka uploadu tekstur. + +Co robi: kawałek bloku staging użyty wcześniej był zerowany przy wydaniu, a potem detiling +pisał te same bajty drugi raz. Z przełącznikiem zerowanie jest pomijane, ale tylko gdy da się +wykazać, że detiling zapisze każdy bajt czytany przez GPU. + +Dowód pokrycia: +1. `victory_formats::texture::Layout::detile` (`walk`) dla każdego `z < depth` i `y < height` + kopiuje `width * element_bytes` bajtów (przebiegi `runs` dzielą cały zakres `[0, bytes)`). + Wszystkie kontrole rozmiaru są przed pierwszym zapisem, więc błąd = nic nie zapisane. +2. `CopyTextureRegion` z footprintu czyta w każdym wierszu tylko `RowSizeInBytes`, a nie + `RowPitch`. Wypełnienie do pitcha, przerwy między podzasobami (wyrównanie 512) i ogon + kawałka nie są czytane. +3. `detile_covers` porównuje dla każdego podzasobu (`mip = first + i % levels`, tak jak + `Staging::part`) wartości z layoutu (`width * element_bytes`, `height`, `depth`) z + `GetCopyableFootprints` (`RowSizeInBytes`, `NumRows`, `Depth`). Jeśli choć jeden podzasób + nie jest pokryty, kawałek jest zerowany jak dawniej (licznik `at_making`). +4. Mipy, których tytuł nie trzyma, są jawnie zerowane w pętli (`linear.fill(0)`). Błąd + detilingu w połowie: reszta podzasobów jest zerowana, tak jak w kawałku wyzerowanym przy + wydaniu. +5. Gdy kopia jest nagrywana, zanim cokolwiek zdetilowało kawałek w całości (pamięć + niezmapowana, nieudany odczyt), `zero_if_unwritten` zeruje bufor pod blokadą `last`. + Wołane w `record_upload` i `PreludeUpload::record`, czyli w obu miejscach, które kopiują + ze staging. `Through` (kopie aliasów) i klatki filmów mają własne bufory. +6. Ścieżka GPU (`VICTORY_GPU_DETILE`) nie bierze kawałków z puli, więc się nie zmienia. + +Ryzyko, gdyby dowód był błędny: na teksturze na chwilę widać bajty innej tekstury zamiast +czerni. Dlatego przełącznik jest domyślnie wyłączony. + +Pomiar: linia co sekundę `texture detiling per frame: on the PC X ms for Y MB` oraz linia co +5 s `staging pieces used before ... (VICTORY_STAGING_NO_ZERO=1)` (tylko z przełącznikiem). + +Test jednostkowy: `texture::detile_covers_tests`, `pool::tests::a_texture_gives_its_piece_back_when_it_goes` +(sprawdza, że `leave=false` zeruje, a `leave=true` zostawia). + +## 3. VICTORY_PIPELINE_WAIT_BACKLOG: IMPLEMENTED (ten PR) + +Kemerd: `pipeline/make.rs` `backlog()` i warunek na początku `wait()`. +U nas: `crates/victory-gpu/src/pipeline/make.rs` `backlog()`, `over_backlog()`, warunek w +`wait()`. Zależność od RT: brak. + +Co robi: gdy w kolejce czeka więcej niż `n` pipeline'ów, draw nie czeka na swój pipeline, +tylko jest pomijany od razu, tak jak dziś po wyczerpaniu budżetu `VICTORY_PIPELINE_WAIT_MS` +(500 ms na klatkę). Draw wraca w kolejnej klatce. Kemerd podaje runy z 470 i 600 PSO w +kolejce, gdzie każda klatka zużywała cały budżet (do 3 fps). + +Koszt: obiekty pojawiają się o kilka klatek później przy zimnym cache. Dlatego przełącznik +jest domyślnie wyłączony i ma sens tylko na niewygrzanym cache. + +Bezpieczeństwo: tylko grafika (`p.graphics.is_some()`). Dispatche compute nie przechodzą +przez tę regułę, nawet z `VICTORY_PIPELINE_COMPUTE_WAIT=0`. Przejścia po ekranie mają własny +budżet i też są wyłączone. + +Pomiar: linia FPS co sekundę, `dropped N without a host pipeline (M being made)`, oraz +`host pipelines are not waited for while more than this many are queued` na starcie. +Test: `pipeline::make::tests::a_wait_is_left_out_only_past_the_backlog`. + +## 3a. VICTORY_FILES_BUFFERED: IMPLEMENTED (ten PR) + +Commit `1053639` w repo Kemerd, autor D Everett Hinton, `crates/victory-hle/src/modules/files.rs` +(`buffered()`, `buffered_flags()`, `open_flags()`, `files_line()`, liczniki w `ReadFile`). Nasz +plik był identyczny z rodzicem tego commita, więc patch nałożony bez zmian. +Sprostowanie: nasz commit `6d39c94` ma w metadanych autora Kemerd. Prawdziwy autor to +D Everett Hinton . Historii nie przepisuję, bo commit jest już na GitHubie. +Późniejszych poprawek w `rt-test-11` nie ma. Zależność od RT: brak. + +Co robi: `1` zdejmuje `FILE_FLAG_NO_BUFFERING` tylko z otwarć pliku z wirtualnego dysku gry, +które są: tylko do odczytu (`GENERIC_READ`), `OPEN_EXISTING` i nie `OVERLAPPED`. Żaden inny bit +się nie zmienia. Odczyt idzie wtedy przez cache Windows i kolejny start gry czyta te same +dane z RAM, a nie z dysku. Przy 64 GB RAM cache ma dużo miejsca. `count` tylko liczy. + +Bezpieczeństwo: odczyt przez cache zwraca te same bajty. Wyrównane odczyty, których wymaga +`NO_BUFFERING`, działają też na zwykłym uchwycie. Zapis i odczyt asynchroniczny (overlapped) nie +są ruszane. Autor: „Compiled only, not run”, czyli trzeba to sprawdzić w grze. + +Pomiar: `files since the start (VICTORY_FILES_BUFFERED): ...` (otwarcia, ile przez cache, +`ReadFile`: wywołania, MB, ms) oraz czas od startu do menu i do świata. Zysk dopiero na drugim +starcie po restarcie PC. Test: `files::tests::only_a_plain_read_of_the_package_reads_through_the_cache`. + +## 3b. VICTORY_SEND_COPIED_FIND: IMPLEMENTED (ten PR) + +Commit `84d94c5`, autor D Everett Hinton, plus poprawka Kemerd `ef8f00c` (część `shadow.rs`). +U nas: `crates/victory-gpu/src/shadow.rs` `Carded`, `find_copied()`, `overlapping()`, +`send_copied()`, linia kopii w `host.rs`. Zależność od RT: brak. + +Co robi: kopia bufora tytułu (`send_copied`) zamiast przeglądać wszystkie kopie w pamięci +karty (autor: 4029 w klatce, z czego 1-2 trafiają w cel) szuka ich w `BTreeMap` po adresie +początku, w zakresie `[dst - longest, dst + len)`. Autor podaje 34 us na wywołanie przy pełnym +przeglądzie, czyli około 0,5 ms na klatkę przy 15 kopiach i 3 ms przy 100. Tyle czasu +wątku submitującego. + +Poprawność: `start` i `len` kopii to zwykłe pola `u64` ustawiane raz przy tworzeniu +(`Shadow`, za `Arc`). `longest` nigdy nie maleje, więc dolna granica wyszukiwania jest +bezpieczna. Sprzątanie `by_start` idzie razem z `list`. Build diagnostyczny porównuje +każde wyszukiwanie z pełnym przeglądem i ostrzega przy różnicy. Poprawka `ef8f00c` zwalnia +kopie dopiero po puszczeniu blokady `CARDED` i mierzy tylko samo wyszukiwanie. + +Pomiar: linia kopii karty w logu (`SEND_COPIED`: wywołania, ns, trafienia). +Test: `shadow::overlapping_tests::finds_every_copy_that_holds_a_byte`. + +## 3c. VICTORY_TEXTURE_LOOK_ONCE: IMPLEMENTED (ten PR) + +Commit `35cafeb`, autor D Everett Hinton, plus poprawka Kemerd `ef8f00c` (`note_looked`). +U nas: `crates/victory-gpu/src/texture.rs` `look_once()`, `LOOK_ONCE`, `looked_already()`, +`look_once_line()`, `note_looked()`, `Last::looked`, sprawdzenie w `Staging::refresh`. +Konflikt tylko w `host.rs` (miejsce wywołania linii logu). Zależność od RT: brak. + +Co robi: tekstura pilnowana przez strażnika zapisów, do której nic nie zapisało, jest +czytana i hashowana w całości najwyżej raz na klatkę zamiast przy każdej submisji (17-30 +na klatkę). Zapis widziany przez strażnika i dokładne odświeżenia (bake) idą jak dawniej. + +Ryzyko (opis autora): tekstura zapisana drogą, której strażnik nie widzi, między dwoma +próbkowaniami w jednej klatce pokaże późniejszemu starsze bajty, czyli najwyżej jedną +klatkę opóźnienia. Dlatego przełącznik jest domyślnie wyłączony. + +Pomiar: linia `guarded textures read with no write told, per frame: ...` jest wypisywana +także bez przełącznika i pokazuje, ile drugich odczytów jest do zaoszczędzenia. Jeśli +`again` jest bliskie zera, przełącznik nic nie da. + +## 3c2. VICTORY_TEXTURE_READ_AHEAD: IMPLEMENTED (ten PR) + +Commit `19f0de6`, autor D Everett Hinton, plus poprawka Kemerd `ef8f00c` (część read-ahead). +U nas: `crates/victory-gpu/src/texture/ahead.rs` `read_ahead()`, `read_soon()`, +`read_worker()`, `read_ahead_line()`; `texture.rs` `Staging::refresh_soon()`, +`refresh_locked()`, `Last::tried`, `unstage()` zwraca bufor; wywołanie w `draw.rs` przy +przejściu po teksturach. Zależność od RT: brak. + +Co robi: bufor staging, który przejście po teksturach puszcza po jednym uploadzie, czytają +dwa wątki `textures read ahead`, zamiast wątku submitującego przy submisji. Nie dodaje +żadnego kopiowania, tylko przenosi odczyt na inny wątek. Kolejka ma limit 64 MB, a po jego +przekroczeniu bufor czeka na submisję jak dawniej. Bez bake'ów (exact), bez buforów +pilnowanych przez draw z tablicy, tylko z odciskiem do późniejszego sprawdzenia. +Autor podaje 1-5 ms czasu wątku submitującego na klatkę bez RT (górna granica). To nie jest +czas klatki. + +Poprawność (`ef8f00c`): decyzja i odczyt pod jedną blokadą `last`, więc submisja nie wejdzie +między nie. Bufor, który submisja już próbowała odświeżyć (`tried`), jest pomijany, bo jego +kopia może lecieć na kartę. + +Pomiar: linia `texture uploads of the lists read ahead of their submission +(VICTORY_TEXTURE_READ_AHEAD=1), per frame` oraz linia FPS. Według autora nie mogą rosnąć: +„a texture picked by index changed after its upload” i „waiting for a texture another +thread is refreshing”. Test: `texture::ahead::tests::reads_ahead_fit_their_bound`. + +Sprostowanie: opis commitu `4162a3d` przypisuje sprawdzanie cichych klatek w `ahead.rs` +commitowi `a309f8e`. W rzeczywistości pochodzi ono z `ef8f00c`. `a309f8e` (licznik `in_flight` +dla `VICTORY_UPLOAD_AHEAD`) nie jest przeniesiony. + +## 3d. Poprawka Kemerd ef8f00c dla VICTORY_STAGING_NO_ZERO + +`PreludeUpload::record` działa pod blokadą stanów listy, a `zero_if_unwritten` bierze +blokadę `last`. Kemerd przeniósł zerowanie do `PreludeUpload::finish_refresh`, przed +nagraniem prelude. U nas zrobione tak samo. W `record` zostaje jako zabezpieczenie +(po wyzerowaniu to tylko odczyt flagi). + +## 4. VICTORY_PIPELINE_WAIT_ONCE: DISCOVERED + +Pomija czekanie, które nie zdąży w budżecie (`skip_wait`). Wymaga `asked_ms` w `Pending` i +`FRONT_MS` w kolejce. Autor: „Compiled and tested, not yet seen in a run”. Odłożone. + +## 5. VICTORY_PIPELINE_SLOW_WORKERS: DISCOVERED + +Dodatkowe wątki do wolnych pipeline'ów, gdy nic nie jest zamówione. Limit +`procesory - workery - 4`. Dla i5-12600K: 16 - 10 - 4 = 2 wątki. Autor: „not verified in a +run”. Mały zysk, odłożone. + +## 6. VICTORY_REFRESH_SET: DISCOVERED (osobny PR) + +Kemerd `host/lean.rs`. Jeden `Step::RefreshSet` na listę zamiast około 245 `Step::Refresh`. +Dotyka `Memory::bring_up` (`memory.rs`) i wszystkich przejść po krokach submisji. Do +osobnego audytu. + +## 7. VICTORY_SEND_THREAD: DISCOVERED (osobny PR) + +Kemerd `host/send_thread.rs` (320 linii) i 5 miejsc w `host.rs`. Zależności u nas: +1. Działa tylko z `late()` (`host.rs`, `late_stage()`): `VICTORY_LATE_WAIT` 1/2/3 albo relay + (`shadow::relay()`). Bez tego przełącznik nic nie robi. +2. Kolejność submitów: wartość fence rezerwuje wątek submitujący (`*submitted += 1`), a + `Flight` trafia do `line()` z tego wątku, przed następną submisją. Wątek wysyłający robi + tylko `ExecuteCommandLists` + `Signal` + `awake::sent` + `card_sent`. U nas ten ogon jest + w bloku `if late {` w `Host::submit` (okolice `awake::sent`). +3. Fence: każda wartość musi zostać zasygnalizowana, także po panice i pustej liście, bo + inaczej czekanie na flight wisi. +4. `card_before` (`host.rs`) i inne ścieżki wkładające listy na kolejkę muszą wołać + `send_thread::wait_idle()` przed swoim `ExecuteCommandLists`. U nas są dodatkowe + wywołania `ExecuteCommandLists` (`host.rs`, `pool.rs`), które trzeba zinwentaryzować. +5. Czas życia zasobów: listy są zamknięte, a bajty zamrożone przez `send::take`, zanim job + trafi do wątku. Zasoby trzyma lista do resetu po fence, więc wątek nic nie zwalnia. + +Nasz `host.rs` różni się od Kemerd o około 2700 linii. Port ręczny, osobny PR.