diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 39e8b68..d4edf99 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -333,17 +333,38 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { } } +/// Runs `f` with the host heap of the title's largest view heap, if there is +/// one (reports: nothing is waited for). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn with_view_heap(f: impl FnOnce(&host::HostHeap) -> T) -> Option { + let heaps = SHADER_HEAPS.try_read().ok()?; + let host = heaps + .iter() + // SAFETY: registered heaps are live (removed when dropped). + .map(|&(_, _, at)| unsafe { &*(at as *const Heap) }) + .filter(|heap| !heap.samplers()) + .filter_map(|heap| heap.host.get()?.as_ref()) + .max_by_key(|host| host.count())?; + Some(f(host)) +} + /// Makes dynamic slot `index` of the host heap behind the title heap at /// `heap`, if that heap still exists, the constant buffer view of `size` -/// bytes at `gpu`. +/// bytes of `buffer` at `gpu`. #[cfg(windows)] -pub(crate) fn constant_slot(heap: usize, index: u32, gpu: u64, size: u32) { +pub(crate) fn constant_slot( + heap: usize, + index: u32, + buffer: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, + gpu: u64, + size: u32, +) { let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); if heaps.iter().any(|&(_, _, h)| h == heap) // SAFETY: registered heaps are live (removed when dropped). && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() { - host.constant_at(index, gpu, size); + host.constant_at(index, buffer, gpu, size); } } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 5aac724..825a2a0 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -866,6 +866,20 @@ fn view_home( crate::shadow::exact(start, len).unwrap_or(shadow) } +/// For device-removed reports: what the slots of the title's view heap that +/// the words of user data may name hold now ([`crate::host::indirects`]). +#[cfg(feature = "diagnostics")] +pub(crate) fn describe_slots(words: &[u32]) -> Vec<(usize, u32, String)> { + super::with_view_heap(|host| { + crate::host::indirects::slots(words, host.count, 6) + .into_iter() + .take(24) + .map(|(word, slot)| (word, slot, host.describe_slot(slot).unwrap_or_default())) + .collect() + }) + .unwrap_or_default() +} + /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for /// device-removed reports: a shader indexing a heap past its end faults. static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); @@ -1859,6 +1873,11 @@ impl HostHeap { fn keep(&self, index: u32, resource: Option) { let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); if let Some(slot) = kept.get_mut(index as usize) { + use windows::core::Interface; + // The same again: nothing to retire. + if slot.as_ref().map(Interface::as_raw) == resource.as_ref().map(Interface::as_raw) { + return; + } // A running submission may still read the old resource through // this slot. if let Some(old) = std::mem::replace(slot, resource) { @@ -1937,7 +1956,6 @@ impl HostHeap { /// Makes slot `index` (a dynamic one) a raw unordered access view of /// nothing: reads give zeros, writes are dropped. pub(crate) fn null_raw_uav_at(&self, index: u32) { - self.keep(index, None); let Some(host) = host() else { return }; let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, @@ -1959,6 +1977,7 @@ impl HostHeap { self.cpu(index), ) }; + self.keep(index, None); } /// The shader-visible handle of slot `index`. @@ -1971,9 +1990,17 @@ impl HostHeap { } /// Makes slot `index` (a dynamic one) a constant buffer view of host - /// memory (the list's own, which it holds). - pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { - self.keep(index, None); + /// memory, `size` bytes at `gpu` of `buffer`, which the slot holds. + /// + /// The list holds it too, until it is reset; the slot shows it until it + /// is made again, and a shader that picks the slot by an index it + /// computes from wrong data reads it through there. The list's scratch + /// chunks go back to the pool and are freed past its limit: session n02 + /// lost the device to a page fault in the memory of three freed ones. + /// `VICTORY_SLOT_HOLDS=0`: only the list holds it, as before. + pub(crate) fn constant_at(&self, index: u32, buffer: &ID3D12Resource, gpu: u64, size: u32) { + static HOLDS: std::sync::OnceLock = std::sync::OnceLock::new(); + let holds = *HOLDS.get_or_init(|| std::env::var_os("VICTORY_SLOT_HOLDS").is_none_or(|v| v != "0")); let Some(host) = host() else { return }; let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, @@ -1984,6 +2011,9 @@ impl HostHeap { host.device .CreateConstantBufferView(Some(&desc), self.cpu(index)) }; + // After the descriptor: what it showed is let go when nothing shows + // it any more. + self.keep(index, holds.then(|| buffer.clone())); } fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { @@ -3297,7 +3327,7 @@ mod tests { assert!(alive(), "a view of {size} bytes"); } // SAFETY: a live upload buffer. - heap.constant_at(1, unsafe { buffer.GetGPUVirtualAddress() }, 969_472); + heap.constant_at(1, &buffer, unsafe { buffer.GetGPUVirtualAddress() }, 969_472); assert!(alive(), "a view of the list's own memory"); assert_eq!(constant_bytes(480), 512); assert_eq!(constant_bytes(64 << 10), 64 << 10); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2b6f8a0..7dccb4f 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -283,6 +283,10 @@ pub(crate) struct State { /// The records clamped in a batch, if later executions may still read /// them ([`batches`]). batch: Option, + /// The user data bound last, of the last stage that has some (for the + /// report of a removed device, `crate::host::indirects`). + #[cfg(feature = "diagnostics")] + user: Vec, /// What the host list has: pipeline, root signature, heaps. host_pipeline: usize, /// Graphics, compute. @@ -1246,6 +1250,11 @@ impl State { None => self.user_value(compute, u.slot, u.root, u.dword), }; } + #[cfg(feature = "diagnostics")] + { + self.user.clear(); + self.user.extend_from_slice(&values); + } // SAFETY: an open list; `values` covers the parameter. unsafe { if compute { @@ -2869,13 +2878,13 @@ impl State { let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k); match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { - let Some((gpu, to)) = list.scratch(u64::from(size)) else { + let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else { host.make_null(index); continue; }; let slot = (std::ptr::from_ref(heap) as usize, index); list.defer_constants(to, address as *const u8, size as usize, slot); - host.constant_at(index, gpu, size); + host.constant_at(index, &buffer, gpu, size); } Some(view) => { host.make_at(index, &view); @@ -3383,6 +3392,8 @@ impl State { list.note_op(|| { self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) }); + #[cfg(feature = "diagnostics")] + list.ran_indirect(p.pso.as_raw() as usize, &p.name, kind, max, &self.user); if kind == MESH { self.mesh_scissor(list, true); } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index e24be3b..20c3785 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -889,6 +889,9 @@ pub(crate) struct HostList { prelude: OnceLock>, /// The pipelines the list binds, for reports of slow submissions. pipelines: std::sync::Arc>>, + /// What its indirect executions ran, for the report of a removed device. + #[cfg(feature = "diagnostics")] + indirects: indirects::Shared, /// The work its indirect executions may still do (`indirect`): a /// shader-writable word, zeroed when the list is submitted, and after /// it what the clamp notes about mesh records. In memory the CPU maps. @@ -1404,7 +1407,14 @@ pub(crate) fn dred_faults() -> bool { #[cfg(feature = "diagnostics")] #[allow(clippy::type_complexity)] static LIST_NOTES: Mutex< - std::collections::BTreeMap>>, std::sync::Weak>>)>, + std::collections::BTreeMap< + u32, + ( + std::sync::Weak>>, + std::sync::Weak>>, + std::sync::Weak>, + ), + >, > = Mutex::new(std::collections::BTreeMap::new()); /// The number in the name of a list of ours ("victory host list 7", which the @@ -3155,6 +3165,7 @@ fn late_line(frames: f64) { } mod card_steps; +pub(crate) mod indirects; mod place; mod send; mod torn; @@ -3522,6 +3533,8 @@ impl Host { let notes = std::sync::Arc::>>::default(); let pipelines = std::sync::Arc::>>::default(); #[cfg(feature = "diagnostics")] + let indirects = indirects::Shared::default(); + #[cfg(feature = "diagnostics")] if dred_on() || dred_light() { static NUMBER: AtomicU32 = AtomicU32::new(0); let number = NUMBER.fetch_add(1, Ordering::Relaxed); @@ -3530,7 +3543,14 @@ impl Host { if number.is_multiple_of(256) { all.retain(|_, l| l.0.strong_count() > 0); } - all.insert(number, (std::sync::Arc::downgrade(¬es), std::sync::Arc::downgrade(&pipelines))); + all.insert( + number, + ( + std::sync::Arc::downgrade(¬es), + std::sync::Arc::downgrade(&pipelines), + std::sync::Arc::downgrade(&indirects), + ), + ); } Ok(HostList { allocator, @@ -3541,6 +3561,8 @@ impl Host { twins: Mutex::default(), prelude, pipelines, + #[cfg(feature = "diagnostics")] + indirects, budget: OnceLock::new(), card_budget: OnceLock::new(), indirect_args: Mutex::default(), @@ -5271,7 +5293,12 @@ impl Host { #[cfg(feature = "diagnostics")] let by_name = list_number(&named).and_then(|n| { let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()); - all.get(&n).map(|(notes, pipelines)| (notes.upgrade(), pipelines.upgrade())) + all.get(&n).map(|(notes, pipelines, _)| (notes.upgrade(), pipelines.upgrade())) + }); + #[cfg(feature = "diagnostics")] + let indirects = run.map(|r| r.indirects.clone()).or_else(|| { + let n = list_number(&named)?; + LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()).get(&n)?.2.upgrade() }); #[cfg(not(feature = "diagnostics"))] #[allow(clippy::type_complexity)] @@ -5301,6 +5328,10 @@ impl Host { if done > 0 { text.push_str(&in_flight(history, &markers, done as usize)); } + #[cfg(feature = "diagnostics")] + if let Some(indirects) = indirects { + text.push_str(&indirects_around(history, done as usize, &indirects)); + } // (Without markers a list that stopped midway says what // it may have been at only by what it binds.) if (done == 0 || markers.is_empty()) @@ -5498,6 +5529,8 @@ impl HostList { self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); #[cfg(feature = "diagnostics")] + self.indirects.lock().unwrap_or_else(|e| e.into_inner()).clear(); + #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); { let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); @@ -5904,6 +5937,15 @@ impl HostList { && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty() } + /// Notes an indirect execution, while device-removed data is kept + /// ([`indirects`]). + #[cfg(feature = "diagnostics")] + pub(crate) fn ran_indirect(&self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) { + if dred_on() || dred_light() { + self.indirects.lock().unwrap_or_else(|e| e.into_inner()).note(pipeline, name, kind, count, user); + } + } + /// Notes a pipeline the list binds. pub(crate) fn used_pipeline(&self, name: &str) { let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); @@ -6025,6 +6067,15 @@ impl HostList { Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data)) } + /// [`HostList::scratch`] and the buffer it lies in, for a descriptor + /// slot to hold: the slot outlives the list's use of it. + pub(crate) fn scratch_held(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> { + let (buffer, at, data) = self.scratch_at(len)?; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() } + at; + Some((buffer, gpu, data)) + } + /// [`HostList::scratch`]: the buffer, the offset in it and the CPU /// pointer. fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> { @@ -7977,6 +8028,34 @@ fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String { /// barriers overlaps on the GPU), by kind, and what the markers just /// before them say (`HostList::note_op`: diagnostics builds with /// device-removed data on). +/// For a list that stopped at command `done`: what the indirect executions +/// there ran, from the one before it to the next barrier (four at most), and +/// what the heap slots their user data names hold now. +#[cfg(feature = "diagnostics")] +fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &indirects::Shared) -> String { + let indirect = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT; + let all = all.lock().unwrap_or_else(|e| e.into_inner()); + let mut text = String::new(); + let mut shown = 0; + for (at, op) in history.iter().enumerate().skip(done.saturating_sub(1)) { + if shown == 4 || (at > done && *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER) { + break; + } + if !indirect(op) { + continue; + } + shown += 1; + let Some((what, words)) = all.nth(indirects::before(history, at, indirect)) else { + continue; + }; + text.push_str(&format!("; command {at} ran {what}")); + for (word, slot, what) in crate::descriptor::host::describe_slots(words) { + text.push_str(&format!(", word {word} slot {slot}: {what}")); + } + } + text +} + fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String { let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER; let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1); diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 881d1b2..84641cd 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -715,7 +715,7 @@ impl Host { To::Slot(heap, index) => { DONE[0].fetch_add(1, Ordering::Relaxed); // (A heap that is gone: nothing can read the slot.) - crate::descriptor::constant_slot(*heap, *index, gpu + op.at, op.len as u32); + crate::descriptor::constant_slot(*heap, *index, &own.between, gpu + op.at, op.len as u32); } To::Buffer(_) => { DONE[0].fetch_add(1, Ordering::Relaxed); diff --git a/crates/victory-gpu/src/host/indirects.rs b/crates/victory-gpu/src/host/indirects.rs new file mode 100644 index 0000000..cc34bff --- /dev/null +++ b/crates/victory-gpu/src/host/indirects.rs @@ -0,0 +1,127 @@ +//! What the indirect executions of a list ran, for the report of a removed +//! device: with `VICTORY_D3D12_DRED=light` the lists carry no markers, and +//! the two device losses of 2026-11-25 (sessions play-1125-0203 and n02) +//! said only that a list of 814 (954) commands stopped at an indirect +//! execution. The pipeline of each was found hours later by finding the +//! same run of commands in a capture. +//! +//! Per list, in the order recorded: the pipeline (by its host object, whose +//! name is kept once) and the first root constants (user data) it had. The +//! report finds an indirect execution by how many the breadcrumbs' history +//! has before it. Nothing is kept without device-removed data. +//! `VICTORY_D3D12_DRED=faults` and no data at all: nothing is noted. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +/// Words of user data kept of each execution. +pub(crate) const WORDS: usize = 16; + +/// One indirect execution. +#[derive(Clone, Copy)] +pub(crate) struct Ran { + pipeline: usize, + kind: u32, + count: u32, + words: [u32; WORDS], + used: u8, +} + +#[derive(Default)] +pub(crate) struct Indirects { + names: HashMap, + ran: Vec, +} + +/// A list's, shared with the report's table of lists. +pub(crate) type Shared = Arc>; + +impl Indirects { + /// An indirect execution of `kind` (the argument's type) of at most + /// `count` records with `pipeline` (a host object) and user data. + pub(crate) fn note(&mut self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) { + self.names.entry(pipeline).or_insert_with(|| name.to_owned()); + let used = user.len().min(WORDS); + let mut words = [0; WORDS]; + words[..used].copy_from_slice(&user[..used]); + self.ran.push(Ran { pipeline, kind, count, words, used: used as u8 }); + } + + pub(crate) fn clear(&mut self) { + self.ran.clear(); + if self.names.len() > 512 { + self.names.clear(); + } + } + + /// The `nth` execution (from 0): its text and its user data. + pub(crate) fn nth(&self, nth: usize) -> Option<(String, &[u32])> { + let ran = self.ran.get(nth)?; + let name = self.names.get(&ran.pipeline).map_or("a pipeline", String::as_str); + let words = &ran.words[..usize::from(ran.used)]; + Some(( + format!("{name} (indirect kind {} max {}, the list's indirect execution {nth}, user data {words:x?})", ran.kind, ran.count), + words, + )) + } +} + +/// How many indirect executions come before command `at` of a history of +/// breadcrumb operations (`is` tells them): which of a list's it is. +pub(crate) fn before(history: &[T], at: usize, is: impl Fn(&T) -> bool) -> usize { + history[..at.min(history.len())].iter().filter(|op| is(op)).count() +} + +/// The heap slots the user data may name, for the report to describe: the +/// words that are slots as they are, and the slots from where a word is a +/// table's byte offset (32 bytes a descriptor), `table` of them. +pub(crate) fn slots(words: &[u32], count: u32, table: u32) -> Vec<(usize, u32)> { + let mut out = Vec::new(); + for (i, &word) in words.iter().enumerate() { + if word > 0 && word < count && word % 32 != 0 { + out.push((i, word)); + } + if word % 32 == 0 && word / 32 > 16 && word / 32 < count { + out.extend((0..table).map(|k| (i, word / 32 + k)).filter(|s| s.1 < count)); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The execution a breadcrumb history stops at is found by the ones + /// before it, and its pipeline and user data are told. + #[test] + fn an_indirect_execution_is_found_by_its_place_in_the_history() { + let mut all = Indirects::default(); + all.note(1, "[compute a]", 2, 1, &[0x2549f40, 0x20, 0x11]); + all.note(2, "[compute b]", 2, 1, &[7; 20]); + all.note(1, "another name of the same is not taken", 10, 4, &[]); + // dispatch, indirect, barrier, indirect, indirect + let history = [6, 5, 15, 5, 5]; + let nth = before(&history, 3, |op| *op == 5); + assert_eq!(nth, 1); + let (text, words) = all.nth(nth).unwrap(); + assert!(text.starts_with("[compute b] (indirect kind 2 max 1"), "{text}"); + assert_eq!(words, [7; WORDS]); + let (text, words) = all.nth(2).unwrap(); + assert!(text.starts_with("[compute a] (indirect kind 10 max 4"), "{text}"); + assert!(words.is_empty()); + assert!(all.nth(3).is_none()); + assert_eq!(before(&history, 99, |op| *op == 5), 3); + all.clear(); + assert!(all.nth(0).is_none()); + } + + /// A table's byte offset names the slots from it on; a small word that + /// is no multiple of a descriptor's bytes names its own slot. + #[test] + fn user_data_names_slots() { + let words = [0, 0x2549f40, 0x20, 0x11, 0x26f1, 0xffff_ffff]; + let slots = slots(&words, 1_245_184, 2); + assert_eq!(slots, [(1, 0x2549f40 / 32), (1, 0x2549f40 / 32 + 1), (3, 0x11), (4, 0x26f1)]); + } +} diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 7d044ab..6d738d8 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -600,7 +600,7 @@ pub(crate) mod tests { use super::*; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; - use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; use windows::Win32::Graphics::Dxgi::*; use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; use windows::core::Interface; @@ -984,6 +984,134 @@ void main() { } } + /// What raw loads through views that are not raw give past the view's + /// end (ignored: a measurement of the card). A buffer view of 4 KiB in a + /// buffer of 1 MiB whose every dword says where it lies: zeros past the + /// view, or the bytes there (whatever the card has in that place). + #[test] + #[ignore] + fn raw_loads_past_views() { + let Some(mut gpu) = WarpHarness::on(std::env::var_os("VICTORY_BENCH_WARP").is_some()) else { + return; + }; + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=4,b0), DescriptorTable(SRV(t0,numDescriptors=8)), UAV(u0), DescriptorTable(CBV(b1,numDescriptors=8))" +cbuffer C : register(b0) { uint which; uint first; uint step; uint at; } +ByteAddressBuffer v[8] : register(t0); +struct Block { uint4 d[4096]; }; +ConstantBuffer c[8] : register(b1); +RWByteAddressBuffer o : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) { + if (step == 0) { if (id.x == 0) o.Store(at, v[which].Load(first)); } + else if (step == 1) { if (id.x == 0) o.Store(at, c[which].d[first / 16][(first / 4) & 3]); } + else { o.Store(at + id.x * 4, v[which].Load(first + id.x * step)); } +} +"#; + let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile"); + let (buffer, data, _) = gpu.shared_buffer(1 << 20); + for i in 0..(1usize << 18) { + // SAFETY: inside the mapping. + unsafe { data.cast::().add(i).write(0xA000_0000 | i as u32) }; + } + let (_out, out_ptr, out_gpu) = gpu.shared_buffer(1 << 16); + // SAFETY: plain heap creation, views of a live buffer. + let heap: ID3D12DescriptorHeap = unsafe { + gpu.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 16, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + } + .unwrap(); + // SAFETY: as above. + let (cpu, table, step) = unsafe { + ( + heap.GetCPUDescriptorHandleForHeapStart().ptr, + heap.GetGPUDescriptorHandleForHeapStart(), + gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize, + ) + }; + let names = ["raw", "structured 24 at 24", "structured 16", "typed u32", "typed u16", "typed 4 x u32", "constant buffer", "null raw"]; + let view = |i: usize, format: i32, first: u64, count: u32, stride: u32, raw: bool, null: bool| { + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(format), + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: first, + NumElements: count, + StructureByteStride: stride, + Flags: if raw { D3D12_BUFFER_SRV_FLAG_RAW } else { D3D12_BUFFER_SRV_FLAG_NONE }, + }, + }, + }; + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu + i * step }; + // SAFETY: a slot of our heap, a live buffer. + unsafe { gpu.device.CreateShaderResourceView(if null { None } else { Some(&buffer) }, Some(&desc), at) }; + }; + for base in [0, 8] { + view(base, 39, 0, 1024, 0, true, false); + view(base + 1, 0, 1, 170, 24, false, false); + view(base + 2, 0, 0, 256, 16, false, false); + view(base + 3, 42, 0, 1024, 0, false, false); + view(base + 4, 57, 0, 2048, 0, false, false); + view(base + 5, 3, 0, 256, 0, false, false); + view(base + 7, 39, 0, 1, 0, true, true); + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { + // SAFETY: a live buffer. + BufferLocation: unsafe { buffer.GetGPUVirtualAddress() }, + SizeInBytes: 4096, + }; + // SAFETY: a slot of our heap. + unsafe { gpu.device.CreateConstantBufferView(Some(&desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu + (base + 6) * step }) }; + } + let table2 = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: table.ptr + 8 * step as u64 }; + let offsets = [0u32, 4092, 4096, 4104, 8192, 65536, 524_288, (1 << 20) - 4]; + for mode in ["one load (uniform)", "a load a thread", "constant buffer load"] { + println!("{mode}:"); + for (which, name) in names.iter().enumerate() { + // SAFETY: our open list, live buffers. + unsafe { + std::ptr::write_bytes(out_ptr, 0x77, 1 << 16); + gpu.list.SetDescriptorHeaps(&[Some(heap.clone())]); + gpu.list.SetComputeRootSignature(&pass.root); + gpu.list.SetPipelineState(&pass.pso); + gpu.list.SetComputeRootDescriptorTable(1, table); + gpu.list.SetComputeRootUnorderedAccessView(2, out_gpu); + gpu.list.SetComputeRootDescriptorTable(3, table2); + for (k, &offset) in offsets.iter().enumerate() { + let step = match mode.as_bytes()[0] { + b'o' => 0u32, + b'c' => 1, + _ => 4, + }; + // (A thread's loads end at the offset.) + let first = if step == 4 { offset.saturating_sub(63 * 4) } else { offset }; + let constants = [which as u32, first, step, k as u32 * 256]; + gpu.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + gpu.list.Dispatch(1, 1, 1); + } + } + gpu.submit_and_wait(); + let found: Vec = offsets + .iter() + .enumerate() + .map(|(k, &offset)| { + let thread = if mode.as_bytes()[0] == b'a' { (offset.min(63 * 4) / 4) as usize } else { 0 }; + // SAFETY: inside the mapping. + let word = unsafe { out_ptr.cast::().add(k * 64 + thread).read_volatile() }; + format!("{offset}: {word:#x}") + }) + .collect(); + println!(" {name:20} {}", found.join(" ")); + } + } + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() {