Jelajahi Sumber

The crash report names direct mesh dispatches; buffers and groups stay inside what there is

- The lists' notes for a lost device hold direct mesh dispatches too (pipeline,
  groups, user data): run n06c stopped among them.
- A mesh dispatch of more than 65,535 groups is cut to that (more is undefined
  on the host; said once). Vertex and index buffer views end with the copy they
  show.
- indirect::tests::loads_far_outside_views (a measurement): raw, typed,
  constant buffer and texture loads at the ends of 32 bits, uniform and per
  lane, samples at coordinates, levels and gradients that are no numbers: all
  198 ways end inside their views on the RX 7900 XTX.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local 1 hari lalu
induk
melakukan
ef556e4218

+ 12 - 3
crates/victory-gpu/src/draw.rs

@@ -1308,7 +1308,7 @@ impl State {
             shadow.refresh(list, v.address, u64::from(v.size));
             *view = D3D12_VERTEX_BUFFER_VIEW {
                 BufferLocation: shadow.gpu(v.address),
-                SizeInBytes: v.size,
+                SizeInBytes: v.size.min(u32::try_from(shadow.left(v.address)).unwrap_or(u32::MAX)),
                 StrideInBytes: v.stride,
             };
         }
@@ -1326,7 +1326,7 @@ impl State {
             shadow.refresh(list, v.address, u64::from(v.size));
             let view = D3D12_INDEX_BUFFER_VIEW {
                 BufferLocation: shadow.gpu(v.address),
-                SizeInBytes: v.size,
+                SizeInBytes: v.size.min(u32::try_from(shadow.left(v.address)).unwrap_or(u32::MAX)),
                 Format: DXGI_FORMAT(v.format as i32),
             };
             // SAFETY: an open list; the view names a live host buffer.
@@ -2791,8 +2791,17 @@ impl State {
                     #[cfg(feature = "diagnostics")]
                     list.note_op(|| self.op_text(format!("mesh {x}"), false));
                     self.mesh_scissor(list, true);
+                    #[cfg(feature = "diagnostics")]
+                    if let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) {
+                        list.ran_indirect(p.pso.as_raw() as usize, &p.name, crate::host::indirects::DIRECT, x, &self.user);
+                    }
+                    // (The host takes 65,535 groups in a dimension: more is
+                    // undefined there.)
+                    if x > 65_535 {
+                        once!(x, "a mesh dispatch of more groups than the host takes: cut");
+                    }
                     // SAFETY: an open list with everything set.
-                    unsafe { l6.DispatchMesh(x, 1, 1) };
+                    unsafe { l6.DispatchMesh(x.min(65_535), 1, 1) };
                     self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
                     self.mesh_scissor(list, false);
                     DRAWN.fetch_add(1, Ordering::Relaxed);

+ 5 - 2
crates/victory-gpu/src/host.rs

@@ -8505,15 +8505,18 @@ fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &ind
     let all = all.lock().unwrap_or_else(|e| e.into_inner());
     let mut text = String::new();
     let mut shown = 0;
+    let mesh = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_DISPATCHMESH;
     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) {
+        if !indirect(op) && !mesh(op) {
             continue;
         }
         shown += 1;
-        let Some((what, words)) = all.nth(indirects::before(history, at, indirect)) else {
+        let direct = mesh(op);
+        let nth = if direct { indirects::before(history, at, mesh) } else { indirects::before(history, at, indirect) };
+        let Some((what, words)) = all.nth(nth, direct) else {
             continue;
         };
         text.push_str(&format!("; command {at} ran {what}"));

+ 30 - 9
crates/victory-gpu/src/host/indirects.rs

@@ -14,6 +14,9 @@
 use std::collections::HashMap;
 use std::sync::{Arc, Mutex};
 
+/// The kind of a direct mesh dispatch.
+pub(crate) const DIRECT: u32 = u32::MAX;
+
 /// Words of user data kept of each execution.
 pub(crate) const WORDS: usize = 16;
 
@@ -31,6 +34,8 @@ pub(crate) struct Ran {
 pub(crate) struct Indirects {
     names: HashMap<usize, String>,
     ran: Vec<Ran>,
+    /// The direct mesh dispatches, likewise.
+    meshes: Vec<Ran>,
 }
 
 /// A list's, shared with the report's table of lists.
@@ -39,28 +44,40 @@ pub(crate) type Shared = Arc<Mutex<Indirects>>;
 impl Indirects {
     /// An indirect execution of `kind` (the argument's type) of at most
     /// `count` records with `pipeline` (a host object) and user data.
+    /// A direct mesh dispatch of `count` groups is of kind [`DIRECT`].
     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 });
+        let ran = Ran { pipeline, kind, count, words, used: used as u8 };
+        if kind == DIRECT {
+            self.meshes.push(ran);
+        } else {
+            self.ran.push(ran);
+        }
     }
 
     pub(crate) fn clear(&mut self) {
         self.ran.clear();
+        self.meshes.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)?;
+    /// The `nth` execution (from 0), or direct mesh dispatch: its text and
+    /// its user data.
+    pub(crate) fn nth(&self, nth: usize, direct: bool) -> Option<(String, &[u32])> {
+        let ran = if direct { &self.meshes } else { &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),
+            if direct {
+                format!("{name} (a mesh dispatch of {} groups, the list's {nth}, user data {words:x?})", ran.count)
+            } else {
+                format!("{name} (indirect kind {} max {}, the list's indirect execution {nth}, user data {words:x?})", ran.kind, ran.count)
+            },
             words,
         ))
     }
