diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index c96ff17e04..befd176520 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -920,6 +920,21 @@ pub(crate) fn view(handle: u64) -> Option { view_at(i, generation) } +/// The view recorded at `handle`, and what says which record that is +/// (`host::HostHeap::publish`). +#[cfg(windows)] +pub(crate) fn view_and_key(handle: u64) -> Option<(View, u64)> { + if handle == 0 { + return None; + } + // SAFETY: as in `view`. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + if tag != VIEW_TAG { + return None; + } + Some((view_at(i, generation)?, u64::from(generation) << 32 | u64::from(i))) +} + /// A description of `N` words, if the title passes one. fn words(desc: *const [u32; N]) -> Option<[u32; N]> { // SAFETY: the title passes a description or null. diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 7970fc5f0c..18dab84416 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -523,6 +523,11 @@ struct Waiting { checked: (u64, u64, u64, u8, u64), } +thread_local! { + /// This thread is inside [`HostHeap::publish`]. + static PUBLISHING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + /// 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). @@ -1489,6 +1494,9 @@ impl HostHeap { /// `texture`, whether it now holds a view of a texture the title may /// fill; `seen` as for [`HostHeap::note_buffer`]. fn queue_texture(&self, index: u32, texture: bool, seen: bool, frame: u64) { + if PUBLISHING.get() { + return; + } let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 }; let now = (frame as u32).wrapping_add(1) & !TABLED_READ; // A table's slot lately: the draw that reads it uploads its @@ -1918,6 +1926,23 @@ impl HostHeap { (looked, due.len() as u64) } + /// Makes host slot `index` from the record at `handle` if it is still + /// the one with `key`, whose texture's upload is in the queue now + /// (`crate::heap_worker`). The slot's place in the queue of textures + /// picked by index was settled when that upload was recorded, and stays + /// as it is. False if the title wrote the slot again. + pub(crate) fn publish(&self, index: u32, handle: u64, key: u64) -> bool { + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + if tag != VIEW_TAG || u64::from(generation) << 32 | u64::from(i) != key { + return false; + } + PUBLISHING.set(true); + let shown = self.mirror(index, handle, true).is_some(); + PUBLISHING.set(false); + shown + } + /// Makes host slot `index` from the record the title has at `handle` /// if it changed since, and returns the view recorded there. Buffer /// views are made only for draws (`for_draw`), which also copy their @@ -3454,6 +3479,40 @@ mod tests { assert_eq!(slots(62), [1]); } + /// A slot whose texture was uploaded ahead shows it when it is + /// published, and does not go back into the queue of textures picked by + /// index for that; one the title wrote again is left alone. + #[test] + fn a_published_slot_stays_out_of_the_queue() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + // 64x64 BC7, one mip, at an address no test and no title uses. + let view = |at: u64| { + let mut desc = [0u32; 16]; + (desc[0], desc[1], desc[2], desc[5]) = (98, 4, 5768, 1); + (desc[10], desc[11]) = (at as u32, (at >> 32) as u32); + View::Placed(false, [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc) + }; + let title = [0u32; 8]; + let handle = title.as_ptr() as u64; + crate::descriptor::record(handle, view(0x7fec_0000_0000)); + let (first, key) = crate::descriptor::view_and_key(handle).unwrap(); + assert!(heap.note_buffer(1, Some(&first), false).is_empty()); + let (index, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; + assert_eq!(index, 1); + // Its upload was recorded: out of the queue, the slot not made yet. + heap.texture_slot_done(1, write, None); + assert!(!heap.made(1)); + assert!(heap.publish(1, handle, key)); + assert!(heap.made(1)); + assert!(heap.texture_slots_due(u64::MAX, 8).0.is_empty()); + // Written again since the upload was recorded. + crate::descriptor::record(handle, view(0x7feb_0000_0000)); + assert!(!heap.publish(1, handle, key)); + assert_ne!(crate::descriptor::view_and_key(handle).unwrap().1, key); + } + /// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that /// overlaps others is left out of the spans, as before. #[test] diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c5e7655d3a..d8ad09f52e 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -369,6 +369,13 @@ pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0); /// index ([`State::heap_buffers`]), and the microseconds they took. pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0); pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0); +/// Where the pass over textures picked by index records its uploads: into +/// a list of the title's, or into lists of the thread that runs it ahead. +pub(crate) enum Into<'a> { + List(&'a HostList), + Ahead(&'a mut crate::heap_worker::Batch), +} + /// Of [`HEAP_BUFFER_MICROS`], the microseconds of the pass over textures /// picked by index that runs inside it (`heap_textures`), and the buffer /// slots the pass over buffer views looked at; since the last frame line. @@ -1505,7 +1512,9 @@ impl State { shadow.refresh(list, *from, to - from); } let textures_began = std::time::Instant::now(); - self.heap_textures(list, heap, host); + if !crate::heap_worker::kick(heap) { + Self::heap_textures(Into::List(list), heap, host); + } HEAP_PASS_PARTS[0].fetch_add(textures_began.elapsed().as_micros() as u64, Ordering::Relaxed); HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); @@ -1571,6 +1580,11 @@ impl State { return; }; let bake = bake && left > 0; + // What can wait for a later list is the worker's. + if !bake && crate::heap_worker::kick(heap) { + return; + } + let _pass = crate::heap_worker::on().then(crate::heap_worker::urgent); let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1; if bake && n.is_power_of_two() { let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); @@ -1585,7 +1599,7 @@ impl State { } let began = std::time::Instant::now(); PASS_BUDGET.set(Some(budget)); - self.heap_textures(list, heap, host); + Self::heap_textures(Into::List(list), heap, host); PASS_BUDGET.set(None); if bake { BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); @@ -1681,9 +1695,11 @@ impl State { /// in place of others, and contents changed with no descriptor write, /// are missed (hook the page-mapping events for those). /// `VICTORY_HEAP_TEXTURES=0` turns it off. - fn heap_textures( - &self, - list: &HostList, + /// On a thread of its own the pass records into lists of its own, and + /// the slots show what they upload from then on + /// (`crate::heap_worker`). + pub(crate) fn heap_textures( + mut into: Into<'_>, heap: &crate::descriptor::Heap, host: &crate::descriptor::host::HostHeap, ) { @@ -1756,6 +1772,8 @@ impl State { static PASSED: AtomicU64 = AtomicU64::new(0); let now = crate::host::now_ms(); let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1); + // The worker may run two passes in a frame: no shorter than that. + let took = if matches!(into, Into::Ahead(_)) { took.max(100) } else { took }; let most = (4000 / took).clamp(16, 256); // What a table entry of a texture a shader samples says. let sampled = UsedResource { @@ -1796,6 +1814,25 @@ impl State { if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span { break; } + let ahead = matches!(into, Into::Ahead(_)); + if ahead && crate::heap_worker::make_way() { + break; + } + // The record the slot has now, and the texture it names held + // while a thread of ours works on it. (Released meanwhile, or + // not a texture: nothing to upload.) + let record = heap.handle(index).and_then(crate::descriptor::view_and_key); + let _held = match &record { + Some((View::Shader(object, _), _)) if ahead => { + let held = crate::resource::hold(*object as This); + if held.is_none() { + host.texture_slot_done(index, write, None); + continue; + } + held + } + _ => None, + }; // A placed texture whose memory is not mapped (not streamed in // yet, or streamed out again: the heap keeps tens of thousands // of such views) gets no host texture; looked at again soon (a @@ -1840,9 +1877,9 @@ impl State { } } let mut partly = None; - if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) { + if let Some((View::Placed(false, resource, desc), _)) = &record { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; - let len = crate::resource::placed_bytes(&resource).unwrap_or(1); + let len = crate::resource::placed_bytes(resource).unwrap_or(1); let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize); if mapped == 0 { HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed); @@ -1867,9 +1904,9 @@ impl State { // host's own contents: nothing to bring up to date, and this // pass is no use of it (its host copy is made when something // uses it, and its slots then: `descriptor::make_waiting`). - if let Some(View::Shader(object, _)) = heap.handle(index).and_then(crate::descriptor::view) - && crate::resource::buffer_bytes(object as This).is_none() - && !crate::resource::title_fills(object as This) + if let Some((View::Shader(object, _), _)) = &record + && crate::resource::buffer_bytes(*object as This).is_none() + && !crate::resource::title_fills(*object as This) { host.texture_slot_done(index, write, None); continue; @@ -1914,7 +1951,12 @@ impl State { ); } } - let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true)); + // On the worker the slot shows the view when the upload is in + // the queue ([`crate::heap_worker::Batch::publish`]). + let view = match &into { + Into::List(_) => heap.handle(index).and_then(|handle| host.mirror(index, handle, true)), + Into::Ahead(_) => record.as_ref().map(|(view, _)| view.clone()), + }; let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); let resource = match placed.as_ref().or(view.as_ref()) { Some(&View::Shader(resource, _)) => resource as This, @@ -1934,7 +1976,18 @@ impl State { // submission that samples it. let tabled = crate::texture::is_staged(resource); if let Some(view) = &view { - readable(list, sampled.kind, view); + match &mut into { + Into::List(list) => readable(list, sampled.kind, view), + Into::Ahead(batch) => { + let Some(list) = batch.list() else { + return; + }; + readable(list, sampled.kind, view); + if let (Some(handle), Some((_, key))) = (heap.handle(index), &record) { + batch.publish(index, handle, *key); + } + } + } } // A texture view the host refuses removes the device: name it. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -1980,6 +2033,9 @@ impl State { }; crate::texture::unstage(resource); SPENT.fetch_add(bytes, Ordering::Relaxed); + if let Into::Ahead(batch) = &mut into { + batch.uploaded(bytes); + } since_asked += bytes; if room && since_asked >= 32 << 20 { since_asked = 0; @@ -2403,7 +2459,7 @@ impl State { let draws: u32 = census.1.values().sum(); if draws > 0 { let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect(); - rects.sort_unstable_by(|a, b| b.1.cmp(&a.1)); + rects.sort_unstable_by_key(|a| std::cmp::Reverse(a.1)); let scissors: Vec = rects .iter() .take(5) diff --git a/crates/victory-gpu/src/heap_worker.rs b/crates/victory-gpu/src/heap_worker.rs new file mode 100644 index 0000000000..7ad742f840 --- /dev/null +++ b/crates/victory-gpu/src/heap_worker.rs @@ -0,0 +1,288 @@ +//! The pass that uploads textures picked by index, on a thread of its own +//! (`VICTORY_HEAP_WORKER=1`; off by default; needs `VICTORY_LATE_WAIT`). +//! +//! [`crate::draw::State::heap_textures`] runs on whichever thread of the +//! title records the frame's first shader that picks textures by index: it +//! asks what of each due texture is mapped, makes the host texture, makes a +//! staging buffer and records the copy, up to 250 ms of every frame while a +//! backlog waits, and the threads waiting for that list wait with it. The +//! detiling of what it recorded then runs on the thread that submits. With +//! the switch the pass runs here, and the recording thread only wakes it. +//! +//! What keeps the picture as it was: +//! - the uploads are recorded into host lists of ours ([`Batch`]), which the +//! next submission of the title's runs ahead of its own lists +//! ([`take_ready`]): texture states are settled by submission order, as +//! between any two lists; +//! - a texture's host slot is given its view at that submission, not before +//! ([`Publish`]): until then shaders see what the slot showed, never a +//! texture without its contents. (A host texture may be placed in memory +//! another texture had: `crate::placed`.) A slot the title wrote again +//! meanwhile is left to the write's own turn in the queue; +//! - the detiling done here is checked at submission as any texture's is: +//! memory the title wrote in between is read again; +//! - a title texture the pass works on is held ([`crate::resource::hold`]), +//! and so is the title's heap; +//! - the uploads before the title's decoration bake, which must be there +//! for that draw, still run on the recording thread; the worker makes way +//! for them ([`urgent`]). +// shortcut: what a submission shows for a texture is up to a frame later +// than when the recording thread did it all; with a backlog it is earlier, +// since the pass has the whole frame instead of a slice of it. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; + +use crate::descriptor::Heap; +use crate::host::HostList; +use crate::object::This; + +/// Whether the pass runs on its own thread now. +pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_WORKER").is_some_and(|v| v == "1")) && crate::host::late() +} + +/// For the frame line, since the last one: nanoseconds the worker was at +/// work, of them detiling, lists given to submissions, textures published, +/// slots the title had written again, and textures in those lists whose +/// detiling was not done here. +pub(crate) static STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + +/// One upload list holds at most this much texture memory, or this many +/// milliseconds of work, so that its textures show soon. +const LIST_BYTES: u64 = 48 << 20; +const LIST_MS: u128 = 40; + +/// A view to give a host slot once its texture's upload is in the queue: +/// the title's heap, the slot, the record's handle, and the record's key as +/// it was when the upload was recorded. +pub(crate) struct Publish { + heap: usize, + index: u32, + handle: u64, + key: u64, +} + +/// Holds a reference to a title heap. +struct HeldHeap(This); +// SAFETY: a reference counted title object, of which only the count and the +// parts behind locks are touched. +unsafe impl Send for HeldHeap {} + +impl HeldHeap { + fn new(heap: &Heap) -> Self { + let this = std::ptr::from_ref(heap).cast(); + crate::object::add_ref(this); + HeldHeap(this) + } + + fn heap(&self) -> &Heap { + crate::descriptor::heap(self.0) + } +} + +impl Drop for HeldHeap { + fn drop(&mut self) { + crate::object::release_boxed::(self.0); + } +} + +/// A closed upload list, and what is published when it is submitted. +struct Ready { + list: HostList, + publish: Vec, + _heap: HeldHeap, +} +// SAFETY: D3D12 objects are free-threaded; the list is closed and touched +// by nobody until it is taken out. +unsafe impl Send for Ready {} + +static READY: Mutex> = Mutex::new(Vec::new()); + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// What a pass on the worker's thread records into: one upload list after +/// the other, made when first needed. +pub(crate) struct Batch { + heap: This, + list: Option, + publish: Vec, + bytes: u64, + began: std::time::Instant, +} + +impl Batch { + fn new(heap: &Heap) -> Self { + Batch { + heap: std::ptr::from_ref(heap).cast(), + list: None, + publish: Vec::new(), + bytes: 0, + began: std::time::Instant::now(), + } + } + + /// The open upload list. + pub(crate) fn list(&mut self) -> Option<&HostList> { + if self.list.is_none() { + self.list = crate::list::fresh_list(); + self.began = std::time::Instant::now(); + } + self.list.as_ref() + } + + /// Slot `index` (its record at `handle`, then with `key`) shows its + /// texture when the open list is submitted. `bytes` were uploaded. + pub(crate) fn publish(&mut self, index: u32, handle: u64, key: u64) { + self.publish.push(Publish { heap: self.heap as usize, index, handle, key }); + } + + /// `bytes` more of texture memory in the open list, which is closed + /// and handed over when it holds enough. + pub(crate) fn uploaded(&mut self, bytes: u64) { + self.bytes += bytes; + if self.bytes >= LIST_BYTES || self.began.elapsed().as_millis() >= LIST_MS { + self.flush(); + } + } + + /// Detiles what the open list uploads, closes it and hands it to the + /// next submission. + fn flush(&mut self) { + self.bytes = 0; + let publish = std::mem::take(&mut self.publish); + let Some(list) = self.list.take() else { + return; + }; + let started = std::time::Instant::now(); + let left = list.refresh_textures_ahead(); + STATS[1].fetch_add(started.elapsed().as_nanos() as u64, Relaxed); + STATS[5].fetch_add(left, Relaxed); + list.close(); + let heap = HeldHeap::new(crate::descriptor::heap(self.heap)); + lock(&READY).push(Ready { list, publish, _heap: heap }); + } +} + +impl Drop for Batch { + fn drop(&mut self) { + self.flush(); + } +} + +/// The upload lists ready now, for the submission about to be made, which +/// runs them ahead of its own lists; their host slots are given their views. +/// Called by the thread that submits. +pub(crate) fn take_ready() -> Vec { + // (Asked without the lock by every submission of a run without it.) + if JOB.get().is_none() { + return Vec::new(); + } + let ready = std::mem::take(&mut *lock(&READY)); + STATS[2].fetch_add(ready.len() as u64, Relaxed); + ready + .into_iter() + .map(|r| { + for p in &r.publish { + let Some(host) = crate::descriptor::heap(p.heap as This).host() else { + continue; + }; + let shown = host.publish(p.index, p.handle, p.key); + STATS[if shown { 3 } else { 4 }].fetch_add(1, Relaxed); + } + r.list + }) + .collect() +} + +/// The heap the next pass is over, and what wakes the worker. +struct Job { + heap: Mutex>, + wake: Condvar, +} + +static JOB: OnceLock = OnceLock::new(); +/// Held by whoever runs the pass. +static PASS: Mutex<()> = Mutex::new(()); +/// A recording thread waits for [`PASS`]. +static URGENT: AtomicBool = AtomicBool::new(false); + +/// A pass over `heap` is due (once a frame). False if there is no worker: +/// the caller runs the pass itself. +pub(crate) fn kick(heap: &Heap) -> bool { + if !on() { + return false; + } + static STARTED: OnceLock = OnceLock::new(); + let started = *STARTED.get_or_init(|| { + JOB.get_or_init(|| Job { heap: Mutex::new(None), wake: Condvar::new() }); + match std::thread::Builder::new().name("victory-heap".into()).spawn(worker) { + Ok(_) => { + tracing::info!("textures picked by index are uploaded by a thread of their own (VICTORY_HEAP_WORKER)"); + true + } + Err(e) => { + tracing::warn!(error = %e, "no thread for textures picked by index"); + false + } + } + }); + let Some(job) = JOB.get().filter(|_| started) else { + return false; + }; + *lock(&job.heap) = Some(HeldHeap::new(heap)); + job.wake.notify_one(); + true +} + +/// Takes the pass from the worker for the caller, which cannot wait for a +/// later submission: what the worker has recorded so far is handed over +/// first, so the caller's list runs behind it. +pub(crate) fn urgent() -> MutexGuard<'static, ()> { + if let Ok(pass) = PASS.try_lock() { + return pass; + } + URGENT.store(true, Relaxed); + let pass = lock(&PASS); + URGENT.store(false, Relaxed); + pass +} + +/// Whether the worker is to stop where it is ([`urgent`]). +pub(crate) fn make_way() -> bool { + URGENT.load(Relaxed) +} + +fn worker() { + let Some(job) = JOB.get() else { + return; + }; + loop { + let heap = { + let mut next = lock(&job.heap); + loop { + match next.take() { + Some(heap) => break heap, + None => next = job.wake.wait(next).unwrap_or_else(|e| e.into_inner()), + } + } + }; + let started = std::time::Instant::now(); + { + let _pass = lock(&PASS); + let heap = heap.heap(); + if let Some(host) = heap.host() { + let mut batch = Batch::new(heap); + crate::draw::State::heap_textures(crate::draw::Into::Ahead(&mut batch), heap, host); + } + } + STATS[0].fetch_add(started.elapsed().as_nanos() as u64, Relaxed); + // Whoever wants the pass now has it first. + while make_way() { + std::thread::yield_now(); + } + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 766e735d28..de2c1598fd 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -5057,11 +5057,19 @@ impl Host { /// the air, at the next point where what they do can be observed /// ([`late`] lists those points); their host lists are reset and kept /// for reuse then, as a queue does for the lists it ran. - pub(crate) fn execute_late(&self, lists: Vec, order: Vec) { + pub(crate) fn execute_late(&self, mut lists: Vec, mut order: Vec) { if order.is_empty() { crate::list::recycle(lists, &order); return; } + // Textures uploaded ahead (`crate::heap_worker`): their lists run + // before the title's. + let ahead = crate::heap_worker::take_ready(); + if !ahead.is_empty() { + let first = lists.len(); + order.splice(0..0, first..first + ahead.len()); + lists.extend(ahead.into_iter().map(crate::list::Detached::ours)); + } late_threads(); let sent = { let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect(); @@ -6717,6 +6725,21 @@ impl HostList { self.deferred().copies.push(Step::Texture(staging)); } + /// Detiles the textures the list uploads now, ahead of its submission + /// ([`crate::texture::Staging::refresh_ahead`]); how many were left. + pub(crate) fn refresh_textures_ahead(&self) -> u64 { + let textures: Vec<_> = self + .deferred() + .copies + .iter() + .filter_map(|step| match step { + Step::Texture(staging) => Some(staging.clone()), + _ => None, + }) + .collect(); + textures.iter().filter(|staging| !staging.refresh_ahead()).count() as u64 + } + /// Runs the list's submission-time steps; refreshes go into `batch` /// (the title's big buffers, a 174 MB one among them, are read by most /// lists of a submission, through many ranges). @@ -7510,6 +7533,18 @@ impl Meter { let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames; let picked_ms = crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames; + { + let [busy, detiling, lists, shown, again, left] = + std::array::from_fn::(|i| crate::heap_worker::STATS[i].swap(0, Ordering::Relaxed) as f64 / frames); + if busy > 0.0 { + tracing::info!( + "textures picked by index, their own thread (VICTORY_HEAP_WORKER), per frame: {:.1} ms at work, of them {:.1} detiling; \ + {lists:.1} lists, {shown:.0} slots shown, {again:.1} written again before, {left:.1} textures left to the submission", + busy / 1e6, + detiling / 1e6 + ); + } + } // Copies between depth textures and their colour twins, each way. let [twin_to_depth, twin_to_colour] = [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames); diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 82449abc5c..3cef3ac080 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -1536,7 +1536,9 @@ void main() { for i in 0..RECORDS as usize { let rec = &out_words[i * 6..(i + 1) * 6]; if rec[0] == (1 << 22) && rec[1] == 16 { - assert!(i == 1 || i == 2, "the first two real draws fit the budget"); + // Which two is the order of the atomics (the second group's can + // win on WARP): never the one that is no draw. + assert!(i != 0, "the record that is no draw must run empty (record {i})"); kept += 1; } else { assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed"); @@ -2156,6 +2158,7 @@ void work() { heap_pairs: [[Option; 2]; 2], tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2], targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2], + #[allow(dead_code)] // a test keeps it beside its tested twin depth_written: D3D12_CPU_DESCRIPTOR_HANDLE, depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE, stamps: ID3D12QueryHeap, diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index d4936077b8..ad8bbde102 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -34,6 +34,8 @@ pub mod frame; #[cfg(windows)] pub mod framelog; #[cfg(windows)] +mod heap_worker; +#[cfg(windows)] mod host; #[cfg(windows)] mod indirect; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 3bf89f3c9b..5a31c2adac 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -195,6 +195,11 @@ pub(crate) struct Detached { #[cfg(windows)] impl Detached { + /// A closed list of ours, to run among a title's. + pub(crate) fn ours(host: crate::host::HostList) -> Self { + Detached { host, _uploads: Vec::new(), _state: Default::default() } + } + pub(crate) fn host(&self) -> &crate::host::HostList { &self.host } @@ -242,7 +247,7 @@ fn pools() -> bool { /// A host list open for recording: one that has run, as a title's list is /// after its reset, or a new one. #[cfg(windows)] -fn fresh_list() -> Option { +pub(crate) fn fresh_list() -> Option { let idle = { let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); let taken = idle.0.pop(); diff --git a/crates/victory-gpu/src/object.rs b/crates/victory-gpu/src/object.rs index 156c92ded4..a60a484c33 100644 --- a/crates/victory-gpu/src/object.rs +++ b/crates/victory-gpu/src/object.rs @@ -71,6 +71,15 @@ pub(crate) extern "system" fn add_ref(this: This) -> u32 { unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1 } +/// Adds a reference to an object that has one; false if it has none any +/// more (its last one is being released). +#[cfg(windows)] +pub(crate) fn add_ref_alive(this: This) -> bool { + // SAFETY: `this` is one of our objects, not freed yet. + let refs = &unsafe { &*this }.refs; + refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n > 0).then(|| n + 1)).is_ok() +} + pub(crate) extern "system" fn release(this: This) -> u32 { // SAFETY: `this` is one of our objects. let refs = &unsafe { &*this }.refs; diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 244a76ccc0..ce651bfbc5 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1182,6 +1182,26 @@ fn textures() -> std::sync::MutexGuard<'static, std::collections::BTreeSet(self.0); + } +} + +/// Holds title texture `this` alive, for work on a thread the title knows +/// nothing of. `None` if it is no texture, or is being released. +#[cfg(windows)] +pub(crate) fn hold(this: This) -> Option { + // A texture leaves the table before it is freed, under this lock. + let all = textures(); + (all.contains(&(this as usize)) && crate::object::add_ref_alive(this)).then(|| Held(this)) +} + /// The title textures the host renders to or writes (targets, depth, /// unordered access), by the address of their memory: what a view the /// title places in that memory in another format shows ([`alias_of`]). A @@ -2549,7 +2569,7 @@ static PLACED_RAW: std::sync::Mutex static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// See [`PLACED_TWINS`]. -#[cfg(windows)] +#[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn placed_filler_twins() -> u64 { PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed) } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index da0a26835e..eb151300af 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2672,7 +2672,7 @@ impl Shadow { } OWN_WRITES[1].fetch_add(bytes.len() as u64, Ordering::Relaxed); let n = OWN_WRITES[0].fetch_add(1, Ordering::Relaxed) + 1; - if n % 16384 == 0 { + if n.is_multiple_of(16384) { tracing::info!( "what shaders wrote, stored through views of our own (VICTORY_BACK_OWN_VIEW=1), since the start: {n} stretches {} MB, {} pages noted current for the copy that wrote them (not copied in again), {} stretches written the old way", OWN_WRITES[1].load(Ordering::Relaxed) >> 20, diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index b9cf5719ed..d41a38b4a7 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -135,6 +135,9 @@ struct Last { asked: u64, /// The frame a partly mapped texture was last read in. partial: Option, + /// The frame it was read in ahead of its submission + /// ([`Staging::refresh_ahead`]). + ahead: Option, } // SAFETY: the staging mapping is written only at submission, under @@ -1023,7 +1026,9 @@ impl Staging { const HASH_EVERY: u64 = 8; let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked); last.asked = now; - let turn = crate::frame::current().wrapping_add((start >> 16) as u64).is_multiple_of(HASH_EVERY); + let frame = crate::frame::current(); + let turn = frame.wrapping_add((start >> 16) as u64).is_multiple_of(HASH_EVERY) + && last.ahead.is_none_or(|at| frame > at + 1); if unwritten && !turn { return 0; } @@ -1111,6 +1116,36 @@ impl Staging { size } + /// Detiles the texture memory into the staging buffer ahead of the + /// submission, on the thread of `crate::heap_worker`: read through the + /// kernel, so that the runtime's remapping never waits for it, whole or + /// not at all (the submission then does it, as ever). False if it was + /// not read. What the title writes after this is found at submission. + pub(crate) fn refresh_ahead(&self) -> bool { + let size = self.layout.size as usize; + let start = self.memory as usize; + let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); + let last = &mut *last; + if last.hash.is_some() || last.asked != 0 { + // Detiled before: the submission's check is cheap. + return true; + } + let asked = crate::watch::writes(start, start + size, false).or_else(|| crate::watch::writes(start, start + size, true)); + let Some((now, _)) = asked else { + return false; + }; + with_read(size, |read| { + if !crate::host::read_into(self.memory, read) { + return false; + } + last.hash = Some(blake3::hash(read)); + self.detile(read); + last.asked = now; + last.ahead = Some(crate::frame::current()); + true + }) + } + /// A refresh while the runtime is remapping title memory ([`no_wait`]): /// the texture is read through the kernel, which fails if a page of it /// is not there at this moment. Then nothing is taken and the texture