diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index d331dd46e6..dbed4416f1 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -371,10 +371,30 @@ static NEW_PENDING: std::sync::LazyLock Option { +thread_local! { + /// This thread is publishing an already-uploaded texture slot + /// ([`HostHeap::publish_uploaded_slot`] / [`HostHeap::publish_for_late`]): + /// `note_buffer` must not re-queue the slot in `TextureQueue`. + static PUBLISHING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +struct PublishingGuard(bool); + +impl PublishingGuard { + fn enter() -> Self { + PublishingGuard(PUBLISHING.replace(true)) + } +} + +impl Drop for PublishingGuard { + fn drop(&mut self) { + PUBLISHING.set(self.0); + } +} + +/// Resolves a texture view to its title resource and host texture, creating +/// the host texture if it does not exist yet (as [`make`] would). +fn texture_of_view<'a>(view: &View) -> Option<(crate::object::This, &'a ID3D12Resource)> { // (Resolved first: the texture made here, a moment ago, is the case.) let shader = match view { View::Placed(false, resource, _) if resource[0] != 1 => placed_texture(view)?, @@ -384,10 +404,35 @@ fn begun_before(view: &View) -> Option { let View::Shader(resource, _) = shader else { return None; }; - let texture = crate::resource::host_resource(resource as crate::object::This)?; + let resource = resource as crate::object::This; + let texture = crate::resource::host_resource(resource)?; + Some((resource, texture)) +} + +/// The submissions begun when the host texture `view` shows was made, if +/// one begun before that may still run (`crate::pool::begun_before`). The +/// host texture is made here if it is not yet, as [`make`] would. +fn begun_before(view: &View) -> Option { + let (_, texture) = texture_of_view(view)?; crate::pool::begun_before(texture) } +/// Deferred fence ceiling for a list-less (`same`-only) late publish, +/// combining `VICTORY_SHOW_NEW_LATER` (`new_later`) and `VICTORY_SHOW_AFTER` +/// (`show_after_on` with in-flight submissions and a fresh non-ahead texture). +fn late_same_after( + new_later: Option, + show_after_on: bool, + submissions: (u64, u64), + fresh_not_ahead: impl FnOnce() -> bool, +) -> Option { + let mut after = new_later; + if show_after_on && submissions.0 > submissions.1 && fresh_not_ahead() { + after = after.max(Some(submissions.0)); + } + after +} + /// Slots shown late ([`show_after`]), the frames they waited, the longest; /// those that were given the neutral texture meanwhile; those not shown any /// more when their time came. @@ -2805,28 +2850,28 @@ impl HostHeap { matches!((view(shown), view(key)), (Some(a), Some(b)) if same_placed_texture(&a, &b)) } - /// Slot `index` is made from the record at `handle` (what it is now) + /// Slot `index` is made from the record at `handle` (pinned to `key`) /// when `list`, which holds the upload of what that view shows, has run: /// until then it shows what it showed. (Made at once, the frames on the /// card read the new view before its levels were filled.) - pub(crate) fn texture_slot_flip(&self, list: &crate::host::HostList, index: u32, handle: u64) { - self.flip(list, index, handle, None); + pub(crate) fn texture_slot_flip(&self, list: &crate::host::HostList, index: u32, handle: u64, key: u64) { + self.flip(list, index, handle, key, None); } /// The same of a slot that shows nothing of the texture the record at /// `handle` views, or something else: until then it shows the neutral /// texture ([`show_after`]). - pub(crate) fn texture_slot_show_after(&self, list: &crate::host::HostList, index: u32, handle: u64) { - if self.show_later(index, handle) { - self.flip(list, index, handle, Some(crate::frame::current())); + pub(crate) fn texture_slot_show_after(&self, list: &crate::host::HostList, index: u32, handle: u64, key: u64) { + if self.show_later(index, handle, key) { + self.flip(list, index, handle, key, Some(crate::frame::current())); } } - /// What slot `index` shows until the texture the record at `handle` views - /// is shown. False: it shows it, or there is none. - fn show_later(&self, index: u32, handle: u64) -> bool { + /// What slot `index` shows until the texture of record `key` is shown. + /// False: it shows it, there is none, or the title has written another + /// record to `handle` since `key` was read. + fn show_later(&self, index: u32, handle: u64, key: u64) -> bool { use std::sync::atomic::Ordering::Relaxed; - let key = record_key(handle); let view = view_at(key as u32, (key >> 32) as u32); let (true, Some(view)) = (key != 0, view) else { return false; @@ -2836,7 +2881,7 @@ impl HostHeap { let Some(shown) = self.made.get(index) else { return false; }; - if shown == key { + if shown == key || record_key(handle) != key { return false; } // (As `mirror`.) @@ -2865,11 +2910,11 @@ impl HostHeap { /// [`HostHeap::texture_slot_show_after`] of a texture whose upload `job` /// makes: shown when that has run. - pub(crate) fn texture_slot_show_ahead(&self, job: &crate::texture::ahead::Job, index: u32, handle: u64) { - if !self.show_later(index, handle) { + pub(crate) fn texture_slot_show_ahead(&self, job: &crate::texture::ahead::Job, index: u32, handle: u64, key: u64) { + if !self.show_later(index, handle, key) { return; } - let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); + let heap = std::ptr::from_ref(self) as usize; let late = Some(crate::frame::current()); job.then(move || { let flip = Flip { after: 0, heap, index, handle, key, late }; @@ -2885,20 +2930,20 @@ impl HostHeap { && !crate::texture::BAKING.get() && index < self.count && !self.texture_slot_made_from(index, handle) - && let Some(view) = super::view(handle) + && let Some((view, key)) = self.prepare_texture_slot(index, handle) && let Some(View::Shader(resource, _)) = placed_texture(&view).or(Some(view)) && crate::resource::buffer_bytes(resource as crate::object::This).is_none() && crate::resource::host_resource(resource as crate::object::This).is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource as crate::object::This) { - return self.texture_slot_show_after(list, index, handle); + return self.texture_slot_show_after(list, index, handle, key); } self.mirror(index, handle, true); } - fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, late: Option) { + fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, key: u64, late: Option) { use std::sync::atomic::Ordering::{Relaxed, Release}; - let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); + let heap = std::ptr::from_ref(self) as usize; let id = NEXT_PENDING_FLIP.fetch_add(1, Relaxed); let origin = (std::ptr::from_ref(list) as usize, list.epoch()); { @@ -2987,11 +3032,12 @@ impl HostHeap { key != 0 && record_key(handle) == key } - /// Looks up `(view, key)` for slot `index` prior to a synchronous bake - /// upload without replacing its current host descriptor with `neutral()`; - /// [`HostHeap::publish_uploaded_slot`] exposes the real descriptor and - /// updates `Spans`/stride tracking once the GPU copy finishes. - pub(crate) fn prepare_bake_slot(&self, index: u32, handle: u64) -> Option<(View, u64)> { + /// The view of the record at `handle` and its key, read once and without + /// touching what slot `index` shows. The upload of that view and what + /// shows it later ([`HostHeap::publish_uploaded_slot`], the flips) all + /// refer to this key, so a record the title writes to the slot meanwhile + /// is never shown on the strength of the replaced record's upload. + pub(crate) fn prepare_texture_slot(&self, index: u32, handle: u64) -> Option<(View, u64)> { if index >= self.count { return None; } @@ -3000,14 +3046,29 @@ impl HostHeap { Some((view, key)) } - /// Exposes the real host descriptor for slot `index` after its synchronous - /// bake upload has completed on the GPU, updating `Spans`/stride tracking - /// without re-queuing the slot in `TextureQueue`. + /// Exposes the real host descriptor for slot `index` after its upload has + /// completed (or is ready to publish without `VICTORY_SHOW_AFTER` / + /// `VICTORY_SHOW_NEW_LATER`), updating `Spans`/stride tracking without + /// re-queuing the slot in `TextureQueue`. pub(crate) fn publish_uploaded_slot(&self, index: u32, handle: u64, key: u64) -> bool { - if index >= self.count || key == 0 { + self.publish_uploaded_slot_with(index, handle, key, || {}) + } + + /// Key-pinned core of [`HostHeap::publish_uploaded_slot`]. Re-verifies + /// `record_key(handle) == key` under `self.made.lock(index)` and builds + /// the descriptor strictly from `key` (never re-reading `handle`). + fn publish_uploaded_slot_with( + &self, + index: u32, + handle: u64, + key: u64, + between_check_and_install: impl FnOnce(), + ) -> bool { + if index >= self.count || key == 0 || record_key(handle) != key { return false; } - let (published, stale) = { + between_check_and_install(); + let (published, stale, requeue) = { let _made = self.made.lock(index); if self.made.get(index) == Some(key) { return false; @@ -3018,22 +3079,152 @@ impl HostHeap { let Some(view) = view_at(key as u32, (key >> 32) as u32) else { return false; }; - let stale = self.note_buffer(index, Some(&view), true); + let stale = { + let _publishing = PublishingGuard::enter(); + self.note_buffer(index, Some(&view), true) + }; if let Some(kept) = make(&view, self.at(index)) { - self.put(index); self.quick_is(index, 0); + self.put(index); self.clear_twin(index); self.made.set(index, key); self.keep(index, kept); - (true, stale) + self.quick_is(index, key); + (true, stale, false) } else { - (false, stale) + (false, stale, crate::residency::upload_refused()) } }; + if requeue { + self.queue_texture(index, true, false, crate::frame::current()); + } self.unmake_stale(index, stale); published } + /// Publishes an already-uploaded worker slot for a late submission + /// (`crate::heap_worker::take_ready_for_late`). + /// + /// Preserves `VICTORY_HELD_LEVELS=1` (`shows_other` mip-upgrade deferral + /// when `list` is `Some`), `VICTORY_SHOW_AFTER=1` (for both upload-list + /// batches and `same`-only batches without a list), and + /// `VICTORY_SHOW_NEW_LATER=1` (when earlier flights may still run on the + /// GPU) via `show_later` and `flip` / `FLIPS` instead of publishing + /// immediately. Never calls `mirror()` and never builds `View` by + /// re-reading `handle`. + pub(crate) fn publish_for_late( + &self, + list: Option<&crate::host::HostList>, + index: u32, + handle: u64, + key: u64, + ) -> bool { + if index >= self.count || key == 0 || record_key(handle) != key { + return false; + } + let Some(view) = view_at(key as u32, (key >> 32) as u32) else { + return false; + }; + if let Some(worker_list) = list { + if !self.sampler + && crate::resource::held_only() + && let Some(shown) = self.made.get(index) + && shown != 0 + && shown != key + && view_at(shown as u32, (shown >> 32) as u32) + .is_some_and(|old| same_placed_texture(&old, &view)) + { + self.flip(worker_list, index, handle, key, None); + return true; + } + if show_after() { + let shown = { + let _publishing = PublishingGuard::enter(); + self.show_later(index, handle, key) + }; + if shown { + self.flip(worker_list, index, handle, key, Some(crate::frame::current())); + } + return shown; + } + } + let check_new_later = show_new_later(); + let check_show_after = list.is_none() && show_after(); + if !self.sampler && (check_new_later || check_show_after) && is_texture_view(&view) { + let submissions = if check_show_after { + crate::host::submissions() + } else { + (0, 0) + }; + let check_fresh = check_show_after && submissions.0 > submissions.1; + let (after, from_new_later) = if !check_new_later && !check_fresh { + (None, false) + } else if let Some((resource, texture)) = texture_of_view(&view) { + let new_later = if check_new_later { + crate::pool::begun_before(texture) + } else { + None + }; + let after = late_same_after(new_later, check_show_after, submissions, || { + crate::pool::fresh(texture) && !crate::texture::ahead::there(resource) + }); + (after, new_later.is_some()) + } else { + if crate::residency::upload_refused() { + self.queue_texture(index, true, false, crate::frame::current()); + return false; + } + (None, false) + }; + if let Some(after) = after { + if let Some(worker_list) = list { + let shown = { + let _publishing = PublishingGuard::enter(); + self.show_later(index, handle, key) + }; + if shown { + self.flip(worker_list, index, handle, key, Some(crate::frame::current())); + NEW_LATER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + return shown; + } + let own = (std::ptr::from_ref(self) as usize, index, key); + if !NEW_PENDING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(own) + { + return true; + } + let shown = { + let _publishing = PublishingGuard::enter(); + self.show_later(index, handle, key) + }; + if shown { + let flip = Flip { + after, + heap: std::ptr::from_ref(self) as usize, + index, + handle, + key, + late: Some(crate::frame::current()), + }; + FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip); + if from_new_later { + NEW_LATER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } else { + NEW_PENDING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&own); + } + return shown; + } + } + self.publish_uploaded_slot(index, handle, key) + } + /// Makes the slots whose new view's upload has run /// ([`HostHeap::texture_slot_flip`]); returns how many. pub(crate) fn texture_slots_flip(&self) -> usize { @@ -3303,6 +3494,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 @@ -4127,6 +4321,12 @@ impl HostHeap { self.made.get(index).is_some_and(|key| key != 0) } + /// The record key slot `index` is currently made from, or 0 (tests). + #[cfg(test)] + pub(crate) fn made_key(&self, index: u32) -> u64 { + self.made.get(index).unwrap_or(0) + } + /// Whether host slot `index` shows `buffer`; `None` if it shows no /// resource (diagnostics: a buffer view's slot must show the host copy /// that is brought up to date for it). @@ -7104,4 +7304,148 @@ mod bake_flip_tests { drop(cb2); assert!(take_pending_list_flip(id2).is_none(), "dropping uncalled closure cleans up entry"); } + + /// Deterministic TOCTOU regression test: if the title replaces the slot's + /// record between the initial key check and descriptor installation, + /// `publish_uploaded_slot_with` rejects the publish and never exposes the + /// unuploaded replacement view. + #[test] + fn publish_rejects_slot_replaced_between_reads() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + 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 mut title = [0u32; 8]; + let handle = title.as_mut_ptr() as u64; + crate::descriptor::record(handle, view(0x7fec_0000_0000)); + let (first, key_a) = heap.prepare_texture_slot(1, 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); + heap.texture_slot_done(1, write, None); + assert!(!heap.made(1)); + + let shown = heap.publish_uploaded_slot_with(1, handle, key_a, || { + crate::descriptor::record(handle, view(0x7feb_0000_0000)); + }); + let (_, key_b) = heap.prepare_texture_slot(1, handle).unwrap(); + assert_ne!(key_a, key_b); + assert!(!shown); + assert!(!heap.made(1)); + assert_eq!(heap.made_key(1), 0); + assert_ne!(heap.made_key(1), key_b); + } + + /// A slot published after `texture_slot_done` stays out of `TextureQueue` + /// (`PUBLISHING` suppresses re-queueing in `note_buffer`), and a later + /// rewrite cannot be published under the stale key. + #[test] + fn published_slot_stays_out_of_texture_queue() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + 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 mut title = [0u32; 8]; + let handle = title.as_mut_ptr() as u64; + crate::descriptor::record(handle, view(0x7fec_0000_0000)); + let (first, key_a) = heap.prepare_texture_slot(1, 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); + heap.texture_slot_done(1, write, None); + assert!(!heap.made(1)); + + assert!(heap.publish_uploaded_slot(1, handle, key_a)); + assert!(heap.made(1)); + assert_eq!(heap.made_key(1), key_a); + assert!(heap.texture_slots_due(u64::MAX, 8).0.is_empty()); + + crate::descriptor::record(handle, view(0x7feb_0000_0000)); + assert!(!heap.publish_uploaded_slot(1, handle, key_a)); + assert_eq!(heap.made_key(1), key_a); + } + + #[test] + fn publish_for_late_same_after_combines_show_after_and_new_later() { + let mut probed = false; + assert_eq!( + late_same_after(None, false, (10, 8), || { + probed = true; + true + }), + None + ); + assert!(!probed); + assert_eq!(late_same_after(None, true, (10, 10), || true), None); + assert_eq!(late_same_after(None, true, (10, 8), || false), None); + assert_eq!(late_same_after(None, true, (10, 8), || true), Some(10)); + assert_eq!(late_same_after(Some(9), true, (10, 8), || true), Some(10)); + assert_eq!(late_same_after(Some(12), true, (10, 8), || true), Some(12)); + assert_eq!(late_same_after(Some(9), false, (10, 8), || true), Some(9)); + } + + /// Under `VICTORY_HELD_LEVELS=1` (default) and `VICTORY_SHOW_AFTER=0` + /// (default), a worker upload replacing a slot with another view of the + /// same placed texture (e.g. a sharper mip) defers via `flip(..., None)` + /// instead of overwriting the live descriptor immediately. + #[test] + fn publish_for_late_defers_shows_other_mip_upgrade() { + let Some(gpu) = host() else { + return; + }; + let Some(heap) = HostHeap::new(false, 8) else { + return; + }; + let list = gpu.new_list().unwrap(); + let view = |first_mip: u32, mip_levels: u32| { + let mut desc = [0u32; 16]; + (desc[0], desc[1], desc[2], desc[4], desc[5]) = (98, 4, 5768, first_mip, mip_levels); + let at = 0x7fea_0000_0000u64; + (desc[10], desc[11]) = (at as u32, (at >> 32) as u32); + View::Placed( + false, + [3, 0, 0, 0, 64, 0, 64, 0x2_0001, 98, 1, 0, 0x105, 0, 0], + desc, + ) + }; + let coarse = view(1, 1); + let sharp = view(0, 2); + assert!(same_placed_texture(&coarse, &sharp)); + + let mut title = [0u32; 8]; + let handle = title.as_mut_ptr() as u64; + crate::descriptor::record(handle, coarse); + let (_, key_coarse) = heap.prepare_texture_slot(1, handle).unwrap(); + assert!(heap.publish_uploaded_slot(1, handle, key_coarse)); + assert_eq!(heap.made_key(1), key_coarse); + + crate::descriptor::record(handle, sharp); + let (_, key_sharp) = heap.prepare_texture_slot(1, handle).unwrap(); + assert_ne!(key_coarse, key_sharp); + + assert!(heap.publish_for_late(Some(&list), 1, handle, key_sharp)); + assert_eq!(heap.made_key(1), key_coarse); + let pending = heap.take_pending_list_flips(); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].key(), key_sharp); + assert!(pending[0].flip.late.is_none()); + } } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e3a7be8bf5..db8743c1e0 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -316,7 +316,7 @@ static BAKE_UPLOAD: std::sync::Mutex> = std::sync::Mutex::new(N /// Pending descriptor publications for a synchronous bake upload pass: slots /// stay on `neutral()` (or their previous compatible view) until the dedicated /// upload list has finished executing on the host GPU. -struct BakeSync { +pub(crate) struct BakeSync { publish: Vec<(u32, u64, u64)>, keep: Vec>, } @@ -1158,6 +1158,13 @@ fn set(roots: &mut Vec, slot: u32, root: Root) -> bool { const CONSTANTS: usize = 0; const OTHERS: usize = 1; +/// 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 TextureTarget<'a> { + List(&'a HostList), + Ahead(&'a mut crate::heap_worker::Batch), +} + /// The pass over the buffer views of `heap` that shaders pick by index /// ([`State::heap_buffers`]): their host slots are made, and the host copies /// they show are to be refreshed. @@ -2423,7 +2430,9 @@ impl State { #[cfg(feature = "diagnostics")] let refreshed = std::time::Instant::now(); stage.next("the heap pass: textures"); - let _ = self.heap_textures(list, heap, host, None); + if !crate::heap_worker::kick(heap) { + let _ = Self::heap_textures(TextureTarget::List(list), heap, host, None); + } stage.end(); #[cfg(feature = "diagnostics")] HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed); @@ -2465,7 +2474,8 @@ impl State { mut sync: Option<&mut BakeSync>, ) { static RESCUED: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; - let drained = crate::texture::ahead::drain(); + let drained = crate::texture::ahead::drain() + + crate::host::host().map_or(0, crate::heap_worker::drain_for_bake); let mut settled = false; let mut flipped = 0usize; for _ in 0..4 { @@ -2704,7 +2714,7 @@ impl State { n[0] = 1; for index in self.bake_sources(p, heap) { let Some(handle) = heap.handle(index) else { continue }; - let Some((view, key)) = host.prepare_bake_slot(index, handle) else { continue }; + let Some((view, key)) = host.prepare_texture_slot(index, handle) else { continue }; n[1] += 1; let placed = crate::descriptor::host::placed_texture(&view); let resource = match placed.as_ref().or(Some(&view)) { @@ -2840,6 +2850,7 @@ impl State { if is_bake { let began = std::time::Instant::now(); let mut bake_slot = BAKE_UPLOAD.lock().unwrap_or_else(|e| e.into_inner()); + let _pass = crate::heap_worker::on().then(crate::heap_worker::urgent); let gpu = crate::host::host(); if bake_slot.is_none() && let Some(gpu) = gpu @@ -2878,7 +2889,12 @@ impl State { } BAKE_SERVED.store(0, Ordering::Relaxed); PASS_BUDGET.set(Some((left, 2 << 30, true))); - served = self.heap_textures(bake_list, heap, host, Some(&mut sync)); + served = Self::heap_textures( + TextureTarget::List(bake_list), + heap, + host, + Some(&mut sync), + ); PASS_BUDGET.set(None); } // Whatever the pass got to: the slots this very draw picks @@ -2924,7 +2940,7 @@ impl State { EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed); PASS_BUDGET.set(Some((left, 2 << 30, true))); crate::texture::BAKING.set(exact); - let _ = self.heap_textures(list, heap, host, None); + let _ = Self::heap_textures(TextureTarget::List(list), heap, host, None); crate::texture::BAKING.set(false); PASS_BUDGET.set(None); BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); @@ -2935,9 +2951,13 @@ impl State { } else { return; }; + // What can wait for a later list is the worker's. + if crate::heap_worker::kick(heap) { + return; + } EARLY_TEXTURE_PASSES[0].fetch_add(1, Ordering::Relaxed); PASS_BUDGET.set(Some((budget.0, budget.1, false))); - let _ = self.heap_textures(list, heap, host, None); + let _ = Self::heap_textures(TextureTarget::List(list), heap, host, None); PASS_BUDGET.set(None); } @@ -2991,9 +3011,9 @@ impl State { None => Some((0, crate::resource::placed_bytes(&resource).unwrap_or(0), address)), } } - Some(View::Shader(object, _)) if crate::resource::title_fills(object as This) => { - crate::resource::copy_state(object as This) - } + Some(View::Shader(object, _)) => crate::resource::hold(object as This) + .filter(|_| crate::resource::title_fills(object as This)) + .and_then(|_held| crate::resource::copy_state(object as This)), _ => None, }; let Some((state, bytes, memory)) = state else { @@ -3030,9 +3050,10 @@ 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 when submitted (`crate::heap_worker`). + pub(crate) fn heap_textures( + mut into: TextureTarget<'_>, heap: &crate::descriptor::Heap, host: &crate::descriptor::host::HostHeap, mut sync: Option<&mut BakeSync>, @@ -3155,9 +3176,12 @@ impl State { // half a frame per second, while the title streams by the clock. // (About a second before the runtime told of the memory it maps: // the looks are now only for what that does not tell.) + let worker = matches!(into, TextureTarget::Ahead(_)); 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 worker { 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 { @@ -3242,6 +3266,10 @@ impl State { served = false; break; } + if worker && crate::heap_worker::make_way() { + served = false; + break; + } outcome(slot_outcome::TAKEN); // A placed texture whose memory is not mapped (not streamed in // yet, or streamed out again: the heap keeps tens of thousands @@ -3313,9 +3341,28 @@ impl State { } let mut partly = None; let mut there = None; - // The view the slot holds now, read once for the looks below. - let held = rest(1, || heap.handle(index).and_then(crate::descriptor::view)); - if let Some(View::Placed(false, resource, desc)) = &held { + // The record the slot has now, read once, 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 = rest(1, || { + heap.handle(index).and_then(|handle| { + host.prepare_texture_slot(index, handle) + .map(|(view, key)| (handle, view, key)) + }) + }); + let _held = match &record { + Some((_, View::Shader(object, _), _)) if worker => { + let held = crate::resource::hold(*object as This); + if held.is_none() { + outcome(slot_outcome::NOTHING); + tells.tell(index, write, Told::Done(None)); + continue; + } + held + } + _ => None, + }; + if let Some((_, View::Placed(false, resource, desc), _)) = &record { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let first = crate::resource::first_mip(desc); let len = crate::resource::placed_bytes_from(resource, first).unwrap_or(1); @@ -3347,9 +3394,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, _)) = held - && 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) { outcome(slot_outcome::NOTHING); HEAP_TEXTURE_NOTHING[0].fetch_add(1, Ordering::Relaxed); @@ -3371,7 +3418,11 @@ impl State { // before. if !room { let has_its_texture = reupload_when_full() - && rest(1, || heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle))); + && rest(1, || { + record + .as_ref() + .is_some_and(|&(handle, _, _)| host.texture_slot_made_from(index, handle)) + }); if !has_its_texture { refused += 1; outcome(slot_outcome::HELD); @@ -3408,34 +3459,51 @@ impl State { // from another level) goes on doing so until the upload of what // the new one shows has run. let sync_bake = sync.is_some(); - let shows_other = !baking + let shows_other = !worker + && !baking && !sync_bake && crate::resource::held_only() - && rest(1, || heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle))); + && rest(1, || { + record + .as_ref() + .is_some_and(|&(handle, _, _)| host.texture_slot_shows_other(index, handle)) + }); // A slot that shows nothing of it yet, or something else, shows it // when the upload has run too. - let late = !shows_other + let show_after_slot = !shows_other && !baking && !sync_bake && crate::descriptor::host::show_after() - && rest(1, || heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle))); - let (view, bake_key) = timed(6, || { - if sync_bake { - match heap.handle(index).and_then(|handle| host.prepare_bake_slot(index, handle)) { - Some((view, key)) => (Some(view), Some(key)), + && rest(1, || { + record + .as_ref() + .is_some_and(|&(handle, _, _)| !host.texture_slot_made_from(index, handle)) + }); + let late = !worker && show_after_slot; + // The view and the record it came from are read once: the upload + // and whatever shows the slot later refer to that record, not to + // one the title wrote to the slot meanwhile. On the worker, never + // call `mirror()` directly. + let (view, upload_key) = timed(6, || { + if worker || sync_bake || shows_other || late { + match &record { + Some((_, view, key)) => (Some(view.clone()), Some(*key)), None => (None, None), } - } else if shows_other || late { - // The view read at the start of this slot's turn (read - // again, the views' table was asked twice a slot). - (held.clone(), None) } else { - (heap.handle(index).and_then(|handle| host.mirror(index, handle, true)), None) + ( + record + .as_ref() + .and_then(|&(handle, _, _)| host.mirror(index, handle, true)), + None, + ) } }); // (`nothing`: the slot has nothing to bring up to date.) let at_once = |nothing: bool| { - if (late || bake_key.is_some()) && let Some(handle) = heap.handle(index) { + if (late || (sync_bake && upload_key.is_some())) + && let Some(&(handle, _, _)) = record.as_ref() + { HEAP_TEXTURE_NOTHING[3].fetch_add(u64::from(nothing), Ordering::Relaxed); shown(0, || { let _ = host.mirror(index, handle, true); @@ -3464,7 +3532,16 @@ impl State { } let title_fills = rest(6, || texture.is_some_and(crate::texture::title_written)); if !title_fills { - at_once(true); + if let TextureTarget::Ahead(batch) = &mut into { + if texture.is_some() + && let (Some(&(handle, _, _)), Some(key)) = (record.as_ref(), upload_key) + && !host.texture_slot_made_from(index, handle) + { + batch.publish(index, handle, key); + } + } else { + at_once(true); + } // a render target, a depth or unordered access texture: the host's own outcome(slot_outcome::NOTHING); HEAP_TEXTURE_NOTHING[2].fetch_add(1, Ordering::Relaxed); @@ -3484,21 +3561,29 @@ impl State { if same { HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed); outcome(slot_outcome::SAME); - if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) { + if let (Some(sync), Some(key), Some(&(handle, _, _))) = + (sync.as_deref_mut(), upload_key, record.as_ref()) + { if let Some(copy) = crate::resource::host_copy(resource) { sync.keep.push(copy); } sync.publish.push((index, handle, key)); - } else { - if shows_other && let Some(handle) = heap.handle(index) { + } else if let TextureTarget::Ahead(batch) = &mut into { + if let (Some(&(handle, _, _)), Some(key)) = (record.as_ref(), upload_key) + && !host.texture_slot_made_from(index, handle) + { + batch.publish(index, handle, key); + } + } else if let TextureTarget::List(list) = &into { + if shows_other && let Some(&(handle, _, _)) = record.as_ref() { shown(2, || { let _ = host.mirror(index, handle, true); }); } // Its bytes are in, or on the way there in a list before. if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) { - if let Some(handle) = heap.handle(index) { - shown(1, || host.texture_slot_show_after(list, index, handle)); + if let (Some(&(handle, _, _)), Some(key)) = (record.as_ref(), upload_key) { + shown(1, || host.texture_slot_show_after(list, index, handle, key)); } } else { at_once(false); @@ -3517,7 +3602,7 @@ impl State { } // The first upload of a texture no list has used: on a queue of // its own, and the slot shows it as soon as that has run. - let ahead = if late && !tabled && texture.is_some_and(crate::pool::fresh) { + let ahead = if show_after_slot && !tabled && texture.is_some_and(crate::pool::fresh) { rest(3, || { crate::texture::ahead::take(resource, first, there.filter(|_| partly.is_none()).unwrap_or(u64::MAX)) }) @@ -3528,8 +3613,8 @@ impl State { use crate::texture::ahead::Taken; let (Taken::New(job) | Taken::Known(job)) = ahead; rest(3, || { - if let Some(handle) = heap.handle(index) { - host.texture_slot_show_ahead(job, index, handle); + if let (Some(&(handle, _, _)), Some(key)) = (record.as_ref(), upload_key) { + host.texture_slot_show_ahead(job, index, handle, key); } if let Taken::New(job) = ahead { crate::texture::ahead::send(job); @@ -3545,6 +3630,13 @@ impl State { if let Some(view) = &view && ahead.is_none() { + let list = match &mut into { + TextureTarget::List(list) => *list, + TextureTarget::Ahead(batch) => match batch.list() { + Some(list) => list, + None => return false, + }, + }; // (What was found mapped of it a moment ago is not asked // again, unless the host copy may need more.) crate::texture::PICKING.set(Some(there.filter(|_| partly.is_none()).unwrap_or(u64::MAX))); @@ -3560,21 +3652,41 @@ impl State { served = false; break; } - if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) { + if ahead.is_none() + && let TextureTarget::Ahead(batch) = &mut into + && let (Some(&(handle, _, _)), Some(key)) = (record.as_ref(), upload_key) + && !host.texture_slot_made_from(index, handle) + { + batch.publish(index, handle, key); + } + if let (Some(sync), Some(key), Some(&(handle, _, _))) = + (sync.as_deref_mut(), upload_key, record.as_ref()) + { if let Some(copy) = crate::resource::host_copy(resource) { sync.keep.push(copy); } sync.publish.push((index, handle, key)); } - if shows_other && let Some(handle) = heap.handle(index) { - shown(2, || host.texture_slot_flip(list, index, handle)); - } - if late && let Some(handle) = heap.handle(index) { - shown(1, || host.texture_slot_show_after(list, index, handle)); + if let TextureTarget::List(list) = &into { + if shows_other + && let (Some(&(handle, _, _)), Some(key)) = (record.as_ref(), upload_key) + { + shown(2, || host.texture_slot_flip(list, index, handle, key)); + } + if late + && let (Some(&(handle, _, _)), Some(key)) = (record.as_ref(), upload_key) + { + shown(1, || host.texture_slot_show_after(list, index, handle, key)); + } } #[cfg(feature = "diagnostics")] if crate::book::on() + && ahead.is_none() && let Some(texture) = texture.filter(|t| crate::pool::fresh(t)) + && let Some(list) = match &into { + TextureTarget::List(list) => Some(*list), + TextureTarget::Ahead(batch) => batch.open_list(), + } { use windows::core::Interface; let raw = texture.as_raw() as usize; @@ -3634,6 +3746,11 @@ impl State { }); rest(6, || crate::texture::unstage(resource)); SPENT.fetch_add(bytes, Ordering::Relaxed); + if ahead.is_none() + && let TextureTarget::Ahead(batch) = &mut into + { + batch.uploaded(bytes); + } since_asked += bytes; if room && since_asked >= 32 << 20 { since_asked = 0; diff --git a/crates/victory-gpu/src/heap_worker.rs b/crates/victory-gpu/src/heap_worker.rs new file mode 100644 index 0000000000..eb11ec8b4a --- /dev/null +++ b/crates/victory-gpu/src/heap_worker.rs @@ -0,0 +1,444 @@ +//! 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` / +//! `VICTORY_RELAY`). +//! +//! [`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_for_late`]): 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`]), and always through a key-pinned publish that builds the +//! descriptor from the recorded key rather than re-reading the title's +//! slot. Under `VICTORY_SHOW_AFTER=1` or `VICTORY_SHOW_NEW_LATER=1`, the +//! descriptor flip waits until the upload list's submission completes. 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 (except for `once` +//! textures, which skip write-watching just as on the recording thread); +//! - 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`]), and any batches already flushed to [`READY`] +//! are executed synchronously and published first ([`drain_for_bake`]). +// 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::{AtomicU64, AtomicUsize, 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 = 128 << 20; +const LIST_MS: u128 = 80; + +/// 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 (or `None` when a pass only found already-uploaded +/// textures), and what is published when it is submitted. +struct Ready { + list: Option, + 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() + } + + /// The currently open upload list, if one has been created. + #[cfg(feature = "diagnostics")] + pub(crate) fn open_list(&self) -> Option<&HostList> { + self.list.as_ref() + } + + /// Slot `index` (its record at `handle`, then with `key`) shows its + /// texture when the open list is submitted. + 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. Also flushes `same`-only publishes without + /// allocating an empty D3D12 command list. + fn flush(&mut self) { + self.bytes = 0; + let publish = std::mem::take(&mut self.publish); + let list = self.list.take(); + if list.is_none() && publish.is_empty() { + return; + } + if let Some(list) = &list { + 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 late submission about to be made, +/// which runs them ahead of its own lists; their host slots are published +/// (or scheduled for deferred flip under `VICTORY_SHOW_AFTER` / +/// `VICTORY_SHOW_NEW_LATER`). Called by the thread that submits. +pub(crate) fn take_ready_for_late() -> 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)); + let mut out = Vec::with_capacity(ready.len()); + for r in ready { + for p in &r.publish { + let Some(host) = crate::descriptor::heap(p.heap as This).host() else { + continue; + }; + let shown = host.publish_for_late(r.list.as_ref(), p.index, p.handle, p.key); + STATS[if shown { 3 } else { 4 }].fetch_add(1, Relaxed); + } + if let Some(list) = r.list { + out.push(list); + } + } + STATS[2].fetch_add(out.len() as u64, Relaxed); + out +} + +/// Executes and publishes any worker batches already flushed to [`READY`] +/// before a synchronous decoration bake runs. Called while holding [`PASS`] +/// via [`urgent`], so no worker pass can flush concurrently. +pub(crate) fn drain_for_bake(gpu: &crate::host::Host) -> usize { + if JOB.get().is_none() { + return 0; + } + let ready = std::mem::take(&mut *lock(&READY)); + if ready.is_empty() { + return 0; + } + let mut lists = Vec::new(); + let mut publishes = Vec::new(); + let mut heaps = Vec::new(); + for r in ready { + if let Some(list) = r.list { + lists.push(list); + } + publishes.extend(r.publish); + heaps.push(r._heap); + } + let list_count = lists.len(); + if !lists.is_empty() { + STATS[2].fetch_add(list_count as u64, Relaxed); + let refs: Vec<&HostList> = lists.iter().collect(); + gpu.execute_sync_internal_many(&refs); + let order: Vec = (0..lists.len()).collect(); + let detached: Vec<_> = lists + .into_iter() + .map(crate::list::Detached::ours) + .collect(); + crate::list::recycle(detached, &order); + } else if !publishes.is_empty() { + crate::host::settle_for_fence(); + } + let mut shown_count = 0usize; + for p in &publishes { + let Some(host) = crate::descriptor::heap(p.heap as This).host() else { + continue; + }; + let shown = host.publish_uploaded_slot(p.index, p.handle, p.key); + STATS[if shown { 3 } else { 4 }].fetch_add(1, Relaxed); + if shown { + shown_count += 1; + } + } + drop(heaps); + shown_count.max(list_count) +} + +/// 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(()); +/// Number of recording threads waiting for [`PASS`]. +static URGENT: AtomicUsize = AtomicUsize::new(0); + +/// 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; + }; + let _prev = lock(&job.heap).replace(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; + } + struct UrgentWaiter; + impl Drop for UrgentWaiter { + fn drop(&mut self) { + URGENT.fetch_sub(1, Relaxed); + } + } + URGENT.fetch_add(1, Relaxed); + let _waiter = UrgentWaiter; + lock(&PASS) +} + +/// Whether the worker is to stop where it is ([`urgent`]). +pub(crate) fn make_way() -> bool { + URGENT.load(Relaxed) > 0 +} + +fn worker() { + crate::cores::keep_on_fast_cores("victory-heap"); + 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); + let _ = crate::draw::State::heap_textures( + crate::draw::TextureTarget::Ahead(&mut batch), + heap, + host, + None, + ); + } + } + 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(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn urgent_stops_worker_and_ready_drains_cleanly() { + assert!(!make_way()); + assert_eq!(URGENT.load(Relaxed), 0); + let held = lock(&PASS); + let (acquired_tx, acquired_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let release_rx = std::sync::Arc::new(Mutex::new(release_rx)); + let spawn_waiter = || { + let acquired_tx = acquired_tx.clone(); + let release_rx = std::sync::Arc::clone(&release_rx); + std::thread::spawn(move || { + let pass = urgent(); + acquired_tx.send((make_way(), URGENT.load(Relaxed))).unwrap(); + release_rx.lock().unwrap().recv().unwrap(); + drop(pass); + }) + }; + let waiter1 = spawn_waiter(); + let waiter2 = spawn_waiter(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while URGENT.load(Relaxed) < 2 { + assert!( + std::time::Instant::now() < deadline, + "both concurrent urgent() calls should increment URGENT while PASS is held" + ); + std::thread::yield_now(); + } + assert!(make_way()); + drop(held); + + let (still_urgent, remaining) = acquired_rx + .recv_timeout(std::time::Duration::from_secs(2)) + .expect("first urgent() should acquire PASS once released"); + assert!(still_urgent); + assert_eq!(remaining, 1); + release_tx.send(()).unwrap(); + + let (after, remaining) = acquired_rx + .recv_timeout(std::time::Duration::from_secs(2)) + .expect("second urgent() should acquire PASS once first releases it"); + assert!(!after); + assert_eq!(remaining, 0); + release_tx.send(()).unwrap(); + + waiter1.join().unwrap(); + waiter2.join().unwrap(); + assert!(!make_way()); + assert_eq!(URGENT.load(Relaxed), 0); + + assert!(take_ready_for_late().is_empty()); + assert!(lock(&READY).is_empty()); + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 66710676f0..0596f9a595 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3601,6 +3601,22 @@ fn split(lists: Vec, order: Vec, cut: usize) -> Result<[Run; 2], Ok([(a, x), (b, y)]) } +/// Prepends `count` worker upload lists (stored at `first..first + count` in +/// `lists`) ahead of `order` and shifts every joined-part split boundary in +/// `parts` by `+count` so submission part cuts preserve title split points. +fn prepend_ahead_order( + order: &mut Vec, + parts: &[usize], + first: usize, + count: usize, +) -> Vec { + if count == 0 { + return parts.to_vec(); + } + order.splice(0..0, first..first + count); + parts.iter().map(|&p| p + count).collect() +} + /// A fence signal on a queue ([`late`]): goes behind the flights in the /// air, if there are any, and is set when they are settled. Whether it /// did; if not the caller sets the fence now. @@ -4218,7 +4234,7 @@ pub(crate) use stamps::{timeline_ready, timeline_restart, timeline_stamps}; #[cfg(test)] mod late_tests { - use super::{continues, join_ranges, touches}; + use super::{continues, join_ranges, prepend_ahead_order, touches}; /// Copies join only when both ends continue and the whole does not /// overlap itself. @@ -4266,6 +4282,36 @@ mod late_tests { } assert!(!touches(&[], 0, usize::MAX)); } + + #[test] + fn prepend_ahead_lists_shifts_join_parts() { + let mut order = vec![0, 1, 2]; + let parts = [1, 2]; + let shifted = prepend_ahead_order(&mut order, &parts, 3, 2); + assert_eq!(order, [3, 4, 0, 1, 2]); + assert_eq!(shifted, [3, 4]); + + let lists = ["ahead0", "ahead1", "title0", "title1", "title2"]; + let firsts = [0, 1, 2, 3, 4]; + let cuts: Vec = shifted + .iter() + .filter_map(|&n| firsts.get(n).copied()) + .collect(); + let mut batches = Vec::new(); + let mut from = 0; + for to in cuts.into_iter().chain([lists.len()]) { + batches.push(&lists[from..to]); + from = to; + } + assert_eq!( + batches, + [ + &["ahead0", "ahead1", "title0"][..], + &["title1"][..], + &["title2"][..], + ] + ); + } } /// Whether a title buffer copy that continues the one recorded before it @@ -5663,6 +5709,14 @@ impl Host { let _ = self.submit(&[list], &[], false); } + /// Runs closed internal upload-only host lists synchronously in one + /// submission without draining title queues (`queue::before_sync`). + pub(crate) fn execute_sync_internal_many(&self, runs: &[&HostList]) { + if !runs.is_empty() { + let _ = self.submit(runs, &[], false); + } + } + /// A queue's submission with [`late`]: the host lists `lists`, taken /// from the title's, go to the card in `order` and are not waited for. /// They join the line of flights and are settled, with the others in @@ -5699,7 +5753,26 @@ impl Host { self.send_late(lists, order, parts); } - fn send_late(&self, lists: Vec, order: Vec, parts: &[usize]) { + fn send_late( + &self, + mut lists: Vec, + mut order: Vec, + parts: &[usize], + ) { + // Textures uploaded ahead (`crate::heap_worker`): their lists run + // before the title's, and joined-part split boundaries shift by their + // count so submission part cuts preserve title split points. + let ahead = crate::heap_worker::take_ready_for_late(); + let shifted_parts: Vec; + let parts = if !ahead.is_empty() { + let first = lists.len(); + let count = ahead.len(); + lists.extend(ahead.into_iter().map(crate::list::Detached::ours)); + shifted_parts = prepend_ahead_order(&mut order, parts, first, count); + &shifted_parts[..] + } else { + parts + }; let sent = { let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect(); self.submit(&runs, parts, true) @@ -8065,6 +8138,24 @@ impl HostList { deferred.prelude_uploads.push(upload); } + /// 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 + } + /// At submission, after the list's steps: the textures whose upload its /// prelude records, each with whether it is the first upload into its /// host copy. Their staging buffers are refreshed first (those the @@ -9861,6 +9952,20 @@ 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/lib.rs b/crates/victory-gpu/src/lib.rs index b60d28f552..fb0e96e182 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -43,6 +43,8 @@ mod book; #[cfg(windows)] mod heap_marks; #[cfg(windows)] +mod heap_worker; +#[cfg(windows)] mod host; /// The F1 settings menu is shown (`host/menu.rs`): the title gets no keyboard meanwhile /// (read by the input module). diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index d2baec2527..58e72a066a 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -269,6 +269,15 @@ 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 } @@ -351,7 +360,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/resource.rs b/crates/victory-gpu/src/resource.rs index 597ede594d..fd5efd9bee 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1492,6 +1492,15 @@ impl Drop for Held { } } +/// 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 diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 301b0455fe..c8aeba109a 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -110,6 +110,9 @@ 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 it was read in ahead of its submission + /// ([`Staging::refresh_ahead`]). + ahead: Option, } /// Frames a guarded texture is hashed at every check from its first check, @@ -1474,26 +1477,27 @@ impl Staging { // the hash, which is taken every eighth frame only, by the // texture's address, so the textures take turns. // `VICTORY_TEXTURE_GUARD=0` hashes at every check, as before. - 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; if !alone - && *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) + && Self::guard_on() && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) { const HASH_EVERY: u64 = 8; let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked); last.asked = now; let frame = crate::frame::current(); + let stale_ahead = last.ahead.is_none_or(|at| frame > at + 1); let turn = frame .wrapping_add((start >> 16) as u64) - .is_multiple_of(HASH_EVERY); + .is_multiple_of(HASH_EVERY) + && stale_ahead; // A texture starts hot: one written that way from its first // frames on changes before the hash has ever caught it. if last.hot_until == 0 { last.hot_until = frame + HOT_FRAMES; } - let hot = hot_textures() && frame < last.hot_until; + let hot = hot_textures() && frame < last.hot_until && stale_ahead; if !exact && unwritten && !turn && !hot { return 0; } @@ -1611,6 +1615,50 @@ impl Staging { size } + fn guard_on() -> bool { + static GUARD: std::sync::OnceLock = std::sync::OnceLock::new(); + *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) + } + + /// 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 + /// (unless `self.once` or `VICTORY_TEXTURE_GUARD=0`, which skip + /// write-watching as `refresh_timed` does). + pub(crate) fn refresh_ahead(&self) -> bool { + let size = self.read; + 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 alone = self.once.load(std::sync::atomic::Ordering::Relaxed); + let now = if alone || !Self::guard_on() { + 0 + } else { + let Some((now, _)) = crate::watch::writes(start, start + size, false) + .or_else(|| crate::watch::writes(start, start + size, true)) + else { + return false; + }; + now + }; + with_read(size, |read| { + if !crate::host::read_into(self.memory, read) { + return false; + } + last.hash = Some(digest(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 a staging buffer that was filled