@@ -104,16 +121,20 @@ mod tests {
         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();
+        let (text, words) = all.nth(nth, false).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();
+        all.note(2, "[mesh b]", DIRECT, 9, &[1]);
+        let (text, _) = all.nth(0, true).unwrap();
+        assert!(text.starts_with("[compute b] (a mesh dispatch of 9 groups"), "{text}");
+        assert!(all.nth(1, true).is_none());
+        let (text, words) = all.nth(2, false).unwrap();
         assert!(text.starts_with("[compute a] (indirect kind 10 max 4"), "{text}");
         assert!(words.is_empty());
-        assert!(all.nth(3).is_none());
+        assert!(all.nth(3, false).is_none());
         assert_eq!(before(&history, 99, |op| *op == 5), 3);
         all.clear();
-        assert!(all.nth(0).is_none());
+        assert!(all.nth(0, false).is_none() && all.nth(0, true).is_none());
     }
 
     /// A table's byte offset names the slots from it on; a small word that

+ 170 - 0
crates/victory-gpu/src/indirect.rs

@@ -1568,6 +1568,176 @@ void main(uint3 t : SV_DispatchThreadID) {
         println!("device: {:?}", unsafe { gpu.device.GetDeviceRemovedReason() });
     }
 
+    /// Loads far outside their views (ignored: it may lose the device, and
+    /// says which way did): raw, typed, constant and texture loads at the
+    /// ends of 32 bits, uniform and per lane, and samples at coordinates,
+    /// levels and gradients that are no numbers. Each way is a submission of
+    /// its own.
+    #[test]
+    #[ignore]
+    fn loads_far_outside_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=4),CBV(b1)), UAV(u0), StaticSampler(s0,filter=FILTER_MIN_MAG_MIP_LINEAR,addressU=TEXTURE_ADDRESS_WRAP,addressV=TEXTURE_ADDRESS_WRAP)"
+cbuffer C : register(b0) { uint how; uint far; uint lane; uint out_at; }
+ByteAddressBuffer raw : register(t0);
+Buffer<float4> typed : register(t1);
+Texture2D<float4> tex : register(t2);
+struct Block { uint4 d[4096]; };
+ConstantBuffer<Block> block : register(b1);
+SamplerState s : register(s0);
+RWByteAddressBuffer o : register(u0);
+[RootSignature(RS)]
+[numthreads(64, 1, 1)]
+void main(uint3 t : SV_DispatchThreadID) {
+    uint at = far + t.x * lane * 4;
+    float4 c = 0;
+    if (how == 0) c = asfloat(raw.Load4(at));
+    if (how == 1) c = asfloat(raw.Load(at + 4092));
+    if (how == 2) c = typed.Load(at);
+    if (how == 3) c = asfloat(block.d[at]);
+    if (how == 4) c = tex.Load(int3(at, 0, 0));
+    if (how == 5) c = tex.Load(int3(0, 0, at));
+    if (how == 6) c = tex.SampleLevel(s, asfloat(uint2(at, at)), 0);
+    if (how == 7) c = tex.SampleLevel(s, float2(0.5, 0.5), asfloat(at));
+    if (how == 8) c = tex.SampleGrad(s, float2(0.5, 0.5), asfloat(at).xx, asfloat(at).xx);
+    uint was;
+    o.InterlockedAdd(any(asuint(c) != 0) ? 4 : 0, 1, was);
+}
+"#;
+        let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile");
+        let (buffer, data, gpu_at) = gpu.shared_buffer(1 << 16);
+        // SAFETY: the mapping.
+        unsafe { std::ptr::write_bytes(data, 0x3f, 1 << 16) };
+        let desc = D3D12_RESOURCE_DESC {
+            Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
+            Width: 64,
+            Height: 64,
+            DepthOrArraySize: 1,
+            MipLevels: 7,
+            Format: DXGI_FORMAT(28),
+            SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+            ..Default::default()
+        };
+        // SAFETY: plain creation; slots of our heap, live objects.
+        let (_texture, heap) = unsafe {
+            let mut made: Option<ID3D12Resource> = None;
+            gpu.device
+                .CreateCommittedResource(
+                    &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
+                    D3D12_HEAP_FLAG_NONE,
+                    &desc,
+                    D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
+                    None,
+                    &mut made,
+                )
+                .unwrap();
+            let texture = made.unwrap();
+            let heap: ID3D12DescriptorHeap = gpu
+                .device
+                .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
+                    Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
+                    NumDescriptors: 5,
+                    Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
+                    NodeMask: 0,
+                })
+                .unwrap();
+            let step = gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize;
+            let at = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: heap.GetCPUDescriptorHandleForHeapStart().ptr + i * step };
+            for (i, format, count, flags) in
+                [(0, 39, 1024, D3D12_BUFFER_SRV_FLAG_RAW), (1, 2, 256, D3D12_BUFFER_SRV_FLAG_NONE)]
+            {
+                let view = 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: 0, NumElements: count, StructureByteStride: 0, Flags: flags },
+                    },
+                };
+                gpu.device.CreateShaderResourceView(&buffer, Some(&view), at(i));
+            }
+            gpu.device.CreateShaderResourceView(&texture, None, at(2));
+            gpu.device.CreateShaderResourceView(&texture, None, at(3));
+            gpu.device.CreateConstantBufferView(
+                Some(&D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu_at, SizeInBytes: 4096 }),
+                at(4),
+            );
+            (texture, heap)
+        };
+        let names = [
+            "raw, 4 dwords",
+            "raw, offset added",
+            "typed",
+            "constant buffer",
+            "texel",
+            "level of a texel",
+            "sample",
+            "level of a sample",
+            "gradients of a sample",
+        ];
+        for (how, name) in names.iter().enumerate() {
+            for far in [
+                0u32,
+                0x1000,
+                0x7fff_fff0,
+                0x8000_0000,
+                0xffff_f000,
+                0xffff_fff0,
+                0xffff_fffc,
+                0x7fc0_0000,
+                0x7f80_0000,
+                0xff80_0000,
+                0x7f7f_ffff,
+            ] {
+                for lane in [0u32, 1] {
+                    let (_out, out_ptr, out_gpu) = gpu.shared_buffer(1 << 12);
+                    // SAFETY: the mapping; our open list, live objects.
+                    unsafe {
+                        std::ptr::write_bytes(out_ptr, 0, 1 << 12);
+                        gpu.list.SetDescriptorHeaps(&[Some(heap.clone())]);
+                        gpu.list.SetComputeRootSignature(&pass.root);
+                        gpu.list.SetPipelineState(&pass.pso);
+                        gpu.list.SetComputeRoot32BitConstants(0, 4, [how as u32, far, lane, 0].as_ptr().cast(), 0);
+                        gpu.list.SetComputeRootDescriptorTable(1, heap.GetGPUDescriptorHandleForHeapStart());
+                        gpu.list.SetComputeRootUnorderedAccessView(2, out_gpu);
+                        gpu.list.Dispatch(1, 1, 1);
+                        // (Not `submit_and_wait`, which expects to go on.)
+                        gpu.list.Close().unwrap();
+                        gpu.submitted += 1;
+                        let cmd: ID3D12CommandList = gpu.list.cast().unwrap();
+                        gpu.queue.ExecuteCommandLists(&[Some(cmd)]);
+                        let _ = gpu.queue.Signal(&gpu.fence, gpu.submitted);
+                        let _ = gpu.fence.SetEventOnCompletion(gpu.submitted, gpu.event);
+                        WaitForSingleObject(gpu.event, 8_000);
+                    }
+                    // SAFETY: the mapping; plain queries.
+                    let (zeros, others, device) = unsafe {
+                        (
+                            out_ptr.cast::<u32>().read_volatile(),
+                            out_ptr.cast::<u32>().add(1).read_volatile(),
+                            gpu.device.GetDeviceRemovedReason(),
+                        )
+                    };
+                    println!(
+                        "{name} at {far:#x}, lanes {lane}: zeros {zeros}, others {others}{}",
+                        if device.is_ok() { "" } else { " DEVICE LOST" }
+                    );
+                    if device.is_err() {
+                        return;
+                    }
+                    // SAFETY: the card is done with them.
+                    unsafe {
+                        gpu.allocator.Reset().unwrap();
+                        gpu.list.Reset(&gpu.allocator, None).unwrap();
+                    }
+                }
+            }
+        }
+    }
+
     /// The clamp compiles with the system's compiler and the host takes it.
     #[test]
     fn argument_clamp_builds() {