diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 2a703a48..9c4812d3 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -83,6 +83,9 @@ pub(crate) struct HostHeap { step: u32, /// Slots mirroring the title's; view heaps have `dynamic` more. count: u32, + /// The first dynamic slot: the title's slots, then unused ones up to + /// this, then the dynamic range (see [`view_layout`]). + base: u32, /// Dynamic slots past `count`: [`DYNAMIC`] in view heaps, none in /// sampler heaps. (Upstream falls back to 2^16 on a capped host heap; /// ours keeps 2^18 there: 2^16 and 2^17 both ran out in this title.) @@ -674,6 +677,37 @@ pub(crate) fn probe_view_limit() { /// table past them is made afresh in these slots like any other. pub(crate) const DYNAMIC: u32 = 1 << 18; +/// The title slots a view heap that the title asked `requested` slots of has +/// room for, the first dynamic slot, and the heap's size; `null` is the last +/// slot of the heap, which shaders clamp view indices to (0: no host limit +/// probed). +/// +/// The dynamic slots sit a fixed distance below the null slot, not right +/// after the title's: shaders are translated before the title makes its heap +/// and clamp the view slots the title made itself below them +/// (`victory_shader`'s `title_view_limit`), so a title heap larger than the +/// room left must not put the title's slots where the dynamic ones are. +/// Upstream PR #2628 (moe-miau) for the same layout. +fn view_layout(requested: u32, null: u32, dynamic: u32) -> (u32, u32, u32) { + view_layout_with(requested, null, dynamic, victory_shader::emit::title_view_clamp()) +} + +/// [`view_layout`], with the dynamic slots the heap keeps (`dynamic`: none in +/// sampler heaps) and the title clamp's switch given. +fn view_layout_with(requested: u32, null: u32, dynamic: u32, clamp: bool) -> (u32, u32, u32) { + if null == 0 || dynamic == 0 { + return (requested, requested, requested + dynamic); + } + let size = null + 1; + let base = null.saturating_sub(dynamic); + if !clamp { + // Switched off: the dynamic slots follow the title's, as before. + let fitted = if requested + dynamic <= null { requested } else { base }; + return (fitted, fitted, size); + } + (requested.min(base), base, size) +} + /// A slot the host made from a view narrowed to a part-resident texture's /// mips ([`narrow_to_resident`]): the texture, the window the title asked /// for and the one the host view names. @@ -722,30 +756,18 @@ impl HostHeap { } else { victory_shader::emit::view_heap_limit() }; - let (heap, count, size) = if null == 0 { - match make(count + extra) { - Ok(heap) => (heap, count, count + extra), - Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); - return None; - } - } - } else { - let size = null + 1; - let fitted = if count + extra <= null { - count - } else { - // shortcut: descriptors past the host's limit are left out; a title that reaches - // them needs remapping. They read the null slot instead. - tracing::warn!(count, "host view heap capped at {size}; views past it read a null slot"); - null - extra - }; - match make(size) { - Ok(heap) => (heap, fitted, size), - Err(e) => { - tracing::warn!(error = %e, count, size, "no host view heap"); - return None; - } + let requested = count; + let (count, base, size) = view_layout(requested, null, extra); + if null != 0 && count < requested { + // shortcut: descriptors past the host's limit are left out; a title that reaches + // them needs remapping. They read the null slot instead. + tracing::warn!(requested, count, size, "host view heap capped at {size}; views past it read a null slot"); + } + let heap = match make(size) { + Ok(heap) => heap, + Err(e) => { + tracing::warn!(error = %e, count, size, sampler, "no host descriptor heap"); + return None; } }; // SAFETY: a live heap. @@ -782,13 +804,14 @@ impl HostHeap { cpu, step, count, + base, dynamic: extra, sampler, made: Mutex::new(vec![0; count as usize]), made_fast: (0..count).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), narrowed: Mutex::default(), narrowed_count: std::sync::atomic::AtomicUsize::new(0), - kept: Mutex::new(vec![None; (count + extra) as usize]), + kept: Mutex::new(vec![None; size as usize]), next: Mutex::new((0, vec![false; DYNAMIC as usize])), free: std::sync::atomic::AtomicU32::new(DYNAMIC), too_long: std::sync::atomic::AtomicU32::new(u32::MAX), @@ -926,7 +949,7 @@ impl HostHeap { taken[first..first + n].fill(true); self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); *next = ((first + n) % DYNAMIC as usize) as u32; - Some(self.count + first as u32) + Some(self.base + first as u32) } /// The title slots this heap has host slots for; fewer than the title's @@ -1256,7 +1279,7 @@ impl HostHeap { /// /// [`dynamic`]: HostHeap::dynamic pub(crate) fn release(&self, first: u32, n: u32) { - let Some(at) = first.checked_sub(self.count) else { + let Some(at) = first.checked_sub(self.base) else { return; }; let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); @@ -2810,6 +2833,31 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + /// The host's dynamic slots sit below the null slot that shaders clamp + /// view indices to, never right after the title's, so an index the title + /// made itself past its slots cannot name one of them. The count shaders + /// assume is the GPU's `DYNAMIC`. + #[test] + fn dynamic_slots_sit_below_the_null_slot() { + assert_eq!(DYNAMIC, victory_shader::emit::DYNAMIC_VIEWS); + let limit = (1 << 21) - 1; + // A title heap that fits: its own slots stay, the dynamic ones below null. + assert_eq!(view_layout_with(1_245_184, limit, DYNAMIC, true), (1_245_184, limit - DYNAMIC, limit + 1)); + // A capped host (1,000,000 slots): the title's slots give way. + let portable = 1_000_000 - 1; + let (count, base, size) = view_layout_with(1_245_184, portable, DYNAMIC, true); + assert_eq!((count, base, size), (portable - DYNAMIC, portable - DYNAMIC, portable + 1)); + // A small title heap: the dynamic slots still lie below null. + assert_eq!(view_layout_with(100, limit, DYNAMIC, true), (100, limit - DYNAMIC, limit + 1)); + // No host heap probed: the dynamic slots follow the title's. + assert_eq!(view_layout_with(100, 0, DYNAMIC, true), (100, 100, 100 + DYNAMIC)); + // Switched off: as before, the dynamic slots follow the title's. + assert_eq!(view_layout_with(100, limit, DYNAMIC, false), (100, 100, limit + 1)); + // A sampler heap keeps none, whatever the host's view limit. + assert_eq!(view_layout_with(100, 0, 0, true), (100, 100, 100)); + assert_eq!(view_layout_with(100, limit, 0, true), (100, 100, 100)); + } + /// A subscriber that only counts the lines said: what a diagnostic's cost /// comes to offline. #[derive(Clone, Default)] @@ -3329,13 +3377,15 @@ mod tests { let Some(heap) = HostHeap::new(false, 4) else { return; // no host GPU }; + // The dynamic slots start at `base`, not right after the title's 4. + let base = heap.base; let a = heap.dynamic(heap.dynamic - 100).unwrap(); let b = heap.dynamic(60).unwrap(); - assert_eq!((a, b), (4, 4 + heap.dynamic - 100)); + assert_eq!((a, b), (base, base + heap.dynamic - 100)); // 40 left at the end: 50 do not fit until something is given back. assert_eq!(heap.dynamic(50), None); heap.release(a, 50); - assert_eq!(heap.dynamic(50), Some(4)); - assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); + assert_eq!(heap.dynamic(50), Some(base)); + assert_eq!(heap.dynamic(40), Some(base + heap.dynamic - 40)); } } diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index eff0ac08..1165f443 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -1047,6 +1047,47 @@ impl Writer { mod tests { use super::*; + /// A view slot the title made itself, on a host heap whose dynamic slots + /// follow the title's, reads the heap's null slot instead of one of the + /// host's tables (upstream PR #2628, moe-miau). + #[test] + fn title_view_indices_past_the_title_slots_read_the_null_slot() { + use crate::emit::DYNAMIC_VIEWS; + use crate::emit::shader::Shader; + + let mut s = Shader::new(false); + let index = s.m.undef(s.t.i32); + // No host heap probed: an index is left as the title made it. + assert_eq!(s.clamp_title_heap_index(s.entry, index), index); + // A heap of 1,000,000 slots (NVIDIA's cap): the title's slots, then + // the host's dynamic ones, then the null slot. + let limit = 1_000_000 - 1; + s.view_limit = limit; + let V::Inst(selected) = s.clamp_title_heap_index(s.entry, index) else { + panic!("a select") + }; + // A constant's value, as the module holds it. + fn value(m: &Module, v: V) -> i64 { + match v { + V::Const(i) => match m.consts[i as usize].1 { + Const::Int(x) => x, + _ => panic!("an integer constant"), + }, + _ => panic!("a constant"), + } + } + let Op::Select(over, t, f) = s.m.insts[selected as usize].op else { + panic!("a select") + }; + assert_eq!((value(&s.m, t), f), (i64::from(limit as i32), index)); + let V::Inst(over) = over else { panic!("a compare") }; + let Op::Cmp(pred, a, b) = s.m.insts[over as usize].op else { + panic!("a compare") + }; + assert_eq!((pred, a), (pred::IUGT, index)); + assert_eq!(value(&s.m, b), i64::from((limit - DYNAMIC_VIEWS - 1) as i32)); + } + #[test] fn vbr_and_blocks() { let mut w = Writer::default(); diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index c8c57109..32af5023 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -233,7 +233,7 @@ impl<'a> Lower<'a> { // which is zeros. let c = self.cur; let slot = self.s.m.i32(slot); - let handle = self.s.heap_handle(c, slot, false, false, (11, 0)); + let handle = self.s.heap_handle(c, slot, false, false, (11, 0), false); let (base_low, base_high) = (self.s.m.i32(base as u32), self.s.m.i32((base >> 32) as u32)); let at = self.s.m.bin(c, Bin::Sub, low, base_low); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index e095c929..ddd20ee0 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2946,7 +2946,7 @@ impl<'a> Lower<'a> { ); let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0); let slot = self.s.m.bin(c, Bin::Add, base, copy); - let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0)); + let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0), false); let k64k = k(self, 0xFFFF); let within = self.s.m.bin(c, Bin::And, lo, k64k); let byte = self.s.m.bin(c, Bin::Add, start, within); @@ -6543,6 +6543,12 @@ impl<'a> Lower<'a> { sampler: bool, props: (u32, u32), ) -> Result { + // An index the title made itself may not name a host slot. + let from_heap = !sampler && src.heap_only(|s| { + let (Source::Loaded { load, .. } | Source::Fetched { load, .. }) = s else { return false }; + self.scalar.get(load).and_then(|a| self.x.native.layout.get(a.param)) + .is_some_and(|p| p.root == RootType::ResourceHeap) + }); match src { Source::Loaded { load, first } => { let key = (self.cur, *load, *first, sampler, props); @@ -6555,7 +6561,7 @@ impl<'a> Lower<'a> { let per_lane = self.x.res.waterfall.loads.contains(load); let h = self .s - .heap_handle(self.cur, index, sampler, per_lane, props); + .heap_handle(self.cur, index, sampler, per_lane, props, from_heap); self.handles.insert(key, h); Ok(h) } @@ -6616,7 +6622,7 @@ impl<'a> Lower<'a> { Source::Phi { block, args } => { let _ = site; let phi = self.descriptor_phi(*block, args, sampler, 8)?; - Ok(self.s.heap_handle(self.cur, phi, sampler, false, props)) + Ok(self.s.heap_handle(self.cur, phi, sampler, false, props, from_heap)) } Source::Select { scc, args } => { // The heap index of each choice, picked by SCC (uniform). @@ -6634,14 +6640,14 @@ impl<'a> Lower<'a> { let set = self.heap_index(a, fa, sampler)?; let clear = self.heap_index(b, fb, sampler)?; let index = self.s.m.select(self.cur, cond, set, clear); - Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) + Ok(self.s.heap_handle(self.cur, index, sampler, false, props, from_heap)) } Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => { // A descriptor each lane has its own of (a waterfall loop // reads it from the first active lane): each lane's heap // index, non-uniform. let index = self.lane_heap_index(src, sampler)?; - Ok(self.s.heap_handle(self.cur, index, sampler, true, props)) + Ok(self.s.heap_handle(self.cur, index, sampler, true, props, from_heap)) } } } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 59d83e37..5f612c06 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -121,10 +121,16 @@ pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_GROUP_BASE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, - USER_VIEW_BIAS, - set_view_heap_limit, view_heap_limit, + USER_VIEW_BIAS, set_view_heap_limit, title_view_clamp, title_view_limit, view_heap_limit, }; +/// The host's dynamic slots in a view heap (`victory-gpu`'s `DYNAMIC`): tables +/// a draw needs made afresh are made there. They follow the title's slots, at +/// a place shaders know before the title's heap is made, so a shader that +/// names a view slot the title made itself is clamped below them +/// ([`title_view_limit`]) instead of naming one of the host's tables. +pub const DYNAMIC_VIEWS: u32 = 1 << 18; + /// The loop limit without an override: 2^20. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; @@ -274,6 +280,7 @@ pub const SWITCHES: &[&str] = &[ "VICTORY_SHADER_LOOP_LIMIT_CS", "VICTORY_SHADER_OPT", "VICTORY_STRICT_JOINS", + "VICTORY_TITLE_VIEW_CLAMP", "VICTORY_WAVE_DEEP_SKIPS", "VICTORY_WAVE_LOCAL", "VICTORY_WAVE_OWN_BITS", diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 0bd72197..a021cf70 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -137,10 +137,38 @@ pub fn view_heap_limit() -> u32 { VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed) } +/// Whether shaders clamp the view slots the title made itself below the +/// host's dynamic slots ([`title_view_limit`]). `VICTORY_TITLE_VIEW_CLAMP=0` +/// turns it off, and `victory-gpu` then keeps its dynamic slots right after +/// the title's, as before. +pub fn title_view_clamp() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TITLE_VIEW_CLAMP").is_none_or(|v| v != "0")) +} + +/// The slots a view index the title made itself may name: the host's view +/// heap less its dynamic slots ([`super::DYNAMIC_VIEWS`]), which follow the +/// title's. 0: no separate limit (no host heap probed, a heap with no room +/// for both, or the clamp is off). +pub fn title_view_limit() -> u32 { + if !title_view_clamp() { + return 0; + } + title_view_limit_of(view_heap_limit()) +} + +/// [`title_view_limit`] for a heap whose last slot is `limit`. +fn title_view_limit_of(limit: u32) -> u32 { + if limit > super::DYNAMIC_VIEWS + 1 { limit - super::DYNAMIC_VIEWS } else { 0 } +} + pub(crate) struct Shader { pub m: Module, pub t: Types, pub pixel: bool, + /// The last slot of the host's view heap when this shader is translated + /// ([`view_heap_limit`]; 0: none), which its view indices are clamped to. + pub view_limit: u32, pub inputs: Vec, pub outputs: Vec, /// A mesh shader's per-primitive outputs. @@ -207,6 +235,7 @@ impl Shader { res_ret, }, pixel, + view_limit: VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed), inputs: Vec::new(), outputs: Vec::new(), prims: Vec::new(), @@ -399,6 +428,25 @@ impl Shader { ) } + /// A view index the title made itself (every path to the descriptor is the + /// resource heap itself, not a table): on a host whose dynamic slots + /// follow the title's ([`title_view_limit`]), an index past the title's + /// slots reads the heap's null slot instead of naming one of the host's + /// tables. A table's index may name a dynamic slot and is not clamped + /// here, only at the heap's end ([`Self::heap_handle`]). + pub fn clamp_title_heap_index(&mut self, block: usize, index: V) -> V { + let limit = if title_view_clamp() { title_view_limit_of(self.view_limit) } else { 0 }; + if limit == 0 { + return index; + } + let last = self.m.i32(limit - 1); + let over = self.m.cmp(block, super::bitcode::pred::IUGT, index, last); + let null = self.m.i32(self.view_limit); + let v = self.m.select(block, over, null, index); + self.m.tag(v, super::bitcode::Tag::Clamp); + v + } + /// A descriptor heap handle, annotated with `props`; `nonuniform` when /// the index may differ between lanes (`NonUniformResourceIndex`). pub fn heap_handle( @@ -408,9 +456,12 @@ impl Shader { sampler: bool, nonuniform: bool, props: (u32, u32), + from_heap: bool, ) -> V { + // An index the title made itself (not a table's) may not name a host slot. + let index = if from_heap && !sampler { self.clamp_title_heap_index(block, index) } else { index }; // a view index past the host heap (`set_view_heap_limit`) reads its null slot instead - let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed); + let limit = self.view_limit; // (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid) let index = if !sampler && limit != 0 { let null = self.m.i32(limit); diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 9f1a8d97..691c6a3b 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -109,6 +109,13 @@ impl Source { s => vec![s], } } + + /// Whether every path to this descriptor reads the resource heap itself + /// (an index the title made, not a table), when `heap` says so of a leaf. + pub fn heap_only(&self, heap: impl Fn(&Self) -> bool) -> bool { + let l = self.leaves(); + !l.is_empty() && l.iter().all(|s| heap(s)) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)]