diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 853341fcb8..02b17442ad 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -70,8 +70,12 @@ pub(crate) enum C { CopyBackUs, SrvMaterializations, SrvMaterializationUs, + /// Questions for written pages shared by several host copies' ranges in + /// one private reservation, and the ranges they answered. + SharedSpans, + SharedRanges, } -const COUNTERS: usize = C::SrvMaterializationUs as usize + 1; +const COUNTERS: usize = C::SharedRanges as usize + 1; static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; pub(crate) fn add(c: C, n: u64) { @@ -230,6 +234,8 @@ pub(crate) fn log(frames: f64) { copyback_ms = ms(value(C::CopyBackUs)), srv_materializations = value(C::SrvMaterializations), srv_materialization_ms = ms(value(C::SrvMaterializationUs)), + shared_spans = value(C::SharedSpans), + shared_ranges = value(C::SharedRanges), "shadow traffic per frame" ); let RefreshStats { ranges, failed } = REFRESH diff --git a/crates/victory-gpu/src/descriptor/tests/coherency.rs b/crates/victory-gpu/src/descriptor/tests/coherency.rs index 2290d672ab..b654d5b67b 100644 --- a/crates/victory-gpu/src/descriptor/tests/coherency.rs +++ b/crates/victory-gpu/src/descriptor/tests/coherency.rs @@ -1350,3 +1350,66 @@ fn directly_indexed_srv_report_scale_benchmark() { BUFFERS as u64 * 2 * PAGE * DISTINCT_PER_BUFFER as u64, ); } + +/// Views into separate title buffers side by side in one write-watched +/// reservation (each its own host copy, as the world's small buffers are) +/// share one question for written pages per submission, and each reads the +/// title's latest value. +#[cfg(feature = "diagnostics")] +#[test] +fn directly_indexed_srvs_of_neighbouring_copies_share_a_question() { + let Some((host, dxc)) = test_host() else { + return; + }; + use crate::copystat::{C, read as counter}; + const BUFFERS: u32 = 8; + const SIZE: u64 = 65536; + let pipeline = pipeline(host, &dxc); + let title = TitleBuffer::watched(u64::from(BUFFERS) * SIZE); + // The reservation is registered as one buffer; register the others + // inside it, each its own resource and host copy. + let bases: Vec = (1..BUFFERS) + .map(|i| title.base + u64::from(i) * SIZE) + .collect(); + for &base in &bases { + crate::shadow::register(base as usize, base, SIZE); + } + let heap = TestHeap::new(64); + let view = |handle: u64, address: u64| { + let mut resource = [0; 14]; + resource[0] = 1; + resource[4] = SIZE as u32; + let mut desc = [0; 16]; + desc[0] = DXGI_FORMAT_R32_TYPELESS.0 as u32; + desc[1] = D3D12_SRV_DIMENSION_BUFFER.0 as u32; + desc[2] = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc[6] = 4; + desc[8] = D3D12_BUFFER_SRV_FLAG_RAW.0 as u32; + desc[10] = address as u32; + desc[11] = (address >> 32) as u32; + create_placed_srv(std::ptr::null(), &resource, &desc, handle); + }; + view(heap.handle(0), title.base); + for (i, &base) in bases.iter().enumerate() { + view(heap.handle(i as u32 + 1), base); + } + let (output, mapped) = host.shared_buffer(4).unwrap(); + for round in 0..2u32 { + for i in [0, BUFFERS - 1] { + title.set(u64::from(i) * SIZE, 1000 * round + 100 + i); + let list = host.new_list().unwrap(); + record(&list, heap.0, &pipeline, i, &output); + list.close(); + let watches = counter(C::Watches); + host.execute(&[&list]); + assert!( + counter(C::Watches) - watches <= 1, + "one question for all copies" + ); + assert_eq!(read(mapped), 1000 * round + 100 + i); + } + } + for &base in &bases { + crate::shadow::unregister(base as usize, base); + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 5ac5bf0bbb..ea313382a1 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1375,6 +1375,89 @@ pub(crate) fn test_submission_copy_bytes() -> u64 { /// Refresh live mirrored SRVs after deferred title writes and before /// GPU work. Retain the resources until the submission has finished. +/// Brings host copies' ready ranges up to date. Ranges of several copies +/// that lie close together in one private reservation (the world has many +/// small title buffers placed side by side) share one question for written +/// pages; the rest goes through each copy's own grouping +/// (`Shadow::update_ready`). +fn refresh_across(per: &[(std::sync::Arc, Vec<(usize, usize)>)]) -> usize { + use crate::watch::PAGE; + const SPAN_GAP: usize = 1 << 20; + #[cfg(feature = "diagnostics")] + { + static OFF: std::sync::OnceLock = std::sync::OnceLock::new(); + let off = *OFF.get_or_init(|| std::env::var_os("VICTORY_NO_SHARED_SPANS").is_some()); + if off { + return per.iter().map(|(s, r)| s.update_ready(r)).sum(); + } + } + let mut flat: Vec<(usize, usize, usize)> = per + .iter() + .enumerate() + .flat_map(|(i, (_, r))| r.iter().map(move |&(a, e)| (a, e, i))) + .collect(); + flat.sort_unstable(); + let mut rest: Vec> = vec![Vec::new(); per.len()]; + let mut copied = 0; + let mut at = 0; + // The last reservation looked up: ranges in it need no new question + // (each is a system call, under Wine a round trip). + let mut last: Option = None; + while at < flat.len() { + let (lo, mut hi, first) = flat[at]; + let page = lo / PAGE * PAGE; + if !last.is_some_and(|a| a.is_live() && a.start <= page && page < a.end) { + last = crate::watch::allocation(page); + } + let reservation = last.filter(|a| a.is_private_span(lo, hi)); + let (mut next, mut shared) = (at + 1, false); + if let Some(a) = reservation { + while next < flat.len() + && flat[next].0 <= hi + SPAN_GAP + && a.is_private_span(lo, flat[next].1.max(hi)) + { + hi = hi.max(flat[next].1); + shared |= flat[next].2 != first; + next += 1; + } + } + let group = &flat[at..next]; + let answer = (shared && group.iter().all(|&(_, _, i)| !per[i].0.not_watched())) + .then(|| { + let after = group + .iter() + .map(|&(a, e, i)| per[i].0.floor(a, e)) + .min() + .unwrap_or(u64::MAX); + crate::watch::grouped_writes(lo, hi, after, reservation) + }) + .flatten(); + if let Some((now, written)) = answer { + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::SharedSpans, 1); + add(C::SharedRanges, group.len() as u64); + } + for &(a, e, i) in group { + let k = written.partition_point(|&(page, _)| page < a / PAGE); + copied += per[i].0.answered(a, e, now, &written[k..]); + } + } else { + for &(a, e, i) in group { + rest[i].push((a, e)); + } + } + at = next; + } + for (i, ranges) in rest.iter().enumerate() { + if !ranges.is_empty() { + copied += per[i].0.update_ready(ranges); + } + } + copied +} + fn refresh_direct_srvs( heaps: &[ViewHeapUse], sampled: Option<&SampledRanges>, @@ -1404,13 +1487,15 @@ fn refresh_direct_srvs( let snapshots = with_srv_ranges(&selection, |snapshots| { let mut current: Option<&Arc> = None; let mut uncovered = Vec::new(); + // Each copy's ready ranges, refreshed together below. + let mut per: Vec<(Arc, Vec<(usize, usize)>)> = Vec::new(); #[cfg(feature = "diagnostics")] let (mut requested, mut visits, mut remaining) = (0usize, 0u64, 0usize); visit_direct_ranges(snapshots, |shadow, from, to| { if let Some(previous) = current && !Arc::ptr_eq(previous, shadow) { - copied += previous.update_ranges(&uncovered); + per.push((previous.clone(), previous.ready(&uncovered))); uncovered.clear(); } current = Some(shadow); @@ -1428,8 +1513,9 @@ fn refresh_direct_srvs( } }); if let Some(shadow) = current { - copied += shadow.update_ranges(&uncovered); + per.push((shadow.clone(), shadow.ready(&uncovered))); } + copied += refresh_across(&per); #[cfg(feature = "diagnostics")] { add(C::DirectRanges, visits); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 7ce9ffae73..593888ca2d 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -427,8 +427,16 @@ impl Shadow { /// Subtract pending GPU writes before planning observations so all of /// the readable pieces can share a fresh sample. pub(crate) fn update_ranges(&self, ranges: &[(usize, usize)]) -> usize { + let ready = self.ready(ranges); + self.update_ready(&ready) + } + + /// The parts of sorted, disjoint title ranges that can be refreshed now: + /// cut to this copy, without the ranges shaders of the submission may + /// be writing. + pub(crate) fn ready(&self, ranges: &[(usize, usize)]) -> Vec<(usize, usize)> { let Some((&(first, _), &(_, last))) = ranges.first().zip(ranges.last()) else { - return 0; + return Vec::new(); }; let (start, end) = (self.start as usize, (self.start + self.len) as usize); let mut pending = self @@ -437,7 +445,7 @@ impl Shadow { .unwrap_or_else(|e| e.into_inner()) .clone(); if pending.is_empty() && start <= first && first < last && last <= end { - return self.update_ready(ranges); + return ranges.to_vec(); } pending.sort_unstable(); @@ -464,10 +472,28 @@ impl Shadow { ready.push((from, to)); } } - self.update_ready(&ready) + ready + } + + /// Whether this copy's memory was found not write-watched. + pub(crate) fn not_watched(&self) -> bool { + self.watched.load(Ordering::Relaxed) == NOT_WATCHED + } + + /// The oldest copy of `[from, to)` (see `watch_floor`), for a question + /// shared with other copies. + pub(crate) fn floor(&self, from: usize, to: usize) -> u64 { + self.watch_floor(from, to) + } + + /// Brings `[from, to)` (ready, see [`Shadow::ready`]) up to date from an + /// answer for written pages asked over a span shared with other copies. + pub(crate) fn answered(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize { + self.watched.store(WATCHED, Ordering::Relaxed); + self.update_watched(from, to, now, written) } - fn update_ready(&self, mut ranges: &[(usize, usize)]) -> usize { + pub(crate) fn update_ready(&self, mut ranges: &[(usize, usize)]) -> usize { let mut copied = 0; let mut allocation: Option = None; let mut failed_private_watch: Option = None; diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 84d32e221c..9809282592 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -172,7 +172,18 @@ pub(crate) fn allocation(address: usize) -> Option { let start = info.AllocationBase as usize; let end = start.checked_add(info.RegionSize)?; // The Private bit is the first field of the Win32 region union. - let private = info.Anonymous.Anonymous._bitfield & 1 != 0; + // Wine leaves the union's flags zero for every region; there the + // allocation type comes from VirtualQuery instead. + let mut private = info.Anonymous.Anonymous._bitfield & 1 != 0; + if info.Anonymous.Anonymous._bitfield == 0 { + use windows_sys::Win32::System::Memory::{ + MEM_PRIVATE, MEMORY_BASIC_INFORMATION, VirtualQuery, + }; + let mut basic = MEMORY_BASIC_INFORMATION::default(); + // SAFETY: a query about an address; nothing is dereferenced. + let n = VirtualQuery(address as *const _, &mut basic, size_of_val(&basic)); + private = n != 0 && basic.Type == MEM_PRIVATE; + } (start <= address && address < end).then_some(Allocation { start, end, @@ -640,6 +651,55 @@ pub(crate) mod tests { }; const MEM_WRITE_WATCH: u32 = 0x20_0000; + /// A private reservation is reported private, a mapped view is not + /// (Wine fills no region flags, so this checks the fallback there). + #[test] + fn allocation_tells_private_memory_from_views() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, + UnmapViewOfFile, + }; + // SAFETY: a fresh write-watched reservation of ours. + let p = unsafe { + VirtualAlloc( + std::ptr::null(), + 2 * PAGE, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + } as usize; + assert_ne!(p, 0); + let Some(a) = allocation(p) else { + // QueryVirtualMemoryInformation is missing: nothing to check. + return; + }; + assert!(a.private, "a VirtualAlloc reservation is private"); + assert!(a.is_private_span(p, p + 2 * PAGE)); + // SAFETY: a pagefile section of one block, mapped read-write. + let view = unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + PAGE as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, PAGE) + }; + assert!(!view.Value.is_null()); + assert!( + !allocation(view.Value as usize).unwrap().private, + "a mapped view is not" + ); + // SAFETY: ours. + unsafe { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: view.Value }); + VirtualFree(p as *mut _, 0, MEM_RELEASE); + } + } + #[test] fn journal_index_preserves_order_bounds_and_older_observers() { let mut journal = Journal {