From 2d1dc3826f331007a3b4ee0d89cecaa73695816e Mon Sep 17 00:00:00 2001 From: Indy2l Date: Thu, 26 Nov 2026 17:14:15 +0100 Subject: [PATCH] Texture read-backs: written by a thread of their own; landing timing split "read-backs and lists" in the landing line is split into texture read-backs, buffer read-backs and the flights' card plans and own work. On a 16 GB machine with an RTX 3060 (Series S, 540p) the texture part stood at 1-2 ms a frame, and at 124-416 ms in the frames where the world streamed: texback::land waits for the lock against mapping changes (watch::title_memory_reading), which the title changes all the time then, and the landing of every submission waited with it. The landing thread now only copies a read-back's texels out of its buffer; waiting for the locks, tiling and writing into title memory go to a thread of their own, which writes only the newest of several copies of one allocation (the title reads the frame before at most). VICTORY_TEXBACK_ASYNC=0 writes them where they land, as before. A new line gives the writer's waits and work per frame. Co-Authored-By: Claude Sonnet 5.5 --- crates/victory-gpu/src/host.rs | 9 ++ crates/victory-gpu/src/land.rs | 40 ++++++- crates/victory-gpu/src/texback.rs | 167 +++++++++++++++++++++++++----- 3 files changed, 188 insertions(+), 28 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 9bdf299..07c976e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3837,12 +3837,18 @@ pub(crate) fn walls_trace() -> bool { /// without it, so the title read a buffer nobody wrote, as before read-backs /// were made (the exposure metering's two small float targets, every frame). fn read_backs(list: &HostList) { + use crate::land::{count, spent, stat}; + let started = std::time::Instant::now(); // Textures shaders wrote that the title reads on the CPU // ([`crate::texback`]). for back in &list.deferred().texture_backs { crate::texback::land(back); + count(stat::RB_TEXTURE_COUNT, 1); } + let textures_done = spent(stat::RB_TEXTURES, started); for (buffer, at, [row, rows, pitch]) in &list.deferred().backs { + count(stat::RB_BUFFER_COUNT, 1); + count(stat::RB_BUFFER_BYTES, (*row * *rows) as u64); let mut data = std::ptr::null_mut(); // SAFETY: a read-back buffer of ours, written by the list that has // run; the title's destination holds every row (checked when the @@ -3870,6 +3876,7 @@ fn read_backs(list: &HostList) { } } } + spent(stat::RB_BUFFERS, textures_done); } /// After the card ran what declared `back`: what shaders wrote there goes @@ -4904,12 +4911,14 @@ impl Host { for &i in &flight.order { read_backs(flight.lists[i].host()); } + let done_from = std::time::Instant::now(); if let Some(card) = flight.card { self.card_done(card); } if let Some(own) = flight.own { own.landed(); } + crate::land::spent(crate::land::stat::RB_DONE, done_from); landed.push((flight.lists, flight.order)); crate::land::spent(crate::land::stat::READ_BACKS, telling) } diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 2bde585..2197db3 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -115,7 +115,26 @@ pub(crate) mod stat { pub(crate) const HAD_BYTES: usize = 24; /// Jobs. pub(crate) const JOBS: usize = 25; - pub(crate) const COUNT: usize = 26; + /// Parts of [`READ_BACKS`]: textures shaders wrote that the title reads + /// (`texback::land`), buffer read-backs (map and copy into title memory), + /// and the flight's card plan and own work told done. + pub(crate) const RB_TEXTURES: usize = 26; + pub(crate) const RB_BUFFERS: usize = 27; + pub(crate) const RB_DONE: usize = 28; + /// Counts for those: texture read-backs landed, buffer read-backs and + /// their bytes. + pub(crate) const RB_TEXTURE_COUNT: usize = 29; + pub(crate) const RB_BUFFER_COUNT: usize = 30; + pub(crate) const RB_BUFFER_BYTES: usize = 31; + /// Writing texture read-backs into title memory (`texback::write`, on + /// its own thread unless `VICTORY_TEXBACK_ASYNC=0`): waiting for the + /// locks against mapping changes, the work after, read-backs written, + /// and those replaced by a newer one before they were. + pub(crate) const TB_WAIT: usize = 32; + pub(crate) const TB_WORK: usize = 33; + pub(crate) const TB_WRITTEN: usize = 34; + pub(crate) const TB_REPLACED: usize = 35; + pub(crate) const COUNT: usize = 36; } static STATS: [AtomicU64; stat::COUNT] = [const { AtomicU64::new(0) }; stat::COUNT]; @@ -172,6 +191,25 @@ pub(crate) fn log(frames: f64) { ms(stat::TOLD), ms(stat::REST), ); + tracing::info!( + "read-backs and lists per frame: textures shaders wrote {:.2} ms ({:.1} landed), buffer read-backs {:.2} ms \ + ({:.1} of them, {:.2} MB), card plans and own work done {:.2} ms", + ms(stat::RB_TEXTURES), + s[stat::RB_TEXTURE_COUNT], + ms(stat::RB_BUFFERS), + s[stat::RB_BUFFER_COUNT], + mb(s[stat::RB_BUFFER_BYTES]), + ms(stat::RB_DONE), + ); + tracing::info!( + "texture read-backs written per frame (VICTORY_TEXBACK_ASYNC={}): {:.1}, {:.1} replaced by a newer one first; \ + waiting for the mapping locks {:.2} ms, tiling and writing {:.2} ms", + u8::from(std::env::var_os("VICTORY_TEXBACK_ASYNC").is_none_or(|v| v != "0")), + s[stat::TB_WRITTEN], + s[stat::TB_REPLACED], + ms(stat::TB_WAIT), + ms(stat::TB_WORK), + ); tracing::info!( "landed per frame: {:.0} pieces, {:.0} with a new byte; of their {:.0} pages of 4 KiB {:.0} with a new byte ({:.1} MB), \ {:.1} MB in blocks of 32 bytes with one, {:.2} MB put as dwords; {:.0} pieces through a view of ours \ diff --git a/crates/victory-gpu/src/texback.rs b/crates/victory-gpu/src/texback.rs index cf7b0e3..36e5d6b 100644 --- a/crates/victory-gpu/src/texback.rs +++ b/crates/victory-gpu/src/texback.rs @@ -197,57 +197,170 @@ pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option Some(Back { buffer, footprints, rows, mips, layout: target.layout, ticket: target.ticket }) } -/// Once the list has run, tile its texels back into the same title allocation. +/// Whether texture read-backs are written into title memory by a thread of +/// their own (`VICTORY_TEXBACK_ASYNC`; on unless `0`). +/// +/// Writing one takes the lock against mapping changes +/// ([`crate::watch::title_memory_reading`]), and while the title streams the +/// world it changes mappings all the time: on the thread that lands +/// submissions the wait for that lock stood 100-400 ms in some frames +/// (run 5 of the 16 GB machine, RTX 3060: "textures shaders wrote" in the +/// read-backs line, two to ten 350 KB water maps a frame), and with it the +/// landing of everything else. Here the landing thread only copies the +/// texels out of the read-back buffer; the waiting, tiling and writing go to +/// [`writer`]. Of several copies of one texture waiting there only the newest +/// is written: the title reads the frame before at most, which it may on the +/// console too. +fn asynchronous() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXBACK_ASYNC").is_none_or(|v| v != "0")) +} + +/// A read-back's texels taken out of its buffer, to be tiled into title memory. +struct Landing { + footprints: Vec, + rows: Vec, + mips: u32, + layout: victory_formats::texture::Layout, + ticket: Arc, + /// The read-back buffer's bytes, from 0 to the end of its last subresource. + data: Vec, +} + +/// Once the list has run, tile its texels back into the same title allocation +/// (on [`writer`]'s thread when [`asynchronous`]). pub(crate) fn land(back: &Back) { - static COPIED: AtomicU64 = AtomicU64::new(0); - static STALE: AtomicU64 = AtomicU64::new(0); - let _mapping = crate::watch::title_memory_reading(); - let _ticket_guard = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); if !back.ticket.valid.load(Ordering::Acquire) { - let skipped = STALE.fetch_add(1, Ordering::Relaxed) + 1; - if skipped.is_power_of_two() { - tracing::info!(skipped, "skipping texture readbacks whose title allocation changed"); - } + stale(); return; } - let (at, end) = back.range(); + let len = back + .footprints + .iter() + .zip(&back.rows) + .map(|(f, &rows)| f.Offset as usize + f.Footprint.RowPitch as usize * rows as usize * f.Footprint.Depth as usize) + .max() + .unwrap_or(0); + let mut mapped = std::ptr::null_mut(); + // SAFETY: our read-back buffer, written by the list that has run; `len` + // ends with its last subresource, which it holds. + let data = unsafe { + if back.buffer.Map(0, None, Some(&mut mapped)).is_err() || mapped.is_null() { + return; + } + let data = std::slice::from_raw_parts(mapped.cast::().cast_const(), len).to_vec(); + back.buffer.Unmap(0, None); + data + }; + let landing = Landing { + footprints: back.footprints.clone(), + rows: back.rows.clone(), + mips: back.mips, + layout: back.layout.clone(), + ticket: back.ticket.clone(), + data, + }; + match asynchronous().then(writer).flatten() { + Some(writer) => writer.send(landing), + None => write(&landing), + } +} + +fn stale() { + static STALE: AtomicU64 = AtomicU64::new(0); + let skipped = STALE.fetch_add(1, Ordering::Relaxed) + 1; + if skipped.is_power_of_two() { + tracing::info!(skipped, "skipping texture readbacks whose title allocation changed"); + } +} + +/// Tiles a read-back's texels into its title allocation. +fn write(landing: &Landing) { + use crate::land::{count, spent, stat}; + static COPIED: AtomicU64 = AtomicU64::new(0); + let asked = std::time::Instant::now(); + let _mapping = crate::watch::title_memory_reading(); + let _ticket_guard = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); + let working = spent(stat::TB_WAIT, asked); + if !landing.ticket.valid.load(Ordering::Acquire) { + stale(); + return; + } + let (at, end) = (landing.ticket.at, landing.ticket.end); let size = end - at; let mut tiled = vec![0u8; size]; // Keep title bytes the subresources do not cover. if !crate::host::read_into(at as *const u8, &mut tiled) { return; } - let mut data = std::ptr::null_mut(); - // SAFETY: our read-back buffer, written by the list that has run. - unsafe { - if back.buffer.Map(0, None, Some(&mut data)).is_err() || data.is_null() { - return; - } - } - for (i, (footprint, &rows)) in back.footprints.iter().zip(&back.rows).enumerate() { - let (mip, slice) = (i as u32 % back.mips, i as u32 / back.mips); + for (i, (footprint, &rows)) in landing.footprints.iter().zip(&landing.rows).enumerate() { + let (mip, slice) = (i as u32 % landing.mips, i as u32 / landing.mips); let f = footprint.Footprint; let pitch = f.RowPitch as usize; - let len = pitch * rows as usize * f.Depth as usize; - // SAFETY: the subresource's part of the mapped buffer. - let linear = unsafe { std::slice::from_raw_parts(data.cast::().add(footprint.Offset as usize), len) }; - if let Err(e) = back.layout.tile(&mut tiled, mip, slice, linear, pitch, pitch * rows as usize) { + let from = footprint.Offset as usize; + let linear = &landing.data[from..from + pitch * rows as usize * f.Depth as usize]; + if let Err(e) = landing.layout.tile(&mut tiled, mip, slice, linear, pitch, pitch * rows as usize) { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!(?e, mip, slice, "a texture copied back could not be tiled")); - // SAFETY: mapped above. - unsafe { back.buffer.Unmap(0, None) }; return; } } - // SAFETY: mapped above. - unsafe { back.buffer.Unmap(0, None) }; crate::host::copy_mapped(at as *mut u8, tiled.as_ptr(), size, true); + spent(stat::TB_WORK, working); + count(stat::TB_WRITTEN, 1); let copied = COPIED.fetch_add(1, Ordering::Relaxed) + 1; if copied == 1 || copied.is_multiple_of(128) { tracing::info!(copied, bytes = size, "texture readback landed"); } } +/// The thread that writes read-backs into title memory, and what waits for it. +struct Writer { + /// By title address: the newest landing for that allocation. + waiting: Mutex>, + more: std::sync::Condvar, +} + +impl Writer { + fn send(&self, landing: Landing) { + let mut waiting = self.waiting.lock().unwrap_or_else(|e| e.into_inner()); + if waiting.insert(landing.ticket.at, landing).is_some() { + crate::land::count(crate::land::stat::TB_REPLACED, 1); + } + drop(waiting); + self.more.notify_one(); + } +} + +/// The writer, if its thread could be started (if not, landings are written +/// where they are made, as before). +fn writer() -> Option<&'static Writer> { + static WRITER: OnceLock> = OnceLock::new(); + *WRITER.get_or_init(|| { + let writer: &'static Writer = + Box::leak(Box::new(Writer { waiting: Mutex::new(std::collections::HashMap::new()), more: std::sync::Condvar::new() })); + let started = std::thread::Builder::new().name("texture read-backs".into()).spawn(move || loop { + let batch: Vec = { + let mut waiting = writer.waiting.lock().unwrap_or_else(|e| e.into_inner()); + while waiting.is_empty() { + waiting = writer.more.wait(waiting).unwrap_or_else(|e| e.into_inner()); + } + waiting.drain().map(|(_, landing)| landing).collect() + }; + for landing in &batch { + write(landing); + } + }); + match started { + Ok(_) => Some(writer), + Err(e) => { + tracing::warn!(error = %e, "no thread for texture read-backs: they are written where they land"); + None + } + } + }) +} + #[cfg(test)] mod tests {