diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index ccc7b4013b..ea80d32370 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -421,6 +421,27 @@ impl State { } } + /// The bytes root view `slot` holds from its start, as [`root_view`] + /// binds it. Shaders check their accesses against it: a root view has + /// no bounds on the host, and an access past the memory it maps is a + /// GPU page fault, which some hosts stall on until the driver resets + /// the device. 0 for a root view the title did not set. + fn root_view_bytes(&self, compute: bool, slot: u8, kind: RootView) -> u32 { + let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { + return 0; + }; + if address == 0 { + return 0; + } + let Some(shadow) = crate::shadow::find(address, 1) else { + return 0; + }; + if kind != RootView::Cbv && !shadow.gpu(address).is_multiple_of(4) { + return 0; + } + root_len(shadow.left(address), kind) as u32 + } + /// The bound heap holding `handle`. fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> { self.heaps @@ -564,6 +585,16 @@ impl State { .find(|m| m.0 == u.slot && u.root == RootType::Table); values[u.index as usize] = match fresh { Some(&(_, offset)) => offset, + None if u.root == RootType::Descriptor => { + let kind = if stage.root_uavs.iter().any(|r| r.0 == u.slot) { + RootView::Uav + } else if stage.root_srvs.iter().any(|r| r.0 == u.slot) { + RootView::Srv + } else { + RootView::Cbv + }; + self.root_view_bytes(compute, u.slot, kind) + } None => self.user_value(compute, u.slot, u.root, u.dword), }; } @@ -1641,6 +1672,138 @@ mod tests { (shader, used) } + fn build_structured_root_uav_cs() -> (victory_shader::emit::HostShader, Vec) { + let s_mov_b32 = + |dst: u8, src: u8| 0xBE80_0000 | u32::from(dst) << 16 | 0x03 << 8 | u32::from(src); + let vop1 = |op: u16, dst: u8, src: u16| { + 0x7e00_0000 | u32::from(dst) << 17 | u32::from(op) << 9 | u32::from(src) + }; + const S_ENDPGM: u32 = 0xbf81_0000; + const STRIDE: u32 = 8; + // MUBUF `op vdata, vaddr(index), s[srsrc:srsrc+3], 0 idxen offset:off`. + let mubuf_idxen = |op: u32, vdata: u8, vaddr: u8, srsrc: u8, off: u16| -> [u32; 2] { + [ + 0x38 << 26 | op << 18 | 1 << 13 | (off as u32 & 0xFFF), + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] + }; + const STORE: u32 = 0x1C; // buffer_store_dword + const LOAD: u32 = 0x0C; // buffer_load_dword + const ATOMIC_ADD: u32 = 0x32; // buffer_atomic_add (no return) + + let mut words = vec![ + // A buffer descriptor around the root UAV s[0:1] in s[8:11]. + s_mov_b32(8, 0), + s_mov_b32(9, 1), + s_mov_b32(10, 0xC1), // -1 records + s_mov_b32(11, 0xFF), + 0x3101_4FAC, + vop1(0x001, 1, 128 + 2), // v1 = 2 (index) + vop1(0x001, 2, 0xFF), // v2 = 0xABCD + 0x0000_ABCD, + vop1(0x001, 3, 128 + 5), // v3 = 5 + vop1(0x001, 5, 128), // v5 = 0 (index) + ]; + // Element 2: dword 5 = 0xABCD, dword 4 += 5; then element 0, dword 0 = + // what element 2 byte 4 holds. + words.extend(mubuf_idxen(STORE, 2, 1, 8, 4)); + words.extend(mubuf_idxen(ATOMIC_ADD, 3, 1, 8, 0)); + words.extend(mubuf_idxen(LOAD, 4, 1, 8, 4)); + words.extend(mubuf_idxen(STORE, 4, 5, 8, 0)); + words.push(S_ENDPGM); + + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![RootParam { + root: RootType::Descriptor, + table_offset_dwords: 0, + sgprs: 2, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Descriptor, + table_offset_dwords: 0, + lower_bound: 0, + stride: STRIDE, + dwords: 2, + user_data: 0, + slot: 0, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [1, 1, 1], + }), + code, + }; + let p = victory_shader::ir::build(&native.code, false, native.vgprs).unwrap(); + let res = victory_shader::resource::track(&p, &native.layout, native.stage).unwrap(); + let io = victory_shader::io::raise(&p, &native).unwrap(); + let st = victory_shader::structure::structure(&p).unwrap(); + let c = Container { + digest: [0; 16], + version: (1, 0), + parts: Vec::new(), + }; + let shader = victory_shader::emit::emit(&c, &native, &p, &st, &io, &res).unwrap(); + (shader, native.used) + } + + #[test] + fn dispatch_binds_the_remaining_bytes_of_an_interior_structured_root_uav() { + const OFFSET: usize = 8; + const PREFIX: [u32; 2] = [0x1234_5678, 0x1020_3040]; + let Some(host) = crate::host::host() else { + eprintln!("no D3D12 adapter; interior root UAV control skipped"); + return; + }; + let (shader, used) = build_structured_root_uav_cs(); + let pso = crate::pipeline::test_compute_pipeline(shader, used); + for (bytes, want) in [ + (24, [0xABCD, 0, 0, 0, 5, 0xABCD]), + (20, [0, 0, 0, 0, 5, 0]), + (16, [0; 6]), + ] { + // Both guest memory and the host's rounded backing cover the + // addresses read by the fixture. Register only the logical range. + let mut guest = Box::new([0u32; 8]); + guest[..2].copy_from_slice(&PREFIX); + let base = guest.as_mut_ptr() as u64; + let root = base + OFFSET as u64; + crate::shadow::register(base as usize, base, OFFSET as u64 + bytes); + let shadow = crate::shadow::find(base, 1).unwrap(); + let padding: Vec<_> = ((OFFSET + bytes as usize)..32) + .step_by(4) + .map(|at| (at, shadow.read_backing_u32(at))) + .collect(); + + let list = host.new_list().expect("new_list"); + let mut state = State::default(); + state.set_pipeline(pso); + state.set_view(true, 0, root); + assert_eq!(state.root_view_bytes(true, 0, RootView::Uav), bytes as u32); + state.dispatch(&list, 1, 1, 1); + list.close(); + host.execute(&[&list]); + + assert_eq!(guest[..2], PREFIX, "interior root overwrote prefix"); + assert_eq!(guest[2..], want, "guest after registered extent {bytes}"); + for (at, word) in padding { + assert_eq!(shadow.read_backing_u32(at), word, "write into physical padding at {at}"); + } + eprintln!("State::dispatch extent {bytes}: {guest:08x?}"); + crate::shadow::unregister(base as usize, base); + } + let release = crate::object::slot:: u32>(pso, 0x10); + assert_eq!(release(pso), 0); + eprintln!("registered interior structured root UAV readback completed"); + } + #[test] fn null_and_unmapped_root_views_use_safe_distinct_fallbacks() { assert!(crate::shadow::find(0, 1).is_none()); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index a2daaef5f8..8f1c193044 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -106,6 +106,15 @@ impl Shadow { unsafe { self.data.add(offset).cast::().read_unaligned() } } + #[cfg(test)] + pub(crate) fn read_backing_u32(&self, offset: usize) -> u32 { + // SAFETY: the live backing buffer can exceed the registered extent. + let width = unsafe { self.buffer.GetDesc() }.Width; + assert!((offset + 4) as u64 <= width); + // SAFETY: the read fits the physical mapping. + unsafe { self.data.add(offset).cast::().read_unaligned() } + } + /// Brings `len` bytes at `address` up to date when `list` is submitted, /// and keeps the copy alive until the list is reset. pub(crate) fn refresh(self: &Arc, list: &HostList, address: u64, len: u64) { diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index fdc02aa119..633a4f5075 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -706,6 +706,9 @@ fn user_data(s: &HostShader, k: &[u32; 4]) -> Vec { (RootType::Table, 3) => 5 * 32, // The typed views of `raw` (compute) from 9. (RootType::Table, 6) => 9 * 32, + // The bytes of the root CBV (slot 4) and SRV (slot 5) bound. + (RootType::Descriptor, 4) => 64 * 4, + (RootType::Descriptor, 5) => 32 * 4, other => panic!("unexpected user data {other:?}"), }; } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c79c33c092..6121675083 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -156,6 +156,8 @@ struct Lower<'a> { params: HashMap, user_data: Option, user_reads: BTreeMap, + /// Bytes each root view holds, by root parameter (see [`Self::root_view_size`]). + root_sizes: HashMap, samplers: Vec<[u32; 4]>, descriptors: HashMap<(Site, bool), &'a Source>, scalar: HashMap, @@ -458,6 +460,7 @@ impl<'a> Lower<'a> { params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), user_data: None, user_reads: BTreeMap::new(), + root_sizes: HashMap::new(), samplers: Vec::new(), descriptors: x .res @@ -604,6 +607,9 @@ impl<'a> Lower<'a> { words: [0, 0], }; let h = self.handle((b, i), &src, false, (11 | 0x1000, 0))?; + let root_ok = self.root_view_size(&src) + .map(|size| self.in_root_view(size, off, 4 * n).0); + let guard = self.narrow(guard, root_ok); let iu = self.s.m.undef(self.s.t.i32); let mut args = vec![h, off, iu]; args.extend(&vals); @@ -669,6 +675,27 @@ impl<'a> Lower<'a> { }; Some(self.handle((b, i), &src, false, (11 | u, 0))?) }; + // Root views: the dwords read checked against the view's size. + let root = if a.param == CODE { + None + } else { + self.root_view_size(&Source::Built { + address: a, + bits: 0, + words: [0, 0], + }) + }; + let (off, ok) = match root { + Some(size) => { + let bytes = if sub.is_some() { 4 } else { 4 * n }; + let not3 = self.s.m.i32(!3); + let at = self.s.m.bin(c, Bin::And, off, not3); + let (ok, _) = self.in_root_view(size, at, bytes); + let zero = self.s.m.i32(0); + (self.s.m.select(c, ok, off, zero), Some(ok)) + } + None => (off, None), + }; let dword = |l: &mut Self, byte: V| -> Result { match h { None => l.code_dword(byte), @@ -688,6 +715,10 @@ impl<'a> Lower<'a> { } } }; + let at = self.begin_guarded(ok); + let c = self.cur; + let zero = self.s.m.i32(0); + let mut values = Vec::with_capacity(n as usize); for k in 0..n { let x = match sub { None => { @@ -710,6 +741,9 @@ impl<'a> Lower<'a> { .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left) } }; + values.push((x, zero)); + } + for (k, x) in self.end_guarded(at, &values).into_iter().enumerate() { self.write(inst, Reg::V(reg + k as u8), x, guard); } Ok(()) @@ -1221,6 +1255,93 @@ impl<'a> Lower<'a> { Val::I32(self.s.m.extract(entry, r, index % 4)) } + /// For a root view (a root CBV, SRV or UAV), the bytes the host's view + /// holds from its start, which the host passes in the user-data dword of + /// the view's address. A root view has no bounds on the host: an access + /// past what the host mapped (an offset from data the host has not + /// mirrored) is a GPU page fault, which some hosts' GPUs stall on until + /// the driver resets the device. Accesses are checked against this size + /// as the console's bounded buffer views are. + fn root_view_size(&mut self, src: &Source) -> Option { + let Source::Built { address, .. } = src else { + return None; + }; + if address.param == CODE { + return None; + } + let rp = *self.x.native.layout.get(address.param)?; + if rp.root != RootType::Descriptor { + return None; + } + if let Some(&v) = self.root_sizes.get(&address.param) { + return Some(v); + } + let index = u32::from(rp.user_data); + self.user_reads.insert( + index, + UserData { + index, + slot: rp.slot, + root: RootType::Descriptor, + dword: 0, + }, + ); + self.s.user_data = self.s.user_data.max(index + 1); + let h = match self.user_data { + Some(h) => h, + None => { + let h = self.s.user_data_handle(); + self.user_data = Some(h); + h + } + }; + let entry = self.s.entry; + let row = self.s.m.i32(index / 4); + let r = self.s.op( + entry, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[h, row], + ); + let v = self.s.m.extract(entry, r, index % 4); + self.root_sizes.insert(address.param, v); + Some(v) + } + + /// Whether `bytes` bytes at byte `off` lie in a root view of `size` + /// bytes, and the offset to access instead (0 when they do not). + fn in_root_view(&mut self, size: V, off: V, bytes: u32) -> (V, V) { + let c = self.cur; + let below = self.s.m.cmp(c, pred::IULT, off, size); + let left = self.s.m.bin(c, Bin::Sub, size, off); + let n = self.s.m.i32(bytes); + let fits = self.s.m.cmp(c, pred::IUGE, left, n); + let ok = self.s.m.bin(c, Bin::And, below, fits); + let zero = self.s.m.i32(0); + (ok, self.s.m.select(c, ok, off, zero)) + } + + /// `guard` (lanes that run an access) narrowed to `ok`. + fn narrow(&mut self, guard: Option, ok: Option) -> Option { + match (guard, ok) { + (Some(g), Some(k)) => Some(self.s.m.bin(self.cur, Bin::And, g, k)), + (g, k) => g.or(k), + } + } + + /// `x` where `ok` holds, else 0 (`ok` none: always `x`). + fn zero_unless(&mut self, ok: Option, x: V) -> V { + match ok { + Some(k) => { + let zero = self.s.m.i32(0); + self.s.m.select(self.cur, k, x, zero) + } + None => x, + } + } + /// A dword of a lane mask as a number: the ballot of the lanes' bits, /// taken in the block that writes the mask (see [`MaskData`]). fn mask_dword(&mut self, v: Value) -> Result { @@ -2851,6 +2972,7 @@ impl<'a> Lower<'a> { (src, addr, (!has_soff && extra.is_none()).then_some(off)) }; let kind = self.used_kind(src); + let size = self.root_view_size(src); if matches!(src, Source::Built { address, .. } if address.param == CODE) { // A descriptor built around a table in the code. for k in 0..count { @@ -2874,6 +2996,13 @@ impl<'a> Lower<'a> { for k in 0..count { let off = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, addr, off); + let (a, ok) = match size { + Some(size) => { + let (ok, a) = self.in_root_view(size, a, 4); + (a, Some(ok)) + } + None => (a, None), + }; let mask = self.s.m.i8(1); let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); let r = self.s.op( @@ -2886,6 +3015,7 @@ impl<'a> Lower<'a> { ); let x = self.s.m.extract(c, r, 0); let x = self.as_int(x); + let x = self.zero_unless(ok, x); self.write(inst, Reg::S(code + k as u8), x, None); } return Ok(()); @@ -2917,7 +3047,14 @@ impl<'a> Lower<'a> { None => { let off = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, addr, off); - self.cbuffer_dword(h, a) + match size { + Some(size) => { + let (ok, a) = self.in_root_view(size, a, 4); + let x = self.cbuffer_dword(h, a); + self.zero_unless(Some(ok), x) + } + None => self.cbuffer_dword(h, a), + } } }; self.write(inst, Reg::S(code + k as u8), x, None); @@ -3263,22 +3400,7 @@ impl<'a> Lower<'a> { } } - /// Whether `src` is a descriptor built around a root SRV's or UAV's - /// address. - fn on_root_descriptor(&self, src: &Source) -> bool { - matches!(src, Source::Built { address, .. } - if self - .x - .native - .layout - .get(address.param) - .is_some_and(|rp| rp.root == RootType::Descriptor)) - } - - /// The handle and the two coordinates of a structured access to element - /// `index`, byte `off` of it: a structured buffer view, or, for a root - /// descriptor (a bare address on the host, with no stride of its own), - /// its raw view at byte `index * stride + off`. + /// The handle and coordinates of a structured access to a heap view. fn structured( &mut self, site: Site, @@ -3287,14 +3409,6 @@ impl<'a> Lower<'a> { stride: u32, (index, off): (V, V), ) -> Result<(V, V, V), Why> { - if self.on_root_descriptor(src) && stride > 0 { - let c = self.cur; - let s = self.s.m.i32(stride); - let at = self.s.m.bin(c, Bin::Mul, index, s); - let at = self.s.m.bin(c, Bin::Add, at, off); - let h = self.handle(site, src, false, (11 | u, 0))?; - return Ok((h, at, self.s.m.undef(self.s.t.i32))); - } if stride < 4 || !stride.is_multiple_of(4) { return Err("a structured buffer of unknown stride"); } @@ -6145,10 +6259,19 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = *data else { return Err("a buffer result"); }; + let size = self.root_view_size(src); for k in 0..count { let four = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, byte, four); + let (a, ok) = match size { + Some(size) => { + let (ok, a) = self.in_root_view(size, a, 4); + (a, Some(ok)) + } + None => (a, None), + }; let x = self.cbuffer_dword(h, a); + let x = self.zero_unless(ok, x); self.write(inst, Reg::V(reg + k as u8), x, guard); } return Ok(()); @@ -6156,6 +6279,34 @@ impl<'a> Lower<'a> { let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav); let u = if uav { 0x1000 } else { 0 }; let iu = self.s.m.undef(self.s.t.i32); + // Root views: the bytes accessed checked against the view's size + // (raw accesses, and the raw loads formatted ones make). + let (off, index, root_ok) = match self.root_view_size(src) { + Some(size) if !typed || format.is_some() => { + let bytes = if format.is_some() { 16 } else { 4 * count }; + let (off, index, no_wrap) = match index { + Some(index) if format.is_none() => { + let stride = used.map_or(0, |u| u.stride); + if stride == 0 { + return Err("a structured buffer of unknown stride"); + } + let stride = self.s.m.i32(stride); + let max = self.s.m.i32(u32::MAX); + let left = self.s.m.bin(c, Bin::Sub, max, off); + let max_index = self.s.m.bin(c, Bin::UDiv, left, stride); + let no_wrap = self.s.m.cmp(c, pred::IULE, index, max_index); + let element = self.s.m.bin(c, Bin::Mul, index, stride); + (self.s.m.bin(c, Bin::Add, element, off), None, Some(no_wrap)) + } + _ => (off, index, None), + }; + let (ok, _) = self.in_root_view(size, off, bytes); + let ok = self.narrow(Some(ok), no_wrap).expect("root access bound"); + let zero = self.s.m.i32(0); + (self.s.m.select(c, ok, off, zero), index, Some(ok)) + } + _ => (off, index, None), + }; if let Some(op) = atomic { let d = data.as_ref().ok_or("buffer atomic data")?; let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?; @@ -6175,7 +6326,8 @@ impl<'a> Lower<'a> { Some(v) if returns => self.i32_of(v)?, _ => self.s.m.i32(0), }; - let at = self.begin_guarded(guard); + let access = self.narrow(guard, root_ok); + let at = self.begin_guarded(access); let i32t = self.s.t.i32; let r = if op == u32::MAX { // cmpswap: data is (new, compare). @@ -6258,7 +6410,8 @@ impl<'a> Lower<'a> { if !typed { args.push(self.s.m.i32(4)); } - let at = self.begin_guarded(guard); + let access = self.narrow(guard, root_ok); + let at = self.begin_guarded(access); let void = self.s.t.void; self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args); self.end_guarded(at, &[]); @@ -6272,11 +6425,19 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = *data else { return Err("a buffer result"); }; - for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() { + let at = self.begin_guarded(root_ok); + let zero = self.s.m.i32(0); + let loaded = self.format_load(h, off, f, count)?; + let values: Vec<_> = loaded.into_iter().map(|x| (x, zero)).collect(); + for (k, x) in self.end_guarded(at, &values).into_iter().enumerate() { self.write(inst, Reg::V(reg + k as u8), x, guard); } return Ok(()); } + // An invalid read must issue no transaction. Redirecting it to + // byte zero still accesses memory if the view is shorter than a read. + let at = self.begin_guarded(root_ok); + let c = self.cur; let r = if typed { if *offen || matches!(off, V::Inst(_)) || *offset != 0 { return Err("a typed buffer load at an offset"); @@ -6326,6 +6487,10 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = *data else { return Err("a buffer result"); }; + let zero = self.s.m.f32(0); + let loaded: Vec<_> = (0..count).map(|k| (self.s.m.extract(c, r, k), zero)).collect(); + let values = self.end_guarded(at, &loaded); + let c = self.cur; if d16 { // Two f16 channels per VGPR (an odd last high half 0). let k16 = self.s.m.i32(16); @@ -6333,7 +6498,7 @@ impl<'a> Lower<'a> { for k in 0..count.div_ceil(2) { let mut x = None; for ch in (2 * k..(2 * k + 2).min(count)).rev() { - let f = self.s.m.extract(c, r, ch); + let f = values[ch as usize]; let h = self .s .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); @@ -6349,9 +6514,8 @@ impl<'a> Lower<'a> { } return Ok(()); } - for k in 0..count { - let x = self.s.m.extract(c, r, k); - let x = self.as_int(x); + for (k, value) in values.into_iter().enumerate() { + let x = self.as_int(value); self.write(inst, Reg::V(reg + k as u8), x, guard); } Ok(()) diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 8e6aaf3066..723dcd595b 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -833,7 +833,7 @@ fn root_uav_validates_and_dispatches_on_gpu_and_warp() { &pso, &Dispatch { roots: vec![ - (0, Root::Constants(vec![0; 4])), + (0, Root::Constants(vec![16, 0, 16, 0, 16])), ( 1, Root::View { @@ -1071,23 +1071,183 @@ fn structured_access_through_a_root_uav_reaches_index_times_stride() { let (root, pso) = host .compute_pipeline(&shader) .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); - let out = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![(0, Root::Constants(vec![0; 4])), (1, Root::Uav(8))], - views: &[], - samplers: &[], - groups: [1, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - assert_eq!( - &out[0][..8], - &[0xABCD, 0, 0, 0, 5, 0xABCD, 0, 0], - "{label}: element 2 is bytes 16..24 of the buffer" - ); + for (bytes, want) in [ + (24, [0xABCD, 0, 0, 0, 5, 0xABCD, 0, 0]), + (20, [0, 0, 0, 0, 5, 0, 0, 0]), + (16, [0; 8]), + ] { + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(vec![bytes, 0, 0, 0])), + (1, Root::Uav(8)), + ], + views: &[], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!( + &out[0][..8], &want, + "{label}: element 2 is bytes 16..24, bound {bytes}" + ); + } + ran += 1; + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); +} + +/// MUBUF `buffer_load_dword vdata, vaddr, s[srsrc:srsrc+3], 0 offen`. +const fn buffer_load_dword_offen(vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { + [ + 0x38 << 26 | 0x0C << 18 | 1 << 12, + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] +} + +/// A root SRV has no bounds on the host: a read past what the host bound +/// reads 0, as a console buffer view past its records does, instead of +/// memory after it (or an unmapped page, which some GPUs stall on). +#[test] +fn root_view_reads_stop_at_the_bound_size() { + // s0..s3 root constants, s4 the UAV table, s[8:9] the root SRV's address. + let mut words = vec![s_mov_b32(5, 0x80)]; + words.extend_from_slice(&s_load_dwordx4(12, 4)); + // The buffer descriptor built around the root address: all records. + words.push(s_mov_b32(10, 0xC1)); + words.push(s_mov_b32(11, 0x80)); + words.push(vop1(0x001, 1, sgpr(0))); // v_mov_b32 v1, s0: the byte offset + words.extend_from_slice(&buffer_load_dword_offen(0, 1, 8)); + words.extend_from_slice(&buffer_store_dword(0, 12, 0)); + words.push(S_ENDPGM); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let root = |root, sgprs, user_data, slot| RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + }; + let used = |kind, root, user_data, slot| UsedResource { + kind, + root, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data, + slot, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + root(RootType::Constants, 4, 0, 0), + root(RootType::Table, 1, 4, 1), + root(RootType::Descriptor, 2, 8, 2), + ], + used: vec![ + used(ResourceType::Uav, RootType::Table, 4, 1), + used(ResourceType::Srv, RootType::Descriptor, 8, 2), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 10 << 1, // 10 user SGPRs: s0..s9 + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let res = resource::track(&p, &native.layout, native.stage).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let st = structure::structure(&p).expect("structure"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + }; + assert_eq!(shader.root_srvs, [2]); + assert!( + shader + .user_data + .iter() + .any(|u| u.root == RootType::Descriptor && u.slot == 2 && u.index == 8), + "the root view's size is user data: {:?}", + shader.user_data + ); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + // 64 dwords bound, of which the host says 16 (64 bytes) are the view's. + let data: Vec = (0..64).map(|i| 0x100 + i).collect(); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host.compute_pipeline(&shader).expect("pipeline"); + for (offset, want) in [ + (0, 0x100), + (60, 0x10F), + (64, 0), + (128, 0), + (u32::MAX - 3, 0), + ] { + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match u.root { + RootType::Constants => offset, + RootType::Descriptor => 64, + _ => 0, + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + ( + 1, + Root::View { + srv: true, + data: data.clone(), + }, + ), + ], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: {e}")); + assert_eq!(out[0][0], want, "{label}: offset {offset:#x}"); + } ran += 1; } assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available");