From b2e03491393fc38a7ff391a95ff6fe285f044d88 Mon Sep 17 00:00:00 2001 From: Saurabh Suresh Date: Thu, 26 Nov 2026 22:25:51 +0400 Subject: [PATCH 1/5] perf(gpu): make a heap sync's changed slots under one hold of the slot lock Before every submission the heap sync makes again the slots whose records the title copied into its shader-visible heaps as bytes: some 40,000 a frame in the prologue's world (about 22,000 left null, the rest views of only ~1,700 distinct records). Each went through HostHeap::mirror, which takes the heap's slot lock (`made`) once a slot, while the title's threads recording draws make their table slots under the same lock. On an M5 Pro that cost 217 ms of a 557 ms frame in a release build, about half of it waiting for the lock. HostHeap::mirror_synced does for each slot exactly what mirror does on the heap-sync path, but with the lock taken once for a page's slots: what each view needs is prepared first without the lock, as mirror does; a slot the title wrote again meanwhile is left to mirror; whether a view is still current is asked under the lock, as mirror asks; views are unpinned after the lock. mirror's null path and its making of a slot move into unmake_locked and make_locked, which both use. Measured in the game (M5 Pro, D3DMetal 4.0 beta 3, same save and key script), interleaved runs of one diagnostics binary with the batching on and off: heap sync 297/231 -> 92/145 ms a frame, preparing 428/368 -> 212/335 ms, frame 750/668 -> 462/639 ms. Test: a_slot_rewritten_while_a_heap_sync_prepares_is_left_as_written_last. Diagnostics builds now also log where a heap sync's time goes, per frame: the pages a heap sync read and of their slots those passed by as made from their record, those holding no view, those checked under the locks (and of them those in blocks not verified since views were last forgotten) and those made again, with the time spent checking, making, reading pages and waiting for the heaps' lock, and the title's releases that forgot views. These counters showed that the slots made again, not the checks or the forgotten views, held the time. watch::TimedNs times spans in nanoseconds, since these add up from many of well under a microsecond. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/copystat.rs | 37 +++- crates/victory-gpu/src/descriptor.rs | 21 ++- crates/victory-gpu/src/descriptor/host.rs | 217 ++++++++++++++++++---- crates/victory-gpu/src/watch.rs | 13 ++ 4 files changed, 250 insertions(+), 38 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 50a5721c..c708727a 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -140,8 +140,26 @@ pub(crate) enum C { TwinToDepthBytes, TwinToTwin, TwinToTwinBytes, + /// The heap sync (`crate::descriptor::sync_heaps`): pages of title heaps + /// read, and of their slots those skipped as made from the record they + /// hold, those holding no view, those checked under the locks (and of + /// them those in blocks not verified since views were last forgotten), + /// and those made again; the time spent reading pages, waiting for the + /// heaps' lock, checking and making; the title's releases that forgot + /// views (each makes every block check its slots again). + SyncPages, + SyncFast, + SyncNoView, + SyncChecked, + SyncUnverified, + SyncMade, + SyncReadNs, + SyncLockNs, + SyncCheckNs, + SyncMakeNs, + ViewsForgot, } -const COUNTERS: usize = C::TwinToTwinBytes as usize + 1; +const COUNTERS: usize = C::ViewsForgot as usize + 1; static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; pub(crate) fn add(c: C, n: u64) { @@ -450,6 +468,23 @@ pub(crate) fn log(frames: f64) { c[C::TwinToTwin as usize], mb(c[C::TwinToTwinBytes as usize]), ); + tracing::info!( + " heap sync per frame: {:.0} pages, {:.0} slots: {:.0} made from their record already, {:.0} no view, \ + {:.0} checked ({:.0} in blocks not verified) in {:.1} ms, {:.0} made again in {:.1} ms; pages read in \ + {:.1} ms, {:.1} ms waiting for the heaps' lock; {:.1} releases forgot views", + c[C::SyncPages as usize], + c[C::SyncSlots as usize], + c[C::SyncFast as usize], + c[C::SyncNoView as usize], + c[C::SyncChecked as usize], + c[C::SyncUnverified as usize], + c[C::SyncCheckNs as usize] / 1e6, + c[C::SyncMade as usize], + c[C::SyncMakeNs as usize] / 1e6, + c[C::SyncReadNs as usize] / 1e6, + c[C::SyncLockNs as usize] / 1e6, + c[C::ViewsForgot as usize], + ); let mut snapshots: Vec<((u64, u64), u64)> = SNAPSHOTS.lock().unwrap_or_else(|e| e.into_inner()).take().into_iter().flatten().collect(); snapshots.sort_by_key(|&(_, bytes)| std::cmp::Reverse(bytes)); diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 8e63b4e9..93270217 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -244,7 +244,14 @@ pub(crate) fn sync_heaps() { for (start, at, ranges) in work { for (from, to) in ranges { for page in (from & !(page_size - 1)..to).step_by(page_size) { + #[cfg(feature = "diagnostics")] + let waited = crate::watch::TimedNs( + std::time::Instant::now(), + crate::copystat::C::SyncLockNs, + ); let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); + #[cfg(feature = "diagnostics")] + drop(waited); if !heaps.iter().any(|&(s, _, h)| (s, h) == (start, at)) { break; } @@ -259,9 +266,19 @@ pub(crate) fn sync_heaps() { let len = end - page; // By page: read the whole mapped range once; one with nothing // mapped (the title unmaps heap pages too) holds no records. - if !crate::host::read_into(page as *const u8, &mut page_buf[..len]) { + #[cfg(feature = "diagnostics")] + let reading = crate::watch::TimedNs( + std::time::Instant::now(), + crate::copystat::C::SyncReadNs, + ); + let mapped = crate::host::read_into(page as *const u8, &mut page_buf[..len]); + #[cfg(feature = "diagnostics")] + drop(reading); + if !mapped { continue; } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SyncPages, 1); let (first, last) = ( (page as u64 - start) / step, (end as u64 - start).div_ceil(step), @@ -675,6 +692,8 @@ pub(crate) fn forget(resource: usize) { } if removed { VIEWS_FORGOT.fetch_add(1, std::sync::atomic::Ordering::Release); + #[cfg(all(windows, feature = "diagnostics"))] + crate::copystat::add(crate::copystat::C::ViewsForgot, 1); } } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index fa2c471e..cb79b1b8 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -851,6 +851,8 @@ impl HostHeap { }; let [tag, view, generation] = record; if tag != VIEW_TAG { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SyncNoView, 1); if self.made_is_nonzero(i) { stale.push(i); } @@ -858,11 +860,23 @@ impl HostHeap { } let key = u64::from(generation) << 32 | u64::from(view); if blocks_verified && self.ready[i as usize].load(Ordering::Acquire) == key { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SyncFast, 1); continue; } candidates.push((i, record)); } + #[cfg(feature = "diagnostics")] + { + crate::copystat::add(crate::copystat::C::SyncChecked, candidates.len() as u64); + if !blocks_verified { + crate::copystat::add(crate::copystat::C::SyncUnverified, candidates.len() as u64); + } + } + #[cfg(feature = "diagnostics")] + let checking = + crate::watch::TimedNs(std::time::Instant::now(), crate::copystat::C::SyncCheckNs); if !candidates.is_empty() { let records: Vec<[u32; 3]> = candidates.iter().map(|&(_, r)| r).collect(); let mut current = Vec::with_capacity(records.len()); @@ -880,9 +894,16 @@ impl HostHeap { } } - for i in stale { - self.mirror(i, at(i), false); - } + #[cfg(feature = "diagnostics")] + drop(checking); + #[cfg(feature = "diagnostics")] + let making = + crate::watch::TimedNs(std::time::Instant::now(), crate::copystat::C::SyncMakeNs); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SyncMade, stale.len() as u64); + self.mirror_synced(&stale, at); + #[cfg(feature = "diagnostics")] + drop(making); for b in b_first..=b_last { let b_start = b * SYNC_BLOCK_SLOTS; @@ -972,13 +993,7 @@ impl HostHeap { let Some(view) = view else { // Not a view of ours (never written, or of a resource the // title released): nothing to read. - if made[index as usize] != 0 { - self.ready[index as usize].store(0, Ordering::Relaxed); - made[index as usize] = 0; - self.set_made_nonzero(index, false); - self.make_null(index); - self.note_address(index, None); - } + self.unmake_locked(&mut made, index); return None; }; // A placed texture's view left null below is made when a draw reads @@ -1015,35 +1030,116 @@ impl HostHeap { return Some(view); } } - { + self.make_locked(&mut made, index, key, &view, later); + Some(view) + } + + /// Under the slot lock (`made`): host slot `index`, made from a record + /// that holds no current view, is left null. + fn unmake_locked(&self, made: &mut [u64], index: u32) { + if made[index as usize] != 0 { self.ready[index as usize].store(0, Ordering::Relaxed); - self.set_stride(index, Some(&view)); - self.note_address(index, Some(&view)); - if later { - // Made once a shader reads it (`crate::shadow::take_reads`). - crate::shadow::forget_read(index); - } - made[index as usize] = key; - self.set_made_nonzero(index, true); - let (kept, mark) = if later { - (None, None) - } else { - make_marked(&view, self.cpu(index)) - }; - self.set_mark(index, mark); - if kept.is_none() && !self.sampler { - null_for(&view, self.cpu(index)); - } - if !self.sampler { - self.viewed.set(index, Some(&view), kept.is_some()); + made[index as usize] = 0; + self.set_made_nonzero(index, false); + self.make_null(index); + self.note_address(index, None); + } + } + + /// Under the slot lock (`made`): makes host slot `index` from `view`, + /// recorded with `key`, what it needs already prepared ([`prepare`]); + /// `later`: a placed texture's view, left null until a shader or draw + /// reads it. + fn make_locked(&self, made: &mut [u64], index: u32, key: u64, view: &View, later: bool) { + self.ready[index as usize].store(0, Ordering::Relaxed); + self.set_stride(index, Some(view)); + self.note_address(index, Some(view)); + if later { + // Made once a shader reads it (`crate::shadow::take_reads`). + crate::shadow::forget_read(index); + } + made[index as usize] = key; + self.set_made_nonzero(index, true); + let (kept, mark) = if later { + (None, None) + } else { + make_marked(view, self.cpu(index)) + }; + self.set_mark(index, mark); + if kept.is_none() && !self.sampler { + null_for(view, self.cpu(index)); + } + if !self.sampler { + self.viewed.set(index, Some(view), kept.is_some()); + } + let kept = kept.flatten(); + // A texture's view left null is made again when a draw reads it. + let ready = if is_texture(view) && kept.is_none() { + 0 + } else { + key + }; + self.keep(index, kept); + self.ready[index as usize].store(ready, Ordering::Release); + } + + /// [`HostHeap::mirror`] of slots `slots`, whose records are at `at(i)`, + /// for a heap sync (not for a draw): the same for each slot, but with + /// the slot lock taken once for them all instead of once a slot. The + /// heap sync makes some 40,000 slots a frame in the world while title + /// threads recording draws make theirs under the same lock, and taking + /// it once a slot cost ~217 ms a frame (M5 Pro, release build), most of + /// it in handing the lock back and forth. What each view needs is + /// prepared first, without the lock, as `mirror` does; a slot the title + /// wrote again meanwhile is left to `mirror`; views are unpinned after + /// the lock, whose holders their release may need. + fn mirror_synced(&self, slots: &[u32], at: impl Fn(u32) -> u64) { + let entries: Vec<(u32, [u32; 3], Option)> = slots + .iter() + .filter(|&&index| index < self.count) + .map(|&index| { + // SAFETY: a descriptor slot in title memory the caller found mapped. + let record = unsafe { (at(index) as *const [u32; 3]).read_unaligned() }; + let [tag, i, generation] = record; + let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten(); + if let Some(view) = &view + && !is_placed_texture(view) + { + prepare(view); + } + (index, record, view) + }) + .collect(); + let mut again = Vec::new(); + { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + // Whether each view is still current, as `mirror` asks under the lock. + let records: Vec<[u32; 3]> = entries.iter().map(|&(_, record, _)| record).collect(); + let mut current = Vec::with_capacity(records.len()); + views_current_into(&records, &mut current); + for ((index, record, view), current) in entries.iter().zip(current) { + let index = *index; + // SAFETY: as above. + if unsafe { (at(index) as *const [u32; 3]).read_unaligned() } != *record { + again.push(index); + continue; + } + match view.as_deref().filter(|_| current) { + None => self.unmake_locked(&mut made, index), + Some(view) => { + let [_, i, generation] = *record; + let key = u64::from(generation) << 32 | u64::from(i); + if made[index as usize] != key { + self.make_locked(&mut made, index, key, view, is_placed_texture(view)); + } + } + } } - let kept = kept.flatten(); - // A texture's view left null is made again when a draw reads it. - let ready = if is_texture(&view) && kept.is_none() { 0 } else { key }; - self.keep(index, kept); - self.ready[index as usize].store(ready, Ordering::Release); } - Some(view) + drop(entries); + for index in again { + self.mirror(index, at(index), false); + } } /// The view host slot `index` was made from, in a few words, with the @@ -2656,6 +2752,55 @@ mod tests { assert!(host.made(0) && !host.made(1), "a cleared record leaves its slot"); } + /// A slot the title writes again while a heap sync prepares the view it + /// held is left as the title wrote it last: the sync makes its slots + /// under one hold of the slot lock and gives a slot rewritten meanwhile + /// to `mirror` instead of making it from the record it read first. + #[test] + fn a_slot_rewritten_while_a_heap_sync_prepares_is_left_as_written_last() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 4, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid( + 0x8efb471d, + 0x616c, + 0x4f49, + [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51], + ); + assert_eq!( + crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), + 0 + ); + let title_heap = crate::descriptor::heap(heap); + let start = title_heap.start; + // A view of no memory, as in `heap_syncs_make_the_slots_whose_records_changed`. + crate::descriptor::create_cbv(null, &[0, 0, 256, 0], start); + let host = title_heap.host().expect("a host view heap"); + // SAFETY: slots 0 and 1 of the heap's memory, 32 bytes each. + unsafe { std::ptr::copy_nonoverlapping(start as *const u8, (start + 32) as *mut u8, 32) }; + // While the sync prepares slot 1's view, the title clears slot 1. + let slot1 = start + 32; + *WHILE_PREPARING.lock().unwrap() = Some(Box::new(move || { + // SAFETY: slot 1 of the heap's memory. + unsafe { std::ptr::write_bytes(slot1 as *mut u8, 0, 32) }; + })); + host.sync_slots(0, 4, start, 32); + assert!(WHILE_PREPARING.lock().unwrap().is_none(), "the prepare ran"); + assert!(host.made(0), "slot 0 stays made"); + assert!( + !host.made(1), + "slot 1 left as the title wrote it last: cleared" + ); + // And copied again as bytes, the next sync makes it. + // SAFETY: as above. + unsafe { std::ptr::copy_nonoverlapping(start as *const u8, (start + 32) as *mut u8, 32) }; + host.sync_slots(0, 4, start, 32); + assert!(host.made(1), "made from the record copied again"); + } + /// The world's 16-byte view of 0 elements removed the device. #[test] fn empty_and_overlong_buffer_views_are_refused() { diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index e0afc0f7..bd5da9e7 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -1231,6 +1231,19 @@ impl Drop for Timed { } } +/// Like [`Timed`], in nanoseconds: for spans of well under a microsecond +/// that add up (a lock or a page read per page of a heap sync). +#[cfg(feature = "diagnostics")] +pub(crate) struct TimedNs(pub(crate) std::time::Instant, pub(crate) crate::copystat::C); + +#[cfg(feature = "diagnostics")] +impl Drop for TimedNs { + fn drop(&mut self) { + let c = std::mem::replace(&mut self.1, crate::copystat::C::Submissions); + crate::copystat::add(c, self.0.elapsed().as_nanos() as u64); + } +} + #[cfg(test)] pub(crate) mod tests { use super::*; From d94a5ef360958797be86d8b24db80851f0b86d95 Mon Sep 17 00:00:00 2001 From: Saurabh Suresh Date: Fri, 27 Nov 2026 01:19:35 +0400 Subject: [PATCH 2/5] fix(gpu): take no lock in a heap sync of a page with nothing to make HostHeap::mirror_synced took the slot lock (`made`) and read `VIEWS` for a page's changed slots even when there were none, so a heap sync of a page whose slots were all empty or already verified waited for title threads writing views, which neither lock held up before the batching. It now returns when there is nothing to make. Test: a_heap_sync_of_empty_slots_does_not_wait_for_the_slot_lock (fails without the fix: the sync waits for the slot lock). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 44 +++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index cb79b1b8..b871d10e 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1110,6 +1110,11 @@ impl HostHeap { (index, record, view) }) .collect(); + // Nothing to make (a page of empty or verified slots): neither the + // slot lock nor `VIEWS`, which title threads writing views wait on. + if entries.is_empty() { + return; + } let mut again = Vec::new(); { let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); @@ -2801,6 +2806,45 @@ mod tests { assert!(host.made(1), "made from the record copied again"); } + /// A heap sync of slots holding nothing made takes no lock: it does not + /// wait for a title thread holding the slot lock (writing a view). + #[test] + fn a_heap_sync_of_empty_slots_does_not_wait_for_the_slot_lock() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 4, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid( + 0x8efb471d, + 0x616c, + 0x4f49, + [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51], + ); + assert_eq!( + crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), + 0 + ); + let title_heap = crate::descriptor::heap(heap); + let start = title_heap.start; + let host = title_heap.host().expect("a host view heap"); + let held = host.made.lock().unwrap(); + let heap = heap as usize; + let (done, synced) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let h = crate::descriptor::heap(heap as crate::object::This); + // No record was ever written: every slot is empty. + h.host().unwrap().sync_slots(0, 4, start, 32); + let _ = done.send(()); + }); + let waited = synced + .recv_timeout(std::time::Duration::from_secs(5)) + .is_err(); + drop(held); + assert!(!waited, "the sync of empty slots waited for the slot lock"); + } + /// The world's 16-byte view of 0 elements removed the device. #[test] fn empty_and_overlong_buffer_views_are_refused() { From 01b05a52895f5fc6fd6ed4f5f32cc813d8e86255 Mon Sep 17 00:00:00 2001 From: Saurabh Suresh Date: Fri, 27 Nov 2026 01:19:50 +0400 Subject: [PATCH 3/5] test(gpu): give each test thread its own prepare hook The work tests run while a view is prepared (`while_preparing`) was one hook for the whole process, and tests run at once: another test's prepare could take it first (the test then passed without the interleaving it was written for) or a second test could replace it (a spurious failure). The hook is now the setting thread's own; every test that uses it prepares on the thread that set it. Test: a_view_prepared_on_another_thread_leaves_the_prepare_hook (fails with the shared hook: the other thread's prepare runs it). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 60 +++++++++++++++++------ 1 file changed, 46 insertions(+), 14 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index b871d10e..0f641788 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2530,16 +2530,39 @@ mod tests { assert!(crate::resource::made_copy(texture).is_some(), "with a host texture again"); } - /// Work to run while a view's texture is prepared, once (tests). - pub(crate) static WHILE_PREPARING: std::sync::Mutex> = std::sync::Mutex::new(None); + std::thread_local! { + /// Work to run while this thread prepares a view's texture, once + /// (tests). Each thread's own: tests run at once, and a hook of the + /// whole process was taken or replaced by another test's prepare. + static WHILE_PREPARING: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; + } pub(crate) fn while_preparing() { - let work = WHILE_PREPARING.lock().unwrap_or_else(|e| e.into_inner()).take(); + let work = WHILE_PREPARING.with_borrow_mut(Option::take); if let Some(work) = work { work(); } } + /// A test's prepare hook is its own thread's: a view prepared on another + /// thread meanwhile (another test's) neither runs it nor takes it. + #[test] + fn a_view_prepared_on_another_thread_leaves_the_prepare_hook() { + let ran = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let set = ran.clone(); + WHILE_PREPARING.set(Some(Box::new(move || set.store(true, Ordering::SeqCst)))); + std::thread::spawn(|| prepare(&View::Sampler([0; 13]))) + .join() + .unwrap(); + assert!( + !ran.load(Ordering::SeqCst), + "another thread's prepare ran it" + ); + prepare(&View::Sampler([0; 13])); + assert!(ran.load(Ordering::SeqCst), "this thread's prepare runs it"); + } + /// A resource's final release during preparation returns at once, and the /// resource stays alive for the make: the view's pin frees it when the /// caller drops the view. @@ -2566,7 +2589,7 @@ mod tests { resource, 0x10, ); - *WHILE_PREPARING.lock().unwrap() = Some(Box::new(move || { + WHILE_PREPARING.set(Some(Box::new(move || { // The title's last reference goes while the view is being made. // The call must not wait for the make: this very thread is the // one making the view, so a wait would never end. @@ -2580,10 +2603,13 @@ mod tests { std::thread::yield_now(); } assert_eq!(released.join().unwrap(), 1, "the pin still holds it"); - })); + }))); let view = heap.mirror(0, at, false).expect("the current view"); - assert!(WHILE_PREPARING.lock().unwrap().is_none(), "the prepare ran"); + assert!( + WHILE_PREPARING.with_borrow(Option::is_none), + "the prepare ran" + ); assert!(heap.made(0), "the view was made from the live resource"); assert!( crate::descriptor::view(at).is_some(), @@ -2622,14 +2648,14 @@ mod tests { let host = title_heap.host().expect("a host view heap"); let (done, waited) = std::sync::mpsc::channel(); let second_view = view_of(second); - *WHILE_PREPARING.lock().unwrap() = Some(Box::new(move || { + WHILE_PREPARING.set(Some(Box::new(move || { // The title writes the other record into the slot meanwhile. std::thread::spawn(move || { crate::descriptor::create_placed_srv(std::ptr::null(), &words, &second_view, at); done.send(()).unwrap(); }); assert!(waited.recv_timeout(std::time::Duration::from_secs(5)).is_ok(), "the write waits"); - })); + }))); // A draw reads the slot: its first record is prepared. assert!(host.mirror(s, at, true).is_some()); let second_texture = crate::resource::texture_at(second, &words).expect("its resource"); @@ -2665,7 +2691,7 @@ mod tests { let heap_at = title_heap.start; let heap = heap as usize; let (done, waited) = std::sync::mpsc::channel(); - *WHILE_PREPARING.lock().unwrap() = Some(Box::new(move || { + WHILE_PREPARING.set(Some(Box::new(move || { std::thread::spawn(move || { let h = crate::descriptor::heap(heap as crate::object::This); h.host().unwrap().mirror(second, heap_at + u64::from(second) * 32, true); @@ -2675,9 +2701,12 @@ mod tests { waited.recv_timeout(std::time::Duration::from_secs(5)).is_ok(), "a view bound while another slot's texture is made waits" ); - })); + }))); assert!(host.mirror(first, slot(first), true).is_some()); - assert!(WHILE_PREPARING.lock().unwrap().is_none(), "the prepare ran"); + assert!( + WHILE_PREPARING.with_borrow(Option::is_none), + "the prepare ran" + ); assert!(host.kept(first) && host.kept(second), "both made"); } @@ -2788,12 +2817,15 @@ mod tests { unsafe { std::ptr::copy_nonoverlapping(start as *const u8, (start + 32) as *mut u8, 32) }; // While the sync prepares slot 1's view, the title clears slot 1. let slot1 = start + 32; - *WHILE_PREPARING.lock().unwrap() = Some(Box::new(move || { + WHILE_PREPARING.set(Some(Box::new(move || { // SAFETY: slot 1 of the heap's memory. unsafe { std::ptr::write_bytes(slot1 as *mut u8, 0, 32) }; - })); + }))); host.sync_slots(0, 4, start, 32); - assert!(WHILE_PREPARING.lock().unwrap().is_none(), "the prepare ran"); + assert!( + WHILE_PREPARING.with_borrow(Option::is_none), + "the prepare ran" + ); assert!(host.made(0), "slot 0 stays made"); assert!( !host.made(1), From 0229bbc1f1ca6ff9756efedf2e098e9f54468229 Mon Sep 17 00:00:00 2001 From: Saurabh Suresh Date: Fri, 27 Nov 2026 02:52:19 +0400 Subject: [PATCH 4/5] test(gpu): benchmark a heap sync of a synthetic heap, alone and contended heap_sync_bench (ignored; run alone, in release, under Wine) syncs a heap of 2,048 slots in pages of 128, an eighth of its slots given another view between sweeps, and gives the median sweep: by one thread alone, and with another thread taking the slot lock all the while, as title threads binding views do. It is a tester's pattern on #409, where the batched sync took 106 us a sweep against main's 65 us alone (M2 Max). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 3 + .../victory-gpu/src/descriptor/host/bench.rs | 94 +++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 crates/victory-gpu/src/descriptor/host/bench.rs diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 0f641788..991d85cd 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2288,6 +2288,9 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { }; } +#[cfg(test)] +mod bench; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/victory-gpu/src/descriptor/host/bench.rs b/crates/victory-gpu/src/descriptor/host/bench.rs new file mode 100644 index 00000000..c02328ac --- /dev/null +++ b/crates/victory-gpu/src/descriptor/host/bench.rs @@ -0,0 +1,94 @@ +//! Heap-sync benchmark: a synthetic heap of 2,048 slots synced in pages of +//! 128, an eighth of its slots changed between sweeps (a tester's pattern on +//! #409), by one thread alone and with another taking the slot lock all the +//! while, as title threads binding views do. Run alone, in release, under +//! Wine: +//! `tools/macos/test-wine.sh -p victory-gpu --release --lib -- --ignored --nocapture heap_sync_bench` + +use super::*; +use std::sync::atomic::AtomicBool; +use std::time::Instant; + +const SLOTS: u32 = 2048; +const PAGE: u32 = 128; +const SWEEPS: usize = 2000; + +/// The median time of a sweep over every page, in microseconds, the slot +/// lock taken meanwhile by another thread if `contended`. +fn sweep_us(heap: &HostHeap, contended: bool) -> f64 { + let null = std::ptr::null(); + // Two views of no memory (made null, as cheaply as a view is made). + let mut views = [[0u8; 32]; 2]; + crate::descriptor::create_cbv(null, &[0, 0, 256, 0], views[0].as_mut_ptr() as u64); + crate::descriptor::create_cbv(null, &[0, 0, 512, 0], views[1].as_mut_ptr() as u64); + let mut memory = vec![0u8; SLOTS as usize * 32]; + for slot in memory.as_chunks_mut::<32>().0 { + *slot = views[0]; + } + let start = memory.as_ptr() as u64; + let sweep = |memory: &[u8]| { + for first in (0..SLOTS).step_by(PAGE as usize) { + let bytes = &memory[first as usize * 32..(first + PAGE) as usize * 32]; + heap.sync_slots_bytes( + first, + first + PAGE, + start, + 32, + start + u64::from(first) * 32, + bytes, + ); + } + }; + sweep(&memory); + let stop = AtomicBool::new(false); + std::thread::scope(|s| { + if contended { + s.spawn(|| { + while !stop.load(Ordering::Relaxed) { + let made = heap.made.lock().unwrap(); + std::hint::black_box(made[0]); + } + }); + } + let mut times = Vec::with_capacity(SWEEPS); + for pass in 0..SWEEPS + 100 { + // An eighth of the slots get the other view. + for (i, slot) in memory.as_chunks_mut::<32>().0.iter_mut().enumerate() { + if i % 8 == pass % 8 { + *slot = views[usize::from(*slot == views[0])]; + } + } + let begun = Instant::now(); + sweep(&memory); + if pass >= 100 { + times.push(begun.elapsed().as_nanos()); + } + } + stop.store(true, Ordering::Relaxed); + // Every slot made from the record it holds last. + let made = heap.made.lock().unwrap(); + for (i, slot) in memory.as_chunks::<32>().0.iter().enumerate() { + let word = |k: usize| u32::from_le_bytes(slot[4 * k..4 * k + 4].try_into().unwrap()); + assert_eq!( + made[i], + u64::from(word(2)) << 32 | u64::from(word(1)), + "slot {i}" + ); + } + drop(made); + times.sort_unstable(); + times[times.len() / 2] as f64 / 1e3 + }) +} + +#[test] +#[ignore = "a benchmark: run alone, in release"] +fn heap_sync_bench() { + if host().is_none() { + return; + } + let heap = HostHeap::new(false, SLOTS).expect("a host heap"); + let alone = sweep_us(&heap, false); + let contended = sweep_us(&heap, true); + println!("heap sync sweep: {alone:.1} us alone, {contended:.1} us with a contending reader"); +} From 4f2fbff7eb67bb9c17f669557d2f79815f4aaee4 Mon Sep 17 00:00:00 2001 From: Saurabh Suresh Date: Fri, 27 Nov 2026 02:57:40 +0400 Subject: [PATCH 5/5] perf(gpu): reuse a heap sync's vectors and ask VIEWS once a page The batched heap sync was slower than main's lock a slot on one thread alone: on heap_sync_bench (2,048 slots, pages of 128, an eighth changed a sweep) 103 us a sweep against main's 72 us (a tester had 106 against 65 on an M2 Max). Each page made fresh vectors for its slots, records, answers and pinned views, and asked VIEWS a second time, under the slot lock, whether the views it had pinned were current. The vectors are now the syncing thread's own, cleared and kept for its next page (a nested sync would take empty ones). The second question is gone: a pinned view is current, as `mirror` finds it after it prepares one without the lock, since only a resource's release makes views stale (`descriptor::forget`, from `Resource::drop`), the pin holds the resource, and views of no resource never go stale. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 120 ++++++++++++++++------ 1 file changed, 87 insertions(+), 33 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 991d85cd..3e5c52da 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -18,6 +18,48 @@ use crate::host::host; const SYNC_BLOCK_SLOTS: u32 = 128; +/// What a heap sync of a page works in ([`HostHeap::sync_slots_bytes`]), +/// kept by each thread for its next page: the slots to make again, those +/// to check under the locks, their records and whether each is current, +/// the views pinned for the make, and the slots left to `mirror`. +#[derive(Default)] +struct Scratch { + stale: Vec, + candidates: Vec<(u32, [u32; 3])>, + records: Vec<[u32; 3]>, + current: Vec, + entries: Vec<(u32, [u32; 3], Option)>, + again: Vec, +} + +impl Scratch { + const fn new() -> Self { + Self { + stale: Vec::new(), + candidates: Vec::new(), + records: Vec::new(), + current: Vec::new(), + entries: Vec::new(), + again: Vec::new(), + } + } + + fn clear(&mut self) { + self.stale.clear(); + self.candidates.clear(); + self.records.clear(); + self.current.clear(); + self.entries.clear(); + self.again.clear(); + } +} + +thread_local! { + /// The thread's [`Scratch`], taken for a page (a nested sync, were there + /// one, takes an empty one). + static SYNC_SCRATCH: std::cell::Cell = const { std::cell::Cell::new(Scratch::new()) }; +} + pub(crate) struct HostHeap { pub(crate) heap: ID3D12DescriptorHeap, cpu: usize, @@ -836,8 +878,14 @@ impl HostHeap { .all(|b| self.block_forgot[b as usize].load(Ordering::Acquire) == forgot); let buf_end = buf_start.saturating_add(buf.len() as u64); - let mut stale: Vec = Vec::new(); - let mut candidates: Vec<(u32, [u32; 3])> = Vec::new(); + let mut scratch = SYNC_SCRATCH.take(); + let Scratch { + stale, + candidates, + records, + current, + .. + } = &mut scratch; for i in first..last { let addr = at(i); @@ -878,11 +926,10 @@ impl HostHeap { let checking = crate::watch::TimedNs(std::time::Instant::now(), crate::copystat::C::SyncCheckNs); if !candidates.is_empty() { - let records: Vec<[u32; 3]> = candidates.iter().map(|&(_, r)| r).collect(); - let mut current = Vec::with_capacity(records.len()); - views_current_into(&records, &mut current); + records.extend(candidates.iter().map(|&(_, r)| r)); + views_current_into(records, current); let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); - for (&(i, [_, view, generation]), is_current) in candidates.iter().zip(current) { + for (&(i, [_, view, generation]), &is_current) in candidates.iter().zip(&*current) { let changed = match made.get(i as usize) { Some(&m) if is_current => m != (u64::from(generation) << 32 | u64::from(view)), Some(&m) => m != 0, @@ -901,7 +948,9 @@ impl HostHeap { crate::watch::TimedNs(std::time::Instant::now(), crate::copystat::C::SyncMakeNs); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::SyncMade, stale.len() as u64); - self.mirror_synced(&stale, at); + self.mirror_synced(&mut scratch, at); + scratch.clear(); + SYNC_SCRATCH.set(scratch); #[cfg(feature = "diagnostics")] drop(making); @@ -1093,43 +1142,47 @@ impl HostHeap { /// prepared first, without the lock, as `mirror` does; a slot the title /// wrote again meanwhile is left to `mirror`; views are unpinned after /// the lock, whose holders their release may need. - fn mirror_synced(&self, slots: &[u32], at: impl Fn(u32) -> u64) { - let entries: Vec<(u32, [u32; 3], Option)> = slots - .iter() - .filter(|&&index| index < self.count) - .map(|&index| { - // SAFETY: a descriptor slot in title memory the caller found mapped. - let record = unsafe { (at(index) as *const [u32; 3]).read_unaligned() }; - let [tag, i, generation] = record; - let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten(); - if let Some(view) = &view - && !is_placed_texture(view) - { - prepare(view); - } - (index, record, view) - }) - .collect(); + /// + /// The slots are `scratch.stale`; the scratch's other vectors are the + /// thread's own, reused from page to page: fresh ones a page made one + /// thread's sync slower than main's lock a slot (`bench::heap_sync_bench`). + fn mirror_synced(&self, scratch: &mut Scratch, at: impl Fn(u32) -> u64) { + let Scratch { + stale, + entries, + again, + .. + } = scratch; + for &index in stale.iter().filter(|&&index| index < self.count) { + // SAFETY: a descriptor slot in title memory the caller found mapped. + let record = unsafe { (at(index) as *const [u32; 3]).read_unaligned() }; + let [tag, i, generation] = record; + let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten(); + if let Some(view) = &view + && !is_placed_texture(view) + { + prepare(view); + } + entries.push((index, record, view)); + } // Nothing to make (a page of empty or verified slots): neither the // slot lock nor `VIEWS`, which title threads writing views wait on. if entries.is_empty() { return; } - let mut again = Vec::new(); { let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); - // Whether each view is still current, as `mirror` asks under the lock. - let records: Vec<[u32; 3]> = entries.iter().map(|&(_, record, _)| record).collect(); - let mut current = Vec::with_capacity(records.len()); - views_current_into(&records, &mut current); - for ((index, record, view), current) in entries.iter().zip(current) { + // A pinned view is current, as `mirror` finds it: only a + // resource's release makes its views stale, and the pin holds + // the resource (views of no resource never go stale). + for (index, record, view) in entries.iter() { let index = *index; // SAFETY: as above. if unsafe { (at(index) as *const [u32; 3]).read_unaligned() } != *record { again.push(index); continue; } - match view.as_deref().filter(|_| current) { + match view.as_deref() { None => self.unmake_locked(&mut made, index), Some(view) => { let [_, i, generation] = *record; @@ -1141,8 +1194,9 @@ impl HostHeap { } } } - drop(entries); - for index in again { + // Unpinned after the lock, whose holders their release may need. + entries.clear(); + for &index in again.iter() { self.mirror(index, at(index), false); } }