From 27890f9d1cc4be787ef3a85ab3e537f0cbb45836 Mon Sep 17 00:00:00 2001 From: Czer0xx Date: Sat, 28 Nov 2026 07:12:39 +0100 Subject: [PATCH 1/2] GPU: narrow placed-copy, buffer, enhanced-group and pipeline-sync barriers (VICTORY_NARROW_BARRIERS) --- crates/victory-gpu/src/host.rs | 3 +- crates/victory-gpu/src/host/menu.rs | 1 + crates/victory-gpu/src/host/place.rs | 256 +++++++++++-- crates/victory-gpu/src/list.rs | 546 ++++++++++++++++++++++++++- crates/victory-gpu/src/list/thin.rs | 27 +- 5 files changed, 797 insertions(+), 36 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 2db060a9d9..a1456bba22 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4395,6 +4395,7 @@ fn late_line(frames: f64) { constants, ); } + place::log_narrow(frames); card_steps::log(frames); crate::port::log(frames); crate::picked::log(frames); @@ -4418,7 +4419,7 @@ pub(crate) mod indirects; mod font; mod menu; mod panel; -mod place; +pub(crate) mod place; mod send; pub(crate) use send::{goes_as_words, words_under}; #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/host/menu.rs b/crates/victory-gpu/src/host/menu.rs index 55bd6e3e01..cbbddbaa1c 100644 --- a/crates/victory-gpu/src/host/menu.rs +++ b/crates/victory-gpu/src/host/menu.rs @@ -186,6 +186,7 @@ const ITEMS: &[Item] = &[ Item { var: "VICTORY_RELAY", label: "RELAY (SPEED, TRIANGLES)", values: STAGES, live: false }, Item { var: "VICTORY_CARD_STEPS", label: "CARD STEPS", values: STAGES, live: false }, Item { var: "VICTORY_PLACED_FILLS", label: "CONSTANTS AFTER PLACED COPIES", values: UNSET_ON, live: false }, + Item { var: "VICTORY_NARROW_BARRIERS", label: "NARROW GPU BARRIERS", values: UNSET_ON, live: false }, Item { var: "VICTORY_INDIRECT_BATCH", label: "INDIRECT BATCH", values: STAGES, live: false }, Item { var: "VICTORY_CARD_BUFFERS_MIN_KB", label: "CARD COMPARES FROM (KB)", values: &[("64", "64"), ("1024", "1024")], live: false }, Item { var: "VICTORY_PORT_CONSTANTS", label: "CONSTANTS HEAP IN PLACE", values: UNSET_ON, live: false }, diff --git a/crates/victory-gpu/src/host/place.rs b/crates/victory-gpu/src/host/place.rs index 871e8c8210..0174c25654 100644 --- a/crates/victory-gpu/src/host/place.rs +++ b/crates/victory-gpu/src/host/place.rs @@ -60,6 +60,111 @@ fn placed_constants() -> bool { *ON.get_or_init(|| on() && std::env::var_os("VICTORY_PLACED_CONSTANTS").is_none_or(|v| v != "0")) } +/// Whether GPU barriers in `place.rs` and `list.rs` are narrowed to the +/// touched buffers, textures and shader sync stages instead of emitting +/// unconditional global `SYNC_ALL` / `UAV_BARRIER(NULL)` drains +/// (`VICTORY_NARROW_BARRIERS=1`; off by default). +/// +/// Off by default, every placed copy records two global `SYNC_ALL` barriers +/// (~52 per frame), and `barrier_groups`, legacy buffer barriers and pipeline +/// syncs record global `UAV_BARRIER(NULL)` drains even for non-UAV texture +/// layout transitions or read-only buffer transitions. +pub(crate) fn narrow_barriers() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_NARROW_BARRIERS")) +} + +/// Since the last frame-rate line (when `VICTORY_NARROW_BARRIERS=1`): +/// `[0]` place buffer barriers narrowed, +/// `[1..4]` enhanced barrier groups (skipped, narrowed, global fallback), +/// `[4..7]` legacy buffer barriers (skipped, narrowed, global fallback), +/// `[7..9]` pipeline syncs (skipped, global). +pub(crate) static NARROW_STATS: [std::sync::atomic::AtomicU64; 9] = [const { std::sync::atomic::AtomicU64::new(0) }; 9]; + +pub(super) fn log_narrow(frames: f64) { + if !narrow_barriers() { + return; + } + let s: Vec = NARROW_STATS.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "narrow barriers per frame (VICTORY_NARROW_BARRIERS=1): place {:.1} narrowed; groups {:.1} skipped, {:.1} narrowed, {:.1} global; \ + legacy_buf {:.1} skipped, {:.1} narrowed, {:.1} global; sync {:.1} skipped, {:.1} global", + s[0], + s[1], + s[2], + s[3], + s[4], + s[5], + s[6], + s[7], + s[8], + ); +} + +/// Whether the host D3D12 device supports Enhanced Barriers (`Options12`). +pub(crate) fn enhanced_barriers(host: &Host) -> bool { + static ENHANCED: OnceLock = OnceLock::new(); + *ENHANCED.get_or_init(|| { + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); + // SAFETY: a feature structure of its size. + let known = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS12, + (&raw mut o).cast(), + size_of::() as u32, + ) + }; + known.is_ok() && o.EnhancedBarriersSupported.as_bool() + }) +} + +/// Emits enhanced buffer barriers scoped only to `barriers`. +/// +/// # Safety +/// `list` is open; every resource inside `barriers` is live for the list's run. +unsafe fn buffer_barriers(list: &ID3D12GraphicsCommandList, barriers: &[D3D12_BUFFER_BARRIER]) -> bool { + let Ok(list7) = list.cast::() else { + return false; + }; + let group = [D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_BUFFER, + NumBarriers: barriers.len() as u32, + Anonymous: D3D12_BARRIER_GROUP_0 { + pBufferBarriers: barriers.as_ptr(), + }, + }]; + // SAFETY: caller guarantees open list and live buffer resources. + unsafe { list7.Barrier(&group) }; + NARROW_STATS[0].fetch_add(barriers.len() as u64, Ordering::Relaxed); + true +} + +fn buf_barrier( + resource: &ID3D12Resource, + sync_before: D3D12_BARRIER_SYNC, + sync_after: D3D12_BARRIER_SYNC, + access_before: D3D12_BARRIER_ACCESS, + access_after: D3D12_BARRIER_ACCESS, +) -> D3D12_BUFFER_BARRIER { + D3D12_BUFFER_BARRIER { + SyncBefore: sync_before, + SyncAfter: sync_after, + AccessBefore: access_before, + AccessAfter: access_after, + pResource: std::mem::ManuallyDrop::new(Some(resource.clone())), + Offset: 0, + Size: u64::MAX, + } +} + +/// Releases the cloned COM pointers held inside `ManuallyDrop` entries of `barriers`. +fn drop_buf_barriers(barriers: &mut [D3D12_BUFFER_BARRIER]) { + for b in barriers { + // SAFETY: each entry was created with `ManuallyDrop::new(Some(resource.clone()))` once. + unsafe { std::mem::ManuallyDrop::drop(&mut b.pResource) }; + } +} + /// What the CPU does at submission for a copy at its place in a list. pub(super) struct Placed { pub(super) dst: usize, @@ -142,19 +247,7 @@ pub(super) fn read_by(runs: &[&HostList], mut ranges: Vec<(usize, usize)>) -> bo /// # Safety /// An open list. unsafe fn wait_for_all(host: &Host, list: &ID3D12GraphicsCommandList) { - static ENHANCED: OnceLock = OnceLock::new(); - let enhanced = *ENHANCED.get_or_init(|| { - let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); - // SAFETY: a feature structure of its size. - let known = unsafe { - host.device.CheckFeatureSupport( - D3D12_FEATURE_D3D12_OPTIONS12, - (&raw mut o).cast(), - size_of::() as u32, - ) - }; - known.is_ok() && o.EnhancedBarriersSupported.as_bool() - }); + let enhanced = enhanced_barriers(host); // SAFETY: the caller's. unsafe { if enhanced && let Ok(list) = list.cast::() { @@ -227,9 +320,53 @@ impl HostList { let at = to.offset(dst as u64); // What the title's CPU wrote around and under it so far goes first. to.refresh(self, dst as u64, len as u64); + let narrow = narrow_barriers() && enhanced_barriers(host); // SAFETY (both): an open list; live buffers (the list holds the // copies and its scratch memory), ranges inside them. - unsafe { wait_for_all(host, &self.list) }; + if narrow { + let mut pre = Vec::with_capacity(2); + if let Some(from) = &own { + if from.buffer.as_raw() == to.buffer.as_raw() { + pre.push(buf_barrier( + &to.buffer, + D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_ACCESS_COPY_SOURCE, + )); + } else { + pre.push(buf_barrier( + &from.buffer, + D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_ACCESS_COPY_SOURCE, + )); + pre.push(buf_barrier( + &to.buffer, + D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_ACCESS_COPY_DEST, + )); + } + } else { + pre.push(buf_barrier( + &to.buffer, + D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_ACCESS_COPY_DEST, + )); + } + let ok = unsafe { buffer_barriers(&self.list, &pre) }; + drop_buf_barriers(&mut pre); + if !ok { + unsafe { wait_for_all(host, &self.list) }; + } + } else { + unsafe { wait_for_all(host, &self.list) }; + } match (&own, &scratch) { (Some(from), _) => { from.refresh(self, src as u64, len as u64); @@ -240,8 +377,37 @@ impl HostList { }; unsafe { self.list.CopyBufferRegion(&between, 0, &from.buffer, offset, len as u64); - self.list.ResourceBarrier(&[transition(&between, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); - wait_for_all(host, &self.list); + if narrow { + let mut mid = [ + buf_barrier( + &between, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_ACCESS_COPY_DEST, + D3D12_BARRIER_ACCESS_COPY_SOURCE, + ), + buf_barrier( + &to.buffer, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_ACCESS_COPY_SOURCE, + D3D12_BARRIER_ACCESS_COPY_DEST, + ), + ]; + let ok = buffer_barriers(&self.list, &mid); + drop_buf_barriers(&mut mid); + if !ok { + self.list.ResourceBarrier(&[transition( + &between, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + wait_for_all(host, &self.list); + } + } else { + self.list.ResourceBarrier(&[transition(&between, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + wait_for_all(host, &self.list); + } self.list.CopyBufferRegion(&to.buffer, at, &between, 0, len as u64); } } else { @@ -254,7 +420,25 @@ impl HostList { }, (None, None) => return false, } - unsafe { wait_for_all(host, &self.list) }; + if narrow { + let mut post = [buf_barrier( + &to.buffer, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_ACCESS_COPY_DEST, + D3D12_BARRIER_ACCESS_COMMON, + )]; + // SAFETY: an open list; live destination buffer. + let ok = unsafe { buffer_barriers(&self.list, &post) }; + drop_buf_barriers(&mut post); + if !ok { + // SAFETY: an open list. + unsafe { wait_for_all(host, &self.list) }; + } + } else { + // SAFETY: an open list. + unsafe { wait_for_all(host, &self.list) }; + } STATS[0].fetch_add(1, Ordering::Relaxed); STATS[1].fetch_add(len as u64, Ordering::Relaxed); to.gpu_writes(self, dst as u64, len as u64); @@ -370,12 +554,42 @@ impl HostList { let between = self.between(host, len as u64)?; from.refresh(self, src as u64, len as u64); STATS[3].fetch_add(1, Ordering::Relaxed); + let narrow = narrow_barriers() && enhanced_barriers(host); // SAFETY: an open list; live buffers, ranges inside them. unsafe { - wait_for_all(host, &self.list); - self.list.CopyBufferRegion(&between, 0, &from.buffer, from.offset(src as u64), len as u64); - self.list.ResourceBarrier(&[transition(&between, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); - wait_for_all(host, &self.list); + if narrow { + let mut pre = [buf_barrier( + &from.buffer, + D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_ACCESS_COPY_SOURCE, + )]; + let ok = buffer_barriers(&self.list, &pre); + drop_buf_barriers(&mut pre); + if !ok { + wait_for_all(host, &self.list); + } + self.list.CopyBufferRegion(&between, 0, &from.buffer, from.offset(src as u64), len as u64); + let mut post = [buf_barrier( + &between, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_ACCESS_COPY_DEST, + D3D12_BARRIER_ACCESS_COPY_SOURCE, + )]; + let ok = buffer_barriers(&self.list, &post); + drop_buf_barriers(&mut post); + if !ok { + self.list.ResourceBarrier(&[transition(&between, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + wait_for_all(host, &self.list); + } + } else { + wait_for_all(host, &self.list); + self.list.CopyBufferRegion(&between, 0, &from.buffer, from.offset(src as u64), len as u64); + self.list.ResourceBarrier(&[transition(&between, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + wait_for_all(host, &self.list); + } } Some(between) } diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 341ef4e622..9a9f62c792 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -914,7 +914,58 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> .collect(); // Buffers have host copies, not resources the barrier can name: // a barrier on one waits for every shader write before it. - if barriers.iter().any(|b| { + // With `VICTORY_NARROW_BARRIERS=1`, skip read-only buffer transitions + // and split-barrier begins, and scope write-involving buffer barriers + // to the buffer's host copy when one is known. + if crate::host::place::narrow_barriers() { + use std::sync::atomic::Ordering::Relaxed; + use windows::core::Interface; + const BEGIN_ONLY: u32 = 1; + let (mut skipped, mut narrowed, mut need_global) = (0u64, 0u64, false); + for b in barriers { + if b.kind == 1 || b.first.is_null() { + continue; + } + let Some((data, size)) = crate::resource::buffer_bytes(b.first) else { + continue; + }; + if b.kind == 0 + && (b.flags & BEGIN_ONLY != 0 + || !buffer_transition_needs_uav((b.second >> 32) as u32, b.last as u32)) + { + skipped += 1; + continue; + } + if let Some(shadow) = crate::shadow::peek(data as u64, size) { + let raw = shadow.buffer.as_raw().cast_const().cast(); + if !host.iter().any(|h| h.kind == 2 && h.first == raw) { + list.keep(&shadow.buffer); + host.push(Barrier { + kind: 2, + flags: 0, + first: raw, + second: 0, + last: 0, + }); + } + narrowed += 1; + } else { + need_global = true; + } + } + if skipped > 0 { + crate::host::place::NARROW_STATS[4].fetch_add(skipped, Relaxed); + } + if narrowed > 0 { + crate::host::place::NARROW_STATS[5].fetch_add(narrowed, Relaxed); + } + if need_global { + host.push(UAV_BARRIER); + crate::host::place::NARROW_STATS[6].fetch_add(1, Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::WaitsForBuffers, 1); + } + } else if barriers.iter().any(|b| { b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some() }) { host.push(UAV_BARRIER); @@ -1702,6 +1753,14 @@ extern "system" fn sync(this: This, flags: u32, control: u32, address: u64, size } crate::copystat::add(crate::copystat::C::WaitsForGroups, 1); } + if crate::host::place::narrow_barriers() { + use std::sync::atomic::Ordering::Relaxed; + if !sync_flags_need_uav(flags) { + crate::host::place::NARROW_STATS[7].fetch_add(1, Relaxed); + return; + } + crate::host::place::NARROW_STATS[8].fetch_add(1, Relaxed); + } // SAFETY: the same layout; no resource named. let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; // SAFETY: an open list. @@ -2361,6 +2420,381 @@ fn group_waits_set() -> u8 { }) } +/// Standard D3D12 Enhanced Barriers group descriptor as passed by the title. +#[repr(C)] +#[derive(Clone, Copy)] +struct TitleBarrierGroup { + kind: u32, + num: u32, + ptr: *const u8, +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct TitleGlobalBarrier { + sync_before: u32, + sync_after: u32, + access_before: u32, + access_after: u32, +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct TitleBufferBarrier { + sync_before: u32, + sync_after: u32, + access_before: u32, + access_after: u32, + resource: This, + offset: u64, + size: u64, +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct TitleTextureBarrier { + sync_before: u32, + sync_after: u32, + access_before: u32, + access_after: u32, + layout_before: u32, + layout_after: u32, + resource: This, + subresources: [u32; 6], + flags: u32, +} + +#[cfg(windows)] +const _: () = { + use windows::Win32::Graphics::Direct3D12::*; + assert!(size_of::() == size_of::()); + assert!(size_of::() == size_of::()); + assert!(size_of::() == size_of::()); + assert!(size_of::() == size_of::()); +}; + +/// Compact narrowed barrier record carried across the thin recording tape. +/// `kind`: 0 = global, 1 = texture UAV, 2 = buffer. +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct CompactBarrier { + kind: u32, + sync_before: u32, + sync_after: u32, + _pad: u32, + resource: This, +} + +pub(crate) enum PackedGroups { + Skip, + Global, + Narrow(Vec), +} + +/// Whether a legacy buffer state transition involves a write state or `COMMON` +/// and therefore needs an ordering barrier on the host. +fn buffer_transition_needs_uav(before: u32, after: u32) -> bool { + // COMMON (0), UNORDERED_ACCESS (0x8), STREAM_OUT (0x100), COPY_DEST (0x400). + const WRITE_STATES: u32 = 0x8 | 0x100 | 0x400; + before == 0 || after == 0 || ((before | after) & WRITE_STATES) != 0 +} + +/// Whether console pipeline-sync flush flags include shader execution waits, +/// full-GPU idle, or shader cache writeback/invalidation that require a host +/// UAV barrier. Pure color/depth block or front-end cache flushes do not. +fn sync_flags_need_uav(flags: u32) -> bool { + // Shader partial flushes (CS/VS/PS), full idle, and L1/L2 texture/shader + // cache writeback/invalidate bits. + const SHADER_SYNC_MASK: u32 = + 0x0002_0000 | 0x0010_0000 | 0x0100_0000 | 0x0020_0000 | 0x0000_0800 | 0x0000_1000 | 0x0000_2000 | 0x0004_0000 | 0x0040_0000 | 0x0080_0000; + flags == 0 || (flags & SHADER_SYNC_MASK) != 0 +} + +/// Masks a title `D3D12_BARRIER_SYNC` bitfield to valid non-split PC sync bits, +/// falling back to `SYNC_ALL (1)` if unknown bits remain or the result is empty. +fn safe_sync(bits: u32) -> u32 { + const KNOWN: u32 = 0x0180_FFFF; + let masked = bits & KNOWN; + if masked == 0 || (bits & !KNOWN & !0x8000_0000) != 0 { + 1 + } else { + masked + } +} + +fn global_barrier_needs_host(sync_before: u32, sync_after: u32, access_before: u32, access_after: u32) -> bool { + const NO_ACCESS: u32 = 0x8000_0000; + if sync_before == 0 || sync_after == 0 || access_before == NO_ACCESS || access_after == NO_ACCESS { + return false; + } + // Any write access or COMMON (0) requires synchronization. + const WRITE_ACCESS: u32 = 0x8 | 0x10 | 0x20 | 0x100 | 0x400 | 0x1000 | 0x8000; + access_before == 0 || (access_before & WRITE_ACCESS) != 0 +} + +fn buffer_barrier_needs_host(sync_before: u32, sync_after: u32, access_before: u32, access_after: u32) -> bool { + const NO_ACCESS: u32 = 0x8000_0000; + if sync_before == 0 || sync_after == 0 || access_before == NO_ACCESS || access_after == NO_ACCESS { + return false; + } + const WRITE_ACCESS: u32 = 0x10 | 0x100 | 0x400 | 0x8000; + access_before == 0 || (access_before & WRITE_ACCESS) != 0 +} + +fn texture_barrier_needs_uav(sync_before: u32, sync_after: u32, access_before: u32, access_after: u32) -> bool { + const NO_ACCESS: u32 = 0x8000_0000; + const UAV_ACCESS: u32 = 0x10; + const SHADER_SYNC: u32 = 0x1 | 0x2 | 0x8 | 0x10 | 0x80 | 0x100 | 0x1000 | 0x2000 | 0x8000; + if sync_before == 0 || sync_after == 0 || access_before == NO_ACCESS { + return false; + } + if (access_before & UAV_ACCESS) != 0 || (access_after & UAV_ACCESS) != 0 { + return true; + } + access_before == 0 && (sync_before & SHADER_SYNC) != 0 +} + +/// Classifies an enhanced `Barrier()` call while the title's `groups` pointer +/// is live on the calling thread, returning compact records for replay or +/// indicating that the call can be skipped or needs a global fallback. +pub(crate) fn pack_barrier_groups(count: u32, groups: *const u8) -> PackedGroups { + if count == 0 { + return PackedGroups::Skip; + } + if groups.is_null() || count > 256 { + return PackedGroups::Global; + } + let mut out = Vec::new(); + let group_ptr = groups.cast::(); + for g in 0..count as usize { + // SAFETY: title passed `count` barrier groups (`count <= 256`, non-null). + let group = unsafe { group_ptr.add(g).read_unaligned() }; + if group.num == 0 { + continue; + } + if group.ptr.is_null() || group.num > 4096 { + return PackedGroups::Global; + } + match group.kind { + 0 => { + let p = group.ptr.cast::(); + for i in 0..group.num as usize { + // SAFETY: title passed `group.num` global barriers (`<= 4096`, non-null). + let b = unsafe { p.add(i).read_unaligned() }; + if global_barrier_needs_host(b.sync_before, b.sync_after, b.access_before, b.access_after) { + out.push(CompactBarrier { + kind: 0, + sync_before: safe_sync(b.sync_before), + sync_after: safe_sync(b.sync_after), + _pad: 0, + resource: std::ptr::null(), + }); + } + } + } + 1 => { + let p = group.ptr.cast::(); + for i in 0..group.num as usize { + // SAFETY: title passed `group.num` texture barriers (`<= 4096`, non-null). + let b = unsafe { p.add(i).read_unaligned() }; + if texture_barrier_needs_uav(b.sync_before, b.sync_after, b.access_before, b.access_after) { + if b.resource.is_null() { + return PackedGroups::Global; + } + out.push(CompactBarrier { + kind: 1, + sync_before: safe_sync(b.sync_before), + sync_after: safe_sync(b.sync_after), + _pad: 0, + resource: b.resource, + }); + } + } + } + 2 => { + let p = group.ptr.cast::(); + for i in 0..group.num as usize { + // SAFETY: title passed `group.num` buffer barriers (`<= 4096`, non-null). + let b = unsafe { p.add(i).read_unaligned() }; + if buffer_barrier_needs_host(b.sync_before, b.sync_after, b.access_before, b.access_after) { + if b.resource.is_null() { + return PackedGroups::Global; + } + out.push(CompactBarrier { + kind: 2, + sync_before: safe_sync(b.sync_before), + sync_after: safe_sync(b.sync_after), + _pad: 0, + resource: b.resource, + }); + } + } + } + _ => return PackedGroups::Global, + } + } + if out.is_empty() { + PackedGroups::Skip + } else { + PackedGroups::Narrow(out) + } +} + +/// Replays compact narrowed enhanced barriers on `this`. +#[cfg(windows)] +pub(crate) fn replay_narrow_barrier_groups(this: This, count: usize, items: *const CompactBarrier) { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + use windows::core::Interface; + if count == 0 || items.is_null() { + return; + } + let Some(list) = host_list(this) else { + return; + }; + with_state(this, |_, state| state.synced()); + // SAFETY: caller passes `count` valid `CompactBarrier` records from the thin tape or stack. + let slice = unsafe { std::slice::from_raw_parts(items, count) }; + let enhanced = crate::host::host().is_some_and(crate::host::place::enhanced_barriers); + let mut globals: Vec = Vec::new(); + let mut buffers: Vec = Vec::new(); + let mut legacy_uavs: Vec = Vec::new(); + let mut need_global_uav = false; + for &b in slice { + match b.kind { + 0 => { + if enhanced { + globals.push(D3D12_GLOBAL_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC(b.sync_before as i32), + SyncAfter: D3D12_BARRIER_SYNC(b.sync_after as i32), + AccessBefore: D3D12_BARRIER_ACCESS_COMMON, + AccessAfter: D3D12_BARRIER_ACCESS_COMMON, + }); + } else { + need_global_uav = true; + } + } + 1 => { + let target = crate::resource::twin_resource(b.resource) + .or_else(|| crate::resource::host_resource(b.resource)); + if let Some(tex) = target { + let raw = tex.as_raw().cast_const().cast(); + if !legacy_uavs.iter().any(|h| h.first == raw) { + list.keep(tex); + legacy_uavs.push(Barrier { + kind: 2, + flags: 0, + first: raw, + second: 0, + last: 0, + }); + } + } else { + need_global_uav = true; + } + } + 2 => { + let shadow = crate::resource::buffer_bytes(b.resource) + .and_then(|(data, size)| crate::shadow::peek(data as u64, size)); + if let Some(shadow) = shadow { + list.keep(&shadow.buffer); + if enhanced { + buffers.push(D3D12_BUFFER_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC(b.sync_before as i32), + SyncAfter: D3D12_BARRIER_SYNC(b.sync_after as i32), + AccessBefore: D3D12_BARRIER_ACCESS_COMMON, + AccessAfter: D3D12_BARRIER_ACCESS_COMMON, + pResource: std::mem::ManuallyDrop::new(Some(shadow.buffer.clone())), + Offset: 0, + Size: u64::MAX, + }); + } else { + let raw = shadow.buffer.as_raw().cast_const().cast(); + if !legacy_uavs.iter().any(|h| h.first == raw) { + legacy_uavs.push(Barrier { + kind: 2, + flags: 0, + first: raw, + second: 0, + last: 0, + }); + } + } + } else { + need_global_uav = true; + } + } + _ => need_global_uav = true, + } + if need_global_uav { + break; + } + } + if need_global_uav { + for b in &mut buffers { + // SAFETY: each entry was created with `ManuallyDrop::new(Some(clone))` once. + unsafe { std::mem::ManuallyDrop::drop(&mut b.pResource) }; + } + crate::host::place::NARROW_STATS[3].fetch_add(1, Relaxed); + // SAFETY: the same layout; no resource named. + let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; + // SAFETY: an open list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + return; + } + let mut emitted_enhanced = false; + if (!globals.is_empty() || !buffers.is_empty()) + && let Ok(list7) = list.list.cast::() + { + let mut groups = Vec::with_capacity(2); + if !globals.is_empty() { + groups.push(D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_GLOBAL, + NumBarriers: globals.len() as u32, + Anonymous: D3D12_BARRIER_GROUP_0 { + pGlobalBarriers: globals.as_ptr(), + }, + }); + } + if !buffers.is_empty() { + groups.push(D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_BUFFER, + NumBarriers: buffers.len() as u32, + Anonymous: D3D12_BARRIER_GROUP_0 { + pBufferBarriers: buffers.as_ptr(), + }, + }); + } + // SAFETY: open list; all buffer resources are kept alive on `list` and in `buffers`. + unsafe { list7.Barrier(&groups) }; + emitted_enhanced = true; + } + for b in &mut buffers { + // SAFETY: each entry was created with `ManuallyDrop::new(Some(clone))` once. + unsafe { std::mem::ManuallyDrop::drop(&mut b.pResource) }; + } + if !emitted_enhanced && (!globals.is_empty() || !buffers.is_empty()) { + crate::host::place::NARROW_STATS[3].fetch_add(1, Relaxed); + // SAFETY: the same layout; no resource named. + let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; + // SAFETY: an open list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + return; + } + if !legacy_uavs.is_empty() { + // SAFETY: same layout as `D3D12_RESOURCE_BARRIER`; resources kept alive on `list`. + let host = unsafe { + std::slice::from_raw_parts( + legacy_uavs.as_ptr().cast::(), + legacy_uavs.len(), + ) + }; + // SAFETY: open list and live resources. + unsafe { list.list.ResourceBarrier(host) }; + } + crate::host::place::NARROW_STATS[2].fetch_add(1, Relaxed); +} + /// The enhanced barriers `(group count, groups)`: buffer, texture and /// global barriers with layouts instead of states. Every host use of a /// title texture (clears, copies) moves its host copy to the state it needs @@ -2398,18 +2832,37 @@ extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { } } #[cfg(windows)] - if count > 0 - && let Some(list) = host_list(this) - { - use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; - with_state(this, |_, state| state.synced()); - if !group_waits(writes) { - return; + if count > 0 { + if crate::host::place::narrow_barriers() { + if !groups.is_null() { + match pack_barrier_groups(count, groups) { + PackedGroups::Skip => { + crate::host::place::NARROW_STATS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return; + } + PackedGroups::Narrow(items) => { + replay_narrow_barrier_groups(this, items.len(), items.as_ptr()); + return; + } + PackedGroups::Global => { + crate::host::place::NARROW_STATS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + } else { + crate::host::place::NARROW_STATS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + if let Some(list) = host_list(this) { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + with_state(this, |_, state| state.synced()); + if !crate::host::place::narrow_barriers() && !group_waits(writes) { + return; + } + // SAFETY: the same layout; no resource named. + let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; + // SAFETY: an open list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; } - // SAFETY: the same layout; no resource named. - let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; - // SAFETY: an open list. - unsafe { list.list.ResourceBarrier(&[barrier]) }; } #[cfg(not(windows))] let _ = (this, count, groups); @@ -2797,4 +3250,73 @@ mod tests { assert_eq!(release(allocator), 0); assert_eq!(release(tex), 0); } + + #[test] + fn narrow_barrier_classification() { + // Legacy buffer transitions: read-to-read skipped, write/COMMON kept. + assert!(!buffer_transition_needs_uav(0x40, 0x80)); // NON_PIXEL_SRV -> PIXEL_SRV + assert!(!buffer_transition_needs_uav(0x1, 0x200)); // VERTEX_AND_CB -> INDIRECT_ARG + assert!(buffer_transition_needs_uav(0x8, 0x40)); // UAV -> SRV + assert!(buffer_transition_needs_uav(0x400, 0x1)); // COPY_DEST -> VERTEX_AND_CB + assert!(buffer_transition_needs_uav(0, 0x80)); // COMMON -> SRV + + // Console pipeline sync flags: pure color/depth/front-end flushes skipped, + // shader partial flushes, idle and L1/L2 flushes kept. + assert!(sync_flags_need_uav(0)); + assert!(sync_flags_need_uav(0x0002_0000)); // CS partial + assert!(sync_flags_need_uav(0x0020_0000)); // idle + assert!(sync_flags_need_uav(0x0000_0800)); // BOP L2 writeback + assert!(!sync_flags_need_uav(0x0000_0004 | 0x0000_0008)); // color/depth block data only + assert!(!sync_flags_need_uav(0x4000_0000 | 0x0800_0000)); // PFP/KCache only + + // Enhanced barrier groups: pure non-UAV texture transitions are skipped. + let tex_rt_to_srv = TitleTextureBarrier { + sync_before: 0x40, // RENDER_TARGET + sync_after: 0x10, // PIXEL_SHADING + access_before: 0x8, // RENDER_TARGET + access_after: 0x80, // SHADER_RESOURCE + layout_before: 4, + layout_after: 5, + resource: std::ptr::null(), + subresources: [0; 6], + flags: 0, + }; + let group = TitleBarrierGroup { + kind: 1, + num: 1, + ptr: (&raw const tex_rt_to_srv).cast(), + }; + assert!(matches!(pack_barrier_groups(1, (&raw const group).cast()), PackedGroups::Skip)); + + // Enhanced buffer UAV -> indirect barrier narrows to one CompactBarrier. + let fake_res = 0x1234usize as This; + let buf_uav = TitleBufferBarrier { + sync_before: 0x80, // COMPUTE_SHADING + sync_after: 0x800, // EXECUTE_INDIRECT + access_before: 0x10, // UNORDERED_ACCESS + access_after: 0x200, // INDIRECT_ARGUMENT + resource: fake_res, + offset: 0, + size: u64::MAX, + }; + let group = TitleBarrierGroup { + kind: 2, + num: 1, + ptr: (&raw const buf_uav).cast(), + }; + match pack_barrier_groups(1, (&raw const group).cast()) { + PackedGroups::Narrow(items) => { + assert_eq!(items.len(), 1); + assert_eq!(items[0].kind, 2); + assert_eq!(items[0].sync_before, 0x80); + assert_eq!(items[0].sync_after, 0x800); + assert_eq!(items[0].resource, fake_res); + } + _ => panic!("expected narrowed buffer barrier"), + } + + // Split sync flag is stripped; unknown bits fall back to SYNC_ALL (1). + assert_eq!(safe_sync(0x80 | 0x8000_0000), 0x80); + assert_eq!(safe_sync(0x0001_0000), 1); + } } diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs index 884307c76b..fd753086d8 100644 --- a/crates/victory-gpu/src/list/thin.rs +++ b/crates/victory-gpu/src/list/thin.rs @@ -729,7 +729,24 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> } 0 } -extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { +extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { + if count > 0 && crate::host::place::narrow_barriers() { + match super::pack_barrier_groups(count, groups) { + super::PackedGroups::Skip => { + crate::host::place::NARROW_STATS[1].fetch_add(1, Relaxed); + return; + } + super::PackedGroups::Narrow(items) => { + front(this).put_with( + BARRIER_GROUPS, + &[u64::from(items.len() as u32) | (1u64 << 63)], + &[bytes_of(items.as_ptr(), items.len())], + ); + return; + } + super::PackedGroups::Global => {} + } + } front(this).put(BARRIER_GROUPS, &[u64::from(count)]); } extern "system" fn viewports(this: This, count: u32, items: *const D3D12_VIEWPORT) { @@ -910,7 +927,13 @@ fn translate(list: This, stream: &[u64], left: impl Fn() -> bool) -> (u64, bool) BARRIER => { super::barrier(list, n as u32, at_or(w, 1)); } - BARRIER_GROUPS => super::barrier_groups(list, n as u32, std::ptr::null()), + BARRIER_GROUPS => { + if w[0] & (1u64 << 63) != 0 { + super::replay_narrow_barrier_groups(list, (w[0] & 0xFFFF_FFFF) as usize, at_or(w, 1)); + } else { + super::barrier_groups(list, n as u32, std::ptr::null()); + } + } VIEWPORTS => state::viewports(list, n as u32, at(w, 1, n)), SCISSORS => state::scissors(list, n as u32, at(w, 1, n)), BLEND_FACTOR => state::blend_factor(list, at(w, 1, n)), From 5cd5faff9df56fabb84ca5224830d27223bfb355 Mon Sep 17 00:00:00 2001 From: Czer0xx Date: Sat, 28 Nov 2026 18:37:49 +0100 Subject: [PATCH 2/2] GPU: fix narrow-barrier ordering holes and add sub-modes (VICTORY_NARROW_BARRIERS) --- crates/victory-gpu/src/host/place.rs | 154 +++++++++-- crates/victory-gpu/src/list.rs | 386 +++++++++++++++++++++------ crates/victory-gpu/src/list/thin.rs | 4 +- crates/victory-gpu/src/shadow.rs | 36 +++ 4 files changed, 466 insertions(+), 114 deletions(-) diff --git a/crates/victory-gpu/src/host/place.rs b/crates/victory-gpu/src/host/place.rs index 0174c25654..e99afbc851 100644 --- a/crates/victory-gpu/src/host/place.rs +++ b/crates/victory-gpu/src/host/place.rs @@ -60,21 +60,81 @@ fn placed_constants() -> bool { *ON.get_or_init(|| on() && std::env::var_os("VICTORY_PLACED_CONSTANTS").is_none_or(|v| v != "0")) } -/// Whether GPU barriers in `place.rs` and `list.rs` are narrowed to the -/// touched buffers, textures and shader sync stages instead of emitting -/// unconditional global `SYNC_ALL` / `UAV_BARRIER(NULL)` drains -/// (`VICTORY_NARROW_BARRIERS=1`; off by default). +/// Sub-mode bitflags for `VICTORY_NARROW_BARRIERS` (off by default). /// -/// Off by default, every placed copy records two global `SYNC_ALL` barriers -/// (~52 per frame), and `barrier_groups`, legacy buffer barriers and pipeline -/// syncs record global `UAV_BARRIER(NULL)` drains even for non-UAV texture -/// layout transitions or read-only buffer transitions. -pub(crate) fn narrow_barriers() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| crate::switch::on("VICTORY_NARROW_BARRIERS")) +/// Accepts `1`/`all`/`on`/`true` to enable all paths, `0`/`off`/`false`/`none` +/// (or empty/unset) to disable, or a comma-separated combination of +/// `place`, `groups`, `legacy`, and `sync` to isolate individual paths. +const NARROW_PLACE: u8 = 1 << 0; +const NARROW_GROUPS: u8 = 1 << 1; +const NARROW_LEGACY: u8 = 1 << 2; +const NARROW_SYNC: u8 = 1 << 3; +const NARROW_ALL: u8 = NARROW_PLACE | NARROW_GROUPS | NARROW_LEGACY | NARROW_SYNC; + +fn parse_narrow_barriers(raw: Option<&str>) -> u8 { + let Some(raw) = raw else { + return 0; + }; + let trimmed = raw.trim(); + if trimmed.is_empty() + || trimmed.eq_ignore_ascii_case("0") + || trimmed.eq_ignore_ascii_case("off") + || trimmed.eq_ignore_ascii_case("false") + || trimmed.eq_ignore_ascii_case("none") + { + return 0; + } + if trimmed == "1" + || trimmed.eq_ignore_ascii_case("all") + || trimmed.eq_ignore_ascii_case("on") + || trimmed.eq_ignore_ascii_case("true") + { + return NARROW_ALL; + } + let mut mask = 0u8; + for token in trimmed.split([',', '+']) { + match token.trim().to_ascii_lowercase().as_str() { + "place" => mask |= NARROW_PLACE, + "groups" => mask |= NARROW_GROUPS, + "legacy" => mask |= NARROW_LEGACY, + "sync" => mask |= NARROW_SYNC, + "all" | "1" => mask |= NARROW_ALL, + _ => {} + } + } + mask } -/// Since the last frame-rate line (when `VICTORY_NARROW_BARRIERS=1`): +/// Active sub-mode bitmask for `VICTORY_NARROW_BARRIERS`. +pub(crate) fn narrow_mask() -> u8 { + static MASK: OnceLock = OnceLock::new(); + *MASK.get_or_init(|| { + let raw = std::env::var("VICTORY_NARROW_BARRIERS").ok(); + parse_narrow_barriers(raw.as_deref()) + }) +} + +/// Whether placed-copy barriers in `place.rs` are narrowed (`place` sub-mode). +pub(crate) fn narrow_place() -> bool { + narrow_mask() & NARROW_PLACE != 0 +} + +/// Whether enhanced `Barrier()` groups in `list.rs`/`list/thin.rs` are narrowed (`groups` sub-mode). +pub(crate) fn narrow_groups() -> bool { + narrow_mask() & NARROW_GROUPS != 0 +} + +/// Whether legacy buffer `ResourceBarrier` calls in `list.rs` are narrowed (`legacy` sub-mode). +pub(crate) fn narrow_legacy() -> bool { + narrow_mask() & NARROW_LEGACY != 0 +} + +/// Whether console pipeline `sync()` calls in `list.rs` are narrowed (`sync` sub-mode). +pub(crate) fn narrow_sync() -> bool { + narrow_mask() & NARROW_SYNC != 0 +} + +/// Since the last frame-rate line (when `VICTORY_NARROW_BARRIERS` is enabled): /// `[0]` place buffer barriers narrowed, /// `[1..4]` enhanced barrier groups (skipped, narrowed, global fallback), /// `[4..7]` legacy buffer barriers (skipped, narrowed, global fallback), @@ -82,12 +142,13 @@ pub(crate) fn narrow_barriers() -> bool { pub(crate) static NARROW_STATS: [std::sync::atomic::AtomicU64; 9] = [const { std::sync::atomic::AtomicU64::new(0) }; 9]; pub(super) fn log_narrow(frames: f64) { - if !narrow_barriers() { + let mask = narrow_mask(); + if mask == 0 { return; } let s: Vec = NARROW_STATS.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect(); tracing::info!( - "narrow barriers per frame (VICTORY_NARROW_BARRIERS=1): place {:.1} narrowed; groups {:.1} skipped, {:.1} narrowed, {:.1} global; \ + "narrow barriers per frame (VICTORY_NARROW_BARRIERS mask={mask:#x}): place {:.1} narrowed; groups {:.1} skipped, {:.1} narrowed, {:.1} global; \ legacy_buf {:.1} skipped, {:.1} narrowed, {:.1} global; sync {:.1} skipped, {:.1} global", s[0], s[1], @@ -320,7 +381,7 @@ impl HostList { let at = to.offset(dst as u64); // What the title's CPU wrote around and under it so far goes first. to.refresh(self, dst as u64, len as u64); - let narrow = narrow_barriers() && enhanced_barriers(host); + let narrow = narrow_place() && enhanced_barriers(host); // SAFETY (both): an open list; live buffers (the list holds the // copies and its scratch memory), ranges inside them. if narrow { @@ -421,14 +482,27 @@ impl HostList { (None, None) => return false, } if narrow { - let mut post = [buf_barrier( + let mut post = Vec::with_capacity(2); + post.push(buf_barrier( &to.buffer, D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_ACCESS_COPY_DEST, D3D12_BARRIER_ACCESS_COMMON, - )]; - // SAFETY: an open list; live destination buffer. + )); + // Order subsequent writes to `from.buffer` after this copy finishes reading it (WAR). + if let Some(from) = &own + && from.buffer.as_raw() != to.buffer.as_raw() + { + post.push(buf_barrier( + &from.buffer, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_ACCESS_COPY_SOURCE, + D3D12_BARRIER_ACCESS_COMMON, + )); + } + // SAFETY: an open list; live destination (and source) buffers. let ok = unsafe { buffer_barriers(&self.list, &post) }; drop_buf_barriers(&mut post); if !ok { @@ -554,7 +628,7 @@ impl HostList { let between = self.between(host, len as u64)?; from.refresh(self, src as u64, len as u64); STATS[3].fetch_add(1, Ordering::Relaxed); - let narrow = narrow_barriers() && enhanced_barriers(host); + let narrow = narrow_place() && enhanced_barriers(host); // SAFETY: an open list; live buffers, ranges inside them. unsafe { if narrow { @@ -571,13 +645,23 @@ impl HostList { wait_for_all(host, &self.list); } self.list.CopyBufferRegion(&between, 0, &from.buffer, from.offset(src as u64), len as u64); - let mut post = [buf_barrier( - &between, - D3D12_BARRIER_SYNC_COPY, - D3D12_BARRIER_SYNC_COPY, - D3D12_BARRIER_ACCESS_COPY_DEST, - D3D12_BARRIER_ACCESS_COPY_SOURCE, - )]; + let mut post = [ + buf_barrier( + &between, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_ACCESS_COPY_DEST, + D3D12_BARRIER_ACCESS_COPY_SOURCE, + ), + // Order subsequent writes to `from.buffer` after this copy finishes reading it (WAR). + buf_barrier( + &from.buffer, + D3D12_BARRIER_SYNC_COPY, + D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_ACCESS_COPY_SOURCE, + D3D12_BARRIER_ACCESS_COMMON, + ), + ]; let ok = buffer_barriers(&self.list, &post); drop_buf_barriers(&mut post); if !ok { @@ -605,6 +689,24 @@ impl HostList { #[cfg(test)] mod tests { + #[test] + fn narrow_barriers_submode_parsing() { + use super::{NARROW_ALL, NARROW_GROUPS, NARROW_LEGACY, NARROW_PLACE, NARROW_SYNC, parse_narrow_barriers}; + assert_eq!(parse_narrow_barriers(None), 0); + assert_eq!(parse_narrow_barriers(Some("")), 0); + assert_eq!(parse_narrow_barriers(Some("0")), 0); + assert_eq!(parse_narrow_barriers(Some("off")), 0); + assert_eq!(parse_narrow_barriers(Some("none")), 0); + assert_eq!(parse_narrow_barriers(Some("1")), NARROW_ALL); + assert_eq!(parse_narrow_barriers(Some("all")), NARROW_ALL); + assert_eq!(parse_narrow_barriers(Some("place")), NARROW_PLACE); + assert_eq!(parse_narrow_barriers(Some("groups")), NARROW_GROUPS); + assert_eq!(parse_narrow_barriers(Some("legacy")), NARROW_LEGACY); + assert_eq!(parse_narrow_barriers(Some("sync")), NARROW_SYNC); + assert_eq!(parse_narrow_barriers(Some("place, sync")), NARROW_PLACE | NARROW_SYNC); + assert_eq!(parse_narrow_barriers(Some("GROUPS+legacy")), NARROW_GROUPS | NARROW_LEGACY); + } + /// What copies with two sides cost to make (ignored: a measurement for /// `VICTORY_CARD_ALL`): buffers of 64 KiB on the card and in the PC's /// memory. diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 9a9f62c792..6d75d2f15b 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -914,14 +914,18 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> .collect(); // Buffers have host copies, not resources the barrier can name: // a barrier on one waits for every shader write before it. - // With `VICTORY_NARROW_BARRIERS=1`, skip read-only buffer transitions - // and split-barrier begins, and scope write-involving buffer barriers - // to the buffer's host copy when one is known. - if crate::host::place::narrow_barriers() { + // With `VICTORY_NARROW_BARRIERS` (`legacy`), skip read-only buffer + // transitions and split-barrier begins, and scope write-involving + // buffer barriers to all overlapping host buffer copies. + if crate::host::place::narrow_legacy() { use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; use windows::core::Interface; const BEGIN_ONLY: u32 = 1; + let enhanced = crate::host::host().is_some_and(crate::host::place::enhanced_barriers); let (mut skipped, mut narrowed, mut need_global) = (0u64, 0u64, false); + let mut enhanced_bufs: Vec = Vec::new(); + let mut seen_bufs: Vec = Vec::new(); for b in barriers { if b.kind == 1 || b.first.is_null() { continue; @@ -936,17 +940,34 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> skipped += 1; continue; } - if let Some(shadow) = crate::shadow::peek(data as u64, size) { - let raw = shadow.buffer.as_raw().cast_const().cast(); - if !host.iter().any(|h| h.kind == 2 && h.first == raw) { - list.keep(&shadow.buffer); - host.push(Barrier { - kind: 2, - flags: 0, - first: raw, - second: 0, - last: 0, - }); + let shadows = crate::shadow::peek_overlapping(data as u64, size); + if !shadows.is_empty() { + for shadow in shadows { + let raw = shadow.buffer.as_raw().cast_const().cast(); + if enhanced { + if !seen_bufs.contains(&raw) { + seen_bufs.push(raw); + list.keep(&shadow.buffer); + enhanced_bufs.push(D3D12_BUFFER_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC_ALL, + SyncAfter: D3D12_BARRIER_SYNC_ALL, + AccessBefore: D3D12_BARRIER_ACCESS_COMMON, + AccessAfter: D3D12_BARRIER_ACCESS_COMMON, + pResource: std::mem::ManuallyDrop::new(Some(shadow.buffer.clone())), + Offset: 0, + Size: u64::MAX, + }); + } + } else if !host.iter().any(|h| h.kind == 2 && h.first == raw) { + list.keep(&shadow.buffer); + host.push(Barrier { + kind: 2, + flags: 0, + first: raw, + second: 0, + last: 0, + }); + } } narrowed += 1; } else { @@ -959,6 +980,29 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> if narrowed > 0 { crate::host::place::NARROW_STATS[5].fetch_add(narrowed, Relaxed); } + if !enhanced_bufs.is_empty() { + let emitted = if let Ok(list7) = list.list.cast::() { + let group = [D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_BUFFER, + NumBarriers: enhanced_bufs.len() as u32, + Anonymous: D3D12_BARRIER_GROUP_0 { + pBufferBarriers: enhanced_bufs.as_ptr(), + }, + }]; + // SAFETY: open list; buffer resources are kept alive on `list` and in `enhanced_bufs`. + unsafe { list7.Barrier(&group) }; + true + } else { + false + }; + for b in &mut enhanced_bufs { + // SAFETY: each entry was created with `ManuallyDrop::new(Some(clone))` once. + unsafe { std::mem::ManuallyDrop::drop(&mut b.pResource) }; + } + if !emitted { + need_global = true; + } + } if need_global { host.push(UAV_BARRIER); crate::host::place::NARROW_STATS[6].fetch_add(1, Relaxed); @@ -1753,7 +1797,7 @@ extern "system" fn sync(this: This, flags: u32, control: u32, address: u64, size } crate::copystat::add(crate::copystat::C::WaitsForGroups, 1); } - if crate::host::place::narrow_barriers() { + if crate::host::place::narrow_sync() { use std::sync::atomic::Ordering::Relaxed; if !sync_flags_need_uav(flags) { crate::host::place::NARROW_STATS[7].fetch_add(1, Relaxed); @@ -2499,15 +2543,24 @@ fn buffer_transition_needs_uav(before: u32, after: u32) -> bool { before == 0 || after == 0 || ((before | after) & WRITE_STATES) != 0 } -/// Whether console pipeline-sync flush flags include shader execution waits, -/// full-GPU idle, or shader cache writeback/invalidation that require a host -/// UAV barrier. Pure color/depth block or front-end cache flushes do not. +/// Whether console pipeline-sync flush flags include color/depth block flushes, +/// shader execution waits, full-GPU idle, or shader cache writeback/invalidation +/// that require a host barrier. Pure front-end/PFP/KCache flushes do not. fn sync_flags_need_uav(flags: u32) -> bool { - // Shader partial flushes (CS/VS/PS), full idle, and L1/L2 texture/shader - // cache writeback/invalidate bits. - const SHADER_SYNC_MASK: u32 = - 0x0002_0000 | 0x0010_0000 | 0x0100_0000 | 0x0020_0000 | 0x0000_0800 | 0x0000_1000 | 0x0000_2000 | 0x0004_0000 | 0x0040_0000 | 0x0080_0000; - flags == 0 || (flags & SHADER_SYNC_MASK) != 0 + // Color/depth block & metadata flushes (0x3F), shader partial flushes + // (CS/VS/PS), full idle, and L1/L2 texture/shader cache writeback/invalidate bits. + const SYNC_MASK: u32 = 0x0000_003F + | 0x0002_0000 + | 0x0010_0000 + | 0x0100_0000 + | 0x0020_0000 + | 0x0000_0800 + | 0x0000_1000 + | 0x0000_2000 + | 0x0004_0000 + | 0x0040_0000 + | 0x0080_0000; + flags == 0 || (flags & SYNC_MASK) != 0 } /// Masks a title `D3D12_BARRIER_SYNC` bitfield to valid non-split PC sync bits, @@ -2524,34 +2577,85 @@ fn safe_sync(bits: u32) -> u32 { fn global_barrier_needs_host(sync_before: u32, sync_after: u32, access_before: u32, access_after: u32) -> bool { const NO_ACCESS: u32 = 0x8000_0000; - if sync_before == 0 || sync_after == 0 || access_before == NO_ACCESS || access_after == NO_ACCESS { + // Any write access: RTV, UAV, DSV_WRITE, STREAM_OUT, COPY_DEST, RESOLVE_DEST, RT_AS_WRITE. + const WRITE_ACCESS: u32 = 0x8 | 0x10 | 0x20 | 0x100 | 0x400 | 0x1000 | 0x8000; + if sync_before == 0 || sync_after == 0 { return false; } - // Any write access or COMMON (0) requires synchronization. - const WRITE_ACCESS: u32 = 0x8 | 0x10 | 0x20 | 0x100 | 0x400 | 0x1000 | 0x8000; - access_before == 0 || (access_before & WRITE_ACCESS) != 0 + // Keep COMMON (0), NO_ACCESS execution/flush barriers, and any RAW/WAR/WAW write access. + access_before == 0 + || access_after == 0 + || access_before == NO_ACCESS + || access_after == NO_ACCESS + || ((access_before | access_after) & WRITE_ACCESS) != 0 } fn buffer_barrier_needs_host(sync_before: u32, sync_after: u32, access_before: u32, access_after: u32) -> bool { const NO_ACCESS: u32 = 0x8000_0000; - if sync_before == 0 || sync_after == 0 || access_before == NO_ACCESS || access_after == NO_ACCESS { + // Buffer write accesses: UAV, STREAM_OUT, COPY_DEST, RT_AS_WRITE. + const WRITE_ACCESS: u32 = 0x10 | 0x100 | 0x400 | 0x8000; + if sync_before == 0 || sync_after == 0 { return false; } - const WRITE_ACCESS: u32 = 0x10 | 0x100 | 0x400 | 0x8000; - access_before == 0 || (access_before & WRITE_ACCESS) != 0 + // Keep COMMON (0), NO_ACCESS execution/flush barriers, and any RAW/WAR/WAW write access. + access_before == 0 + || access_after == 0 + || access_before == NO_ACCESS + || access_after == NO_ACCESS + || ((access_before | access_after) & WRITE_ACCESS) != 0 } -fn texture_barrier_needs_uav(sync_before: u32, sync_after: u32, access_before: u32, access_after: u32) -> bool { +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum TextureBarrierKind { + Skip, + UavOnly, + ScopedGlobal, +} + +fn classify_texture_barrier( + sync_before: u32, + sync_after: u32, + access_before: u32, + access_after: u32, +) -> TextureBarrierKind { const NO_ACCESS: u32 = 0x8000_0000; const UAV_ACCESS: u32 = 0x10; - const SHADER_SYNC: u32 = 0x1 | 0x2 | 0x8 | 0x10 | 0x80 | 0x100 | 0x1000 | 0x2000 | 0x8000; - if sync_before == 0 || sync_after == 0 || access_before == NO_ACCESS { - return false; + // Non-UAV texture writes: RTV, DSV_WRITE, COPY_DEST, RESOLVE_DEST. + const NON_UAV_WRITE: u32 = 0x8 | 0x20 | 0x400 | 0x1000; + if sync_before == 0 || sync_after == 0 { + return TextureBarrierKind::Skip; + } + if access_before == NO_ACCESS + || access_after == NO_ACCESS + || access_before == 0 + || access_after == 0 + || ((access_before | access_after) & NON_UAV_WRITE) != 0 + { + return TextureBarrierKind::ScopedGlobal; + } + if access_before == UAV_ACCESS && access_after == UAV_ACCESS { + return TextureBarrierKind::UavOnly; } - if (access_before & UAV_ACCESS) != 0 || (access_after & UAV_ACCESS) != 0 { - return true; + if ((access_before | access_after) & UAV_ACCESS) != 0 { + // UAV <-> SRV / other read accesses need a full stage/cache barrier, + // not a legacy UAV-only barrier (especially for bindless SRV reads). + return TextureBarrierKind::ScopedGlobal; + } + TextureBarrierKind::Skip +} + +fn push_scoped_global(out: &mut Vec, sync_before: u32, sync_after: u32) { + let sb = safe_sync(sync_before); + let sa = safe_sync(sync_after); + if !out.iter().any(|c| c.kind == 0 && c.sync_before == sb && c.sync_after == sa) { + out.push(CompactBarrier { + kind: 0, + sync_before: sb, + sync_after: sa, + _pad: 0, + resource: std::ptr::null(), + }); } - access_before == 0 && (sync_before & SHADER_SYNC) != 0 } /// Classifies an enhanced `Barrier()` call while the title's `groups` pointer @@ -2582,13 +2686,7 @@ pub(crate) fn pack_barrier_groups(count: u32, groups: *const u8) -> PackedGroups // SAFETY: title passed `group.num` global barriers (`<= 4096`, non-null). let b = unsafe { p.add(i).read_unaligned() }; if global_barrier_needs_host(b.sync_before, b.sync_after, b.access_before, b.access_after) { - out.push(CompactBarrier { - kind: 0, - sync_before: safe_sync(b.sync_before), - sync_after: safe_sync(b.sync_after), - _pad: 0, - resource: std::ptr::null(), - }); + push_scoped_global(&mut out, b.sync_before, b.sync_after); } } } @@ -2597,17 +2695,24 @@ pub(crate) fn pack_barrier_groups(count: u32, groups: *const u8) -> PackedGroups for i in 0..group.num as usize { // SAFETY: title passed `group.num` texture barriers (`<= 4096`, non-null). let b = unsafe { p.add(i).read_unaligned() }; - if texture_barrier_needs_uav(b.sync_before, b.sync_after, b.access_before, b.access_after) { - if b.resource.is_null() { - return PackedGroups::Global; + match classify_texture_barrier(b.sync_before, b.sync_after, b.access_before, b.access_after) { + TextureBarrierKind::Skip => {} + TextureBarrierKind::ScopedGlobal => { + push_scoped_global(&mut out, b.sync_before, b.sync_after); + } + TextureBarrierKind::UavOnly => { + if b.resource.is_null() { + push_scoped_global(&mut out, b.sync_before, b.sync_after); + } else { + out.push(CompactBarrier { + kind: 1, + sync_before: safe_sync(b.sync_before), + sync_after: safe_sync(b.sync_after), + _pad: 0, + resource: b.resource, + }); + } } - out.push(CompactBarrier { - kind: 1, - sync_before: safe_sync(b.sync_before), - sync_after: safe_sync(b.sync_after), - _pad: 0, - resource: b.resource, - }); } } } @@ -2646,18 +2751,19 @@ pub(crate) fn replay_narrow_barrier_groups(this: This, count: usize, items: *con use std::sync::atomic::Ordering::Relaxed; use windows::Win32::Graphics::Direct3D12::*; use windows::core::Interface; + with_state(this, |_, state| state.synced()); if count == 0 || items.is_null() { return; } let Some(list) = host_list(this) else { return; }; - with_state(this, |_, state| state.synced()); // SAFETY: caller passes `count` valid `CompactBarrier` records from the thin tape or stack. let slice = unsafe { std::slice::from_raw_parts(items, count) }; let enhanced = crate::host::host().is_some_and(crate::host::place::enhanced_barriers); let mut globals: Vec = Vec::new(); let mut buffers: Vec = Vec::new(); + let mut seen_bufs: Vec<(This, u32, u32)> = Vec::new(); let mut legacy_uavs: Vec = Vec::new(); let mut need_global_uav = false; for &b in slice { @@ -2675,6 +2781,23 @@ pub(crate) fn replay_narrow_barrier_groups(this: This, count: usize, items: *con } } 1 => { + if crate::resource::is_aliased(b.resource) { + if enhanced { + let sb = D3D12_BARRIER_SYNC(b.sync_before as i32); + let sa = D3D12_BARRIER_SYNC(b.sync_after as i32); + if !globals.iter().any(|g| g.SyncBefore == sb && g.SyncAfter == sa) { + globals.push(D3D12_GLOBAL_BARRIER { + SyncBefore: sb, + SyncAfter: sa, + AccessBefore: D3D12_BARRIER_ACCESS_COMMON, + AccessAfter: D3D12_BARRIER_ACCESS_COMMON, + }); + } + } else { + need_global_uav = true; + } + continue; + } let target = crate::resource::twin_resource(b.resource) .or_else(|| crate::resource::host_resource(b.resource)); if let Some(tex) = target { @@ -2694,23 +2817,28 @@ pub(crate) fn replay_narrow_barrier_groups(this: This, count: usize, items: *con } } 2 => { - let shadow = crate::resource::buffer_bytes(b.resource) - .and_then(|(data, size)| crate::shadow::peek(data as u64, size)); - if let Some(shadow) = shadow { - list.keep(&shadow.buffer); - if enhanced { - buffers.push(D3D12_BUFFER_BARRIER { - SyncBefore: D3D12_BARRIER_SYNC(b.sync_before as i32), - SyncAfter: D3D12_BARRIER_SYNC(b.sync_after as i32), - AccessBefore: D3D12_BARRIER_ACCESS_COMMON, - AccessAfter: D3D12_BARRIER_ACCESS_COMMON, - pResource: std::mem::ManuallyDrop::new(Some(shadow.buffer.clone())), - Offset: 0, - Size: u64::MAX, - }); - } else { + let shadows = crate::resource::buffer_bytes(b.resource) + .map(|(data, size)| crate::shadow::peek_overlapping(data as u64, size)) + .unwrap_or_default(); + if !shadows.is_empty() { + for shadow in shadows { let raw = shadow.buffer.as_raw().cast_const().cast(); - if !legacy_uavs.iter().any(|h| h.first == raw) { + list.keep(&shadow.buffer); + if enhanced { + let key = (raw, b.sync_before, b.sync_after); + if !seen_bufs.contains(&key) { + seen_bufs.push(key); + buffers.push(D3D12_BUFFER_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC(b.sync_before as i32), + SyncAfter: D3D12_BARRIER_SYNC(b.sync_after as i32), + AccessBefore: D3D12_BARRIER_ACCESS_COMMON, + AccessAfter: D3D12_BARRIER_ACCESS_COMMON, + pResource: std::mem::ManuallyDrop::new(Some(shadow.buffer.clone())), + Offset: 0, + Size: u64::MAX, + }); + } + } else if !legacy_uavs.iter().any(|h| h.first == raw) { legacy_uavs.push(Barrier { kind: 2, flags: 0, @@ -2833,10 +2961,11 @@ extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { } #[cfg(windows)] if count > 0 { - if crate::host::place::narrow_barriers() { + if crate::host::place::narrow_groups() { if !groups.is_null() { match pack_barrier_groups(count, groups) { PackedGroups::Skip => { + with_state(this, |_, state| state.synced()); crate::host::place::NARROW_STATS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); return; } @@ -2855,7 +2984,7 @@ extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { if let Some(list) = host_list(this) { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; with_state(this, |_, state| state.synced()); - if !crate::host::place::narrow_barriers() && !group_waits(writes) { + if !crate::host::place::narrow_groups() && !group_waits(writes) { return; } // SAFETY: the same layout; no resource named. @@ -3260,23 +3389,81 @@ mod tests { assert!(buffer_transition_needs_uav(0x400, 0x1)); // COPY_DEST -> VERTEX_AND_CB assert!(buffer_transition_needs_uav(0, 0x80)); // COMMON -> SRV - // Console pipeline sync flags: pure color/depth/front-end flushes skipped, - // shader partial flushes, idle and L1/L2 flushes kept. + // Console pipeline sync flags: color/depth block flushes, shader partial + // flushes, idle and L1/L2 flushes kept; pure front-end flushes skipped. assert!(sync_flags_need_uav(0)); assert!(sync_flags_need_uav(0x0002_0000)); // CS partial assert!(sync_flags_need_uav(0x0020_0000)); // idle assert!(sync_flags_need_uav(0x0000_0800)); // BOP L2 writeback - assert!(!sync_flags_need_uav(0x0000_0004 | 0x0000_0008)); // color/depth block data only + assert!(sync_flags_need_uav(0x0000_0004 | 0x0000_0008)); // color/depth block data kept assert!(!sync_flags_need_uav(0x4000_0000 | 0x0800_0000)); // PFP/KCache only - // Enhanced barrier groups: pure non-UAV texture transitions are skipped. - let tex_rt_to_srv = TitleTextureBarrier { - sync_before: 0x40, // RENDER_TARGET - sync_after: 0x10, // PIXEL_SHADING - access_before: 0x8, // RENDER_TARGET - access_after: 0x80, // SHADER_RESOURCE - layout_before: 4, - layout_after: 5, + // NO_ACCESS execution barriers (with non-zero syncs) are preserved across all kinds. + assert!(global_barrier_needs_host(0x80, 0x10, 0x8000_0000, 0x8000_0000)); + assert!(buffer_barrier_needs_host(0x80, 0x800, 0x10, 0x8000_0000)); + assert_eq!( + classify_texture_barrier(0x40, 0x10, 0x8000_0000, 0x8000_0000), + TextureBarrierKind::ScopedGlobal + ); + // SYNC_NONE barriers are skipped. + assert!(!global_barrier_needs_host(0, 0x10, 0x8000_0000, 0x8000_0000)); + assert!(!buffer_barrier_needs_host(0x80, 0, 0x10, 0x80)); + assert_eq!(classify_texture_barrier(0, 0x10, 0x8, 0x80), TextureBarrierKind::Skip); + + // WAR (read -> write) barriers are preserved; pure read -> read barriers are skipped. + assert!(global_barrier_needs_host(0x10, 0x40, 0x80, 0x8)); // SRV -> RTV + assert!(!global_barrier_needs_host(0x10, 0x80, 0x80, 0x80)); // SRV -> SRV + assert!(buffer_barrier_needs_host(0x10, 0x80, 0x80, 0x10)); // SRV -> UAV + assert!(!buffer_barrier_needs_host(0x8, 0x10, 0x1, 0x80)); // VB -> SRV + + // Enhanced texture barriers: RTV -> SRV narrows to a deduplicated stage-scoped global + // barrier (never dropped), pure read -> read is skipped, and UAV -> UAV targets the texture. + let tex_rt_to_srv = [ + TitleTextureBarrier { + sync_before: 0x40, // RENDER_TARGET + sync_after: 0x10, // PIXEL_SHADING + access_before: 0x8, // RENDER_TARGET + access_after: 0x80, // SHADER_RESOURCE + layout_before: 4, + layout_after: 5, + resource: std::ptr::null(), + subresources: [0; 6], + flags: 0, + }, + TitleTextureBarrier { + sync_before: 0x40, + sync_after: 0x10, + access_before: 0x8, + access_after: 0x80, + layout_before: 4, + layout_after: 5, + resource: std::ptr::null(), + subresources: [0; 6], + flags: 0, + }, + ]; + let group = TitleBarrierGroup { + kind: 1, + num: 2, + ptr: tex_rt_to_srv.as_ptr().cast(), + }; + match pack_barrier_groups(1, (&raw const group).cast()) { + PackedGroups::Narrow(items) => { + assert_eq!(items.len(), 1); + assert_eq!(items[0].kind, 0); + assert_eq!(items[0].sync_before, 0x40); + assert_eq!(items[0].sync_after, 0x10); + } + _ => panic!("expected deduplicated scoped global barrier for RTV -> SRV"), + } + + let tex_read_to_read = TitleTextureBarrier { + sync_before: 0x10, // PIXEL_SHADING + sync_after: 0x200, // COPY + access_before: 0x80, // SHADER_RESOURCE + access_after: 0x800, // COPY_SOURCE + layout_before: 5, + layout_after: 6, resource: std::ptr::null(), subresources: [0; 6], flags: 0, @@ -3284,12 +3471,37 @@ mod tests { let group = TitleBarrierGroup { kind: 1, num: 1, - ptr: (&raw const tex_rt_to_srv).cast(), + ptr: (&raw const tex_read_to_read).cast(), }; assert!(matches!(pack_barrier_groups(1, (&raw const group).cast()), PackedGroups::Skip)); - // Enhanced buffer UAV -> indirect barrier narrows to one CompactBarrier. let fake_res = 0x1234usize as This; + let tex_uav_to_uav = TitleTextureBarrier { + sync_before: 0x80, // COMPUTE_SHADING + sync_after: 0x80, // COMPUTE_SHADING + access_before: 0x10, // UNORDERED_ACCESS + access_after: 0x10, // UNORDERED_ACCESS + layout_before: 7, + layout_after: 7, + resource: fake_res, + subresources: [0; 6], + flags: 0, + }; + let group = TitleBarrierGroup { + kind: 1, + num: 1, + ptr: (&raw const tex_uav_to_uav).cast(), + }; + match pack_barrier_groups(1, (&raw const group).cast()) { + PackedGroups::Narrow(items) => { + assert_eq!(items.len(), 1); + assert_eq!(items[0].kind, 1); + assert_eq!(items[0].resource, fake_res); + } + _ => panic!("expected targeted texture UAV barrier"), + } + + // Enhanced buffer UAV -> indirect barrier narrows to one CompactBarrier. let buf_uav = TitleBufferBarrier { sync_before: 0x80, // COMPUTE_SHADING sync_after: 0x800, // EXECUTE_INDIRECT diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs index fd753086d8..ed40995b7e 100644 --- a/crates/victory-gpu/src/list/thin.rs +++ b/crates/victory-gpu/src/list/thin.rs @@ -730,10 +730,12 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> 0 } extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { - if count > 0 && crate::host::place::narrow_barriers() { + if count > 0 && crate::host::place::narrow_groups() { match super::pack_barrier_groups(count, groups) { super::PackedGroups::Skip => { crate::host::place::NARROW_STATS[1].fetch_add(1, Relaxed); + // Keep a zero-item marker so replay still invokes `state.synced()`. + front(this).put(BARRIER_GROUPS, &[1u64 << 63]); return; } super::PackedGroups::Narrow(items) => { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 215be62bf4..468ed878b9 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -5682,6 +5682,42 @@ pub(crate) fn peek(address: u64, len: u64) -> Option> { buffers_read().range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end).and_then(|(_, e)| e.shadow.clone()) } +/// All live host copies (title buffer shadows and loose windows) whose title +/// address range overlaps `[address, address + len)`. +pub(crate) fn peek_overlapping(address: u64, len: u64) -> Vec> { + let Some(end) = address.checked_add(len.max(1)) else { + return Vec::new(); + }; + let mut out = Vec::new(); + { + let map = buffers_read(); + for (_, entry) in map.range((address, 0)..(end, 0)) { + if let Some(shadow) = &entry.shadow { + out.push(shadow.clone()); + } + } + for (_, entry) in map.range(..(address, 0)).rev().take(64) { + if entry.end > address + && let Some(shadow) = &entry.shadow + { + out.push(shadow.clone()); + } + } + } + { + let map = LOOSE.read().unwrap_or_else(|e| e.into_inner()); + for (_, shadow) in map.range((address, 0)..(end, 0)) { + out.push(shadow.clone()); + } + for (&(start, bytes), shadow) in map.range(..(address, 0)).rev().take(32) { + if start.saturating_add(bytes) > address { + out.push(shadow.clone()); + } + } + } + out +} + fn lookup(address: u64, len: u64, any: bool) -> Option> { let quick = quick_find(); if quick && let Some(shadow) = found(address, len) {