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 56913872..c6278424 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -246,7 +246,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; } @@ -261,9 +268,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), @@ -679,6 +696,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 a66359c0..04375427 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -19,6 +19,47 @@ 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()) }; +} /// Monotonic identity for each [`HostHeap`] so stale dynamic-slot releases /// targeting a released heap's recycled address never free a newer heap's slots. static NEXT_ID: AtomicU64 = AtomicU64::new(1); @@ -900,8 +941,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); @@ -915,6 +962,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); } @@ -922,17 +971,28 @@ 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()); - 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, @@ -944,9 +1004,18 @@ 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(&mut scratch, at); + scratch.clear(); + SYNC_SCRATCH.set(scratch); + #[cfg(feature = "diagnostics")] + drop(making); for b in b_first..=b_last { let b_start = b * SYNC_BLOCK_SLOTS; @@ -1036,13 +1105,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 @@ -1079,35 +1142,126 @@ 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)); + 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. + /// + /// 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); } - if !self.sampler { - self.viewed.set(index, Some(&view), kept.is_some()); + 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 made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + // 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() { + 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) + // Unpinned after the lock, whose holders their release may need. + entries.clear(); + for &index in again.iter() { + self.mirror(index, at(index), false); + } } /// The view host slot `index` was made from, in a few words, with the @@ -2328,6 +2482,9 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { }; } +#[cfg(test)] +mod bench; + #[cfg(test)] mod tests { use super::*; @@ -2570,16 +2727,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. @@ -2606,7 +2786,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. @@ -2620,10 +2800,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(), @@ -2662,14 +2845,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"); @@ -2705,7 +2888,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); @@ -2715,9 +2898,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"); } @@ -2797,6 +2983,97 @@ 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.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.with_borrow(Option::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"); + } + + /// 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() { 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"); +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 09dfc86e..45b793cd 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -1299,6 +1299,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::*;