From c3fb89e82f43d827c9fff9636ebda4492fe37fdd Mon Sep 17 00:00:00 2001 From: Remington Wilcox <129909388+RemingtonWilcox@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:18:17 -0800 Subject: [PATCH 1/6] Memory windows from the descriptor heap: no per-access switch With more than one memory window every access in a translated shader was inlined once per window (a switch over the root UAVs mem, mem1..). Now window k is a raw UAV at MEM_HEAP_BASE + k of the shared shader-visible heap, and each access is one ResourceDescriptorHeap load/store. - Options::heap_windows / HEAP_WINDOWS flag in the windows count (so the translation and DXIL cache keys differ); on unless XCL_HEAP_WINDOWS=0 or the views could not be made. - console_heap: the first 4 descriptors of the shared heap are the windows' raw views (4 GiB - 64 KiB at most: a 4 GiB raw view does not fit a 32-bit byte size). - Lists bind the shared heap before an ABI dispatch / draw when they set none. - xcl shaders --precompile uses the same key. - Experiments (aperture_tests.rs), RTX 3090: E1: one structured view over a 16 GiB reserved buffer wraps at 4 GiB (root UAV and heap view) - a single aperture binding is not possible on NVIDIA. E1b (debug layer): a 4 GiB - 64 KiB raw view and a 1 GiB raw view at FirstElement 5 GiB both work, no debug-layer messages. E2 (ignored, run alone): a 19 601-instruction CS, DXC 12.1 s with one window, 150.7 s with the 4-window switch, 12.5 s with heap windows. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/aperture_tests.rs | 751 ++++++++++++++++++++ crates/xcl/src/gpu/recomp/emit.rs | 22 +- crates/xcl/src/gpu/recomp/mod.rs | 24 +- crates/xcl/src/gpu/recomp/pso.rs | 19 +- crates/xcl/src/gpu/recomp/runner.rs | 32 + crates/xcl/src/gpu/recomp/tests.rs | 15 +- crates/xcl/src/hle/d3d12x/bind.rs | 1 + crates/xcl/src/hle/d3d12x/console_heap.rs | 36 +- crates/xcl/src/hle/d3d12x/console_list.rs | 9 + crates/xcl/src/hle/d3d12x/list_x.rs | 20 + crates/xcl/src/hle/d3d12x/real.rs | 7 + crates/xcl/src/shaders.rs | 9 +- 12 files changed, 934 insertions(+), 11 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/aperture_tests.rs diff --git a/crates/xcl/src/gpu/recomp/aperture_tests.rs b/crates/xcl/src/gpu/recomp/aperture_tests.rs new file mode 100644 index 000000000..4ebe0889e --- /dev/null +++ b/crates/xcl/src/gpu/recomp/aperture_tests.rs @@ -0,0 +1,751 @@ +//! Experiment E1 (memory aperture): can one binding reach a reserved buffer far above 4 GiB? +//! +//! The memory windows are four root UAVs of 4 GiB each, because a `ByteAddressBuffer` offset +//! is a 32-bit `uint`. A *structured* view with a 2048-byte row addresses +//! `row · 2048 + byte`: 2^32 rows reach 8 TiB through one binding, so a shader could reach all +//! of title memory without a per-access `switch` over windows. This test checks that the +//! drivers actually compute that address beyond 4 GiB, through a root UAV and through a +//! descriptor-heap view, on a 16 GiB reserved buffer with tiles mapped at 0, 4 GiB + 64 KiB, +//! 13 GiB and the last 64 KiB. A tile at 64 KiB (where a 32-bit truncation of 4 GiB + 64 KiB +//! would land) must stay untouched. + +use std::mem::{transmute_copy, ManuallyDrop}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D::*; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::Graphics::Dxgi::*; + +const GIB: u64 = 1 << 30; +const TILE: u64 = 0x1_0000; +/// aperture size +const SIZE: u64 = 16 * GIB; +/// tiles written by the shader (byte offsets in the aperture) +const TILES: [u64; 4] = [0, 4 * GIB + TILE, 13 * GIB, SIZE - TILE]; +/// a 32-bit truncation of `TILES[1]` lands here: must stay zero +const ALIAS: u64 = TILE; +/// dwords per lane and tile the shader writes (one every 4 KiB of the tile) +const STEPS: u64 = 16; +const LANES: u64 = 64; + +fn shader(heap: bool) -> String { + let (decl, get) = if heap { + ("", "RWStructuredBuffer ap = ResourceDescriptorHeap[0];") + } else { + ("RWStructuredBuffer ap : register(u0);", "") + }; + format!( + r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), UAV(u0), UAV(u1), RootConstants(num32BitConstants=4, b0)" +struct XclRow {{ uint d[512]; }}; +{decl} +RWByteAddressBuffer outb : register(u1); +cbuffer C : register(b0) {{ uint pass_; uint probe; uint pad0; uint pad1; }}; +// (hi, lo) of a 64-bit aperture offset → row and byte +uint xcl_row(uint hi, uint lo) {{ return (hi << 21) | (lo >> 11); }} +static const uint THI[4] = {{ {h0}u, {h1}u, {h2}u, {h3}u }}; +static const uint TLO[4] = {{ {l0}u, {l1}u, {l2}u, {l3}u }}; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint l : SV_GroupThreadID) {{ + {get} + for (uint t = 0; t < 4; t++) {{ + for (uint j = 0; j < {steps}u; j++) {{ + uint lo = TLO[t] + j * 4096u + l * 4u; + uint row = xcl_row(THI[t], lo); + uint byte = lo & 2047u; + uint v = 0x80000000u | (t << 24) | (j << 16) | l; + if (pass_ == 0u) {{ + ap[row].d[byte >> 2] = v; + }} else {{ + outb.Store(((t * {steps}u + j) * 64u + l) * 4u, ap[row].d[byte >> 2]); + }} + }} + }} + if (pass_ == 1u && l == 0u) {{ + // probe: a dword past the end of row 0 of tile 0 (d[512] = row 1, d[0]?) + outb.Store(4u * 4u * {steps}u * 64u, ap[0].d[511u + probe]); + }} +}} +"#, + h0 = TILES[0] >> 32, + h1 = TILES[1] >> 32, + h2 = TILES[2] >> 32, + h3 = TILES[3] >> 32, + l0 = TILES[0] as u32, + l1 = TILES[1] as u32, + l2 = TILES[2] as u32, + l3 = TILES[3] as u32, + steps = STEPS, + ) +} + +fn expected(t: u64, j: u64, l: u64) -> u32 { + 0x8000_0000 | (t << 24 | j << 16 | l) as u32 +} + +fn buf(dev: &ID3D12Device, size: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES, uav: bool) -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: if uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + }; + let mut r: Option = None; + unsafe { dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap() }; + r.unwrap() +} + +fn barrier_uav(r: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: unsafe { transmute_copy(r) } }) }, + } +} + +fn transition(r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: unsafe { transmute_copy(r) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } +} + +fn device() -> Option<(ID3D12Device, String)> { + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + if sel == crate::gpu::adapter::Selector::Warp { + return None; + } + let (a, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next()?; + let dev = crate::gpu::agility::create_device(&a, D3D_FEATURE_LEVEL_12_0).ok()?; + Some((dev, crate::gpu::adapter::name(&desc))) + } +} + +/// One run (root UAV or heap view): the words read back through the shader and the tiles' +/// contents copied straight out of the aperture. +unsafe fn run(dev: &ID3D12Device, heap_view: bool) -> Result<(Vec, Vec>), String> { + let dxil = super::dxc::compile(&shader(heap_view), "main", "cs_6_6", &[])?; + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("root signature: {e}"))?; + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }) + .map_err(|e| format!("pipeline: {e}"))?; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).map_err(|e| e.to_string())?; + // the aperture: a 16 GiB reserved buffer + let mut ap: Option = None; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: SIZE, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut ap).map_err(|e| format!("16 GiB reserved buffer: {e}"))?; + let ap = ap.unwrap(); + let mapped: Vec = TILES.iter().copied().chain([ALIAS]).collect(); + let mut tiles: Option = None; + dev.CreateHeap( + &D3D12_HEAP_DESC { + SizeInBytes: TILE * mapped.len() as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, + }, + &mut tiles, + ) + .map_err(|e| e.to_string())?; + let tiles = tiles.unwrap(); + let coords: Vec = mapped.iter().map(|&o| D3D12_TILED_RESOURCE_COORDINATE { X: (o / TILE) as u32, ..Default::default() }).collect(); + let regions: Vec = mapped.iter().map(|_| D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }).collect(); + let flags = vec![D3D12_TILE_RANGE_FLAG_NONE; mapped.len()]; + let offsets: Vec = (0..mapped.len() as u32).collect(); + let counts = vec![1u32; mapped.len()]; + queue.UpdateTileMappings(&ap, coords.len() as u32, Some(coords.as_ptr()), Some(regions.as_ptr()), &tiles, flags.len() as u32, Some(flags.as_ptr()), Some(offsets.as_ptr()), Some(counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE); + + let out_words = 4 * STEPS * LANES + 1; + let out = buf(dev, out_words * 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true); + let rb_bytes = out_words * 4 + TILE * mapped.len() as u64; + let rb = buf(dev, rb_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + // shader-visible heap: [0] = the aperture as a structured UAV of 2048-byte rows + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 1, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }) + .map_err(|e| e.to_string())?; + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: (SIZE / 2048) as u32, StructureByteStride: 2048, CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_NONE }, + }, + }; + dev.CreateUnorderedAccessView(&ap, None::<&ID3D12Resource>, Some(&uav), dh.GetCPUDescriptorHandleForHeapStart()); + + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(|e| e.to_string())?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).map_err(|e| e.to_string())?; + // fresh tiles hold whatever the heap had: clear them first (copy from a zeroed buffer) + let zero = buf(dev, TILE, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false); + let mut p = std::ptr::null_mut(); + zero.Map(0, None, Some(&mut p)).map_err(|e| e.to_string())?; + std::ptr::write_bytes(p as *mut u8, 0, TILE as usize); + zero.Unmap(0, None); + for &o in &mapped { + list.CopyBufferRegion(&ap, o, &zero, 0, TILE); + } + list.ResourceBarrier(&[ + transition(&ap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + transition(&out, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]); + list.SetDescriptorHeaps(&[Some(dh.clone())]); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, ap.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, out.GetGPUVirtualAddress()); + for pass in 0..2u32 { + list.SetComputeRoot32BitConstants(2, 2, [pass, 1u32].as_ptr() as _, 0); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[barrier_uav(&ap), barrier_uav(&out)]); + } + list.ResourceBarrier(&[ + transition(&ap, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + ]); + list.CopyBufferRegion(&rb, 0, &out, 0, out_words * 4); + for (i, &o) in mapped.iter().enumerate() { + list.CopyBufferRegion(&rb, out_words * 4 + i as u64 * TILE, &ap, o, TILE); + } + list.Close().map_err(|e| e.to_string())?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(|e| e.to_string())?)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| e.to_string())?; + queue.Signal(&fence, 1).map_err(|e| e.to_string())?; + crate::gpu::fence::wait(&fence, 1, dev, None, 20_000).map_err(|e| format!("{e}"))?; + let mut q = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut q)).map_err(|e| e.to_string())?; + let all = std::slice::from_raw_parts(q as *const u32, (rb_bytes / 4) as usize).to_vec(); + rb.Unmap(0, None); + let read = all[..out_words as usize].to_vec(); + let tiles = (0..mapped.len()).map(|i| all[out_words as usize + i * (TILE as usize / 4)..][..TILE as usize / 4].to_vec()).collect(); + Ok((read, tiles)) +} + +/// Not an assertion: what the GPU does (RTX 3090, driver 616.92: both bindings fail above +/// 4 GiB – the structured row · stride wraps at 2^32 and a heap view's byte size is 32 bits – +/// so a single aperture binding cannot replace the windows; `gpu_raw_window_view_reaches_its_top` +/// is the form XCL uses). +#[test] +fn gpu_aperture_structured_rows_above_4_gib() { + let Some((dev, name)) = device() else { + println!("no GPU – skipping"); + return; + }; + if super::dxc::location().is_err() { + println!("no DXC – skipping"); + return; + } + let mut va = D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT::default(); + unsafe { dev.CheckFeatureSupport(D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT, &mut va as *mut _ as _, std::mem::size_of_val(&va) as u32).unwrap() }; + println!("{name}: GPU VA bits per resource {}, per process {}", va.MaxGPUVirtualAddressBitsPerResource, va.MaxGPUVirtualAddressBitsPerProcess); + let mut fails = Vec::new(); + for heap_view in [false, true] { + let how = if heap_view { "heap view" } else { "root UAV" }; + let (read, tiles) = match unsafe { run(&dev, heap_view) } { + Ok(r) => r, + Err(e) => { + fails.push(format!("{how}: {e}")); + continue; + } + }; + let mut bad = 0; + for t in 0..4u64 { + for j in 0..STEPS { + for l in 0..LANES { + let want = expected(t, j, l); + let got_read = read[((t * STEPS + j) * LANES + l) as usize]; + let got_mem = tiles[t as usize][((j * 4096 + l * 4) / 4) as usize]; + if got_read != want || got_mem != want { + if bad < 5 { + println!("{how}: tile {t} step {j} lane {l}: read {got_read:#x}, memory {got_mem:#x}, want {want:#x}"); + } + bad += 1; + } + } + } + } + let alias_dirty = tiles[4].iter().filter(|&&w| w != 0).count(); + let probe = read[(4 * STEPS * LANES) as usize]; + println!( + "{how}: {bad} wrong words of {}, alias tile dirty words {alias_dirty}; d[512] of row 0 reads {probe:#x} (row 1 d[0] = {:#x})", + 4 * STEPS * LANES, + tiles[0][512] + ); + if bad > 0 || alias_dirty > 0 { + fails.push(format!("{how}: {bad} wrong words, {alias_dirty} words in the alias tile")); + } + } + println!("{name}: structured aperture {}", if fails.is_empty() { "works".to_string() } else { format!("fails: {fails:?}") }); +} + +/// The heap-window form (`Options::heap_windows`) on a real sparse window: a 4 GiB reserved +/// buffer seen through `runner::raw_window_uav` (4 GiB − 64 KiB) reaches its last usable tile. +#[test] +fn gpu_raw_window_view_reaches_its_top() { + let Some((dev, name)) = device() else { return }; + if super::dxc::location().is_err() { + return; + } + let top = (4 * GIB) - 2 * TILE; // the last tile the view covers + let src = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), UAV(u0)" +RWByteAddressBuffer outb : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint l : SV_GroupThreadID) { + RWByteAddressBuffer w = ResourceDescriptorHeap[NonUniformResourceIndex(0u)]; + w.Store(0xFFFE0000u + 4u * l, 0x5A000000u | l); + w.Store(4u * l, 0xA5000000u | l); + DeviceMemoryBarrier(); + outb.Store(8u * l, w.Load(0xFFFE0000u + 4u * l)); + outb.Store(8u * l + 4u, w.Load(4u * l)); +} +"#; + unsafe { + let dxil = super::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }) + .unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 4 * GIB, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut win: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut win).unwrap(); + let win = win.unwrap(); + let mut heap: Option = None; + dev.CreateHeap(&D3D12_HEAP_DESC { SizeInBytes: 2 * TILE, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }, &mut heap).unwrap(); + let heap = heap.unwrap(); + let coords = [0u64, top].map(|o| D3D12_TILED_RESOURCE_COORDINATE { X: (o / TILE) as u32, ..Default::default() }); + let regions = [D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }; 2]; + let flags = [D3D12_TILE_RANGE_FLAG_NONE; 2]; + queue.UpdateTileMappings(&win, 2, Some(coords.as_ptr()), Some(regions.as_ptr()), &heap, 2, Some(flags.as_ptr()), Some([0u32, 1].as_ptr()), Some([1u32; 2].as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE); + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 1, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }) + .unwrap(); + dev.CreateUnorderedAccessView(&win, None::<&ID3D12Resource>, Some(&super::runner::raw_window_uav(4 * GIB)), dh.GetCPUDescriptorHandleForHeapStart()); + let out = buf(&dev, 512, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb = buf(&dev, 512 + 256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap(); + list.SetDescriptorHeaps(&[Some(dh.clone())]); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, out.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[ + transition(&win, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + ]); + list.CopyBufferRegion(&rb, 0, &out, 0, 512); + list.CopyBufferRegion(&rb, 512, &win, top, 256); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + let mut q = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut q)).unwrap(); + let w = std::slice::from_raw_parts(q as *const u32, 192).to_vec(); + rb.Unmap(0, None); + for l in 0..64usize { + assert_eq!(w[2 * l], 0x5A00_0000 | l as u32, "{name}: lane {l}, the window's top tile through the heap view"); + assert_eq!(w[2 * l + 1], 0xA500_0000 | l as u32, "{name}: lane {l}, the window's first tile"); + assert_eq!(w[128 + l], 0x5A00_0000 | l as u32, "{name}: lane {l}, the top tile in memory"); + } + } +} + +/// Where does each path wrap? One 16 GiB reserved buffer, tiles at 64 KiB (A) and +/// 4 GiB + 64 KiB (B), each pre-filled by the shader through a root UAV whose *VA* already +/// points past 4 GiB (so no shader offset above 4 GiB): then (1) a raw read through a root UAV +/// at VA + 4 GiB, (2) a structured read of row 0x200020 through a root UAV at VA, (3) the copy +/// engine at offset 4 GiB + 64 KiB. +#[test] +fn gpu_aperture_probe_where_it_wraps() { + let Some((dev, name)) = device() else { return }; + if super::dxc::location().is_err() { + return; + } + let src = r#" +#define RS "UAV(u0), UAV(u1), UAV(u2), UAV(u3)" +struct XclRow { uint d[512]; }; +RWByteAddressBuffer lo4 : register(u0); // VA + 0 +RWByteAddressBuffer hi4 : register(u1); // VA + 4 GiB +RWStructuredBuffer rows : register(u2); // VA + 0, rows of 2 KiB +RWByteAddressBuffer outb : register(u3); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + lo4.Store(0x10000, 0xAAAAu); + hi4.Store(0x10000, 0xBBBBu); + DeviceMemoryBarrier(); + outb.Store(0, lo4.Load(0x10000)); + outb.Store(4, hi4.Load(0x10000)); + outb.Store(8, rows[0x200020u].d[0]); // 4 GiB + 64 KiB as row · 2048 + outb.Store(12, rows[0x20u].d[0]); // 64 KiB as row · 2048 + rows[0x200020u].d[1] = 0xCCCCu; // write through the structured path +} +"#; + unsafe { + let dxil = super::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }) + .unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: SIZE, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut ap: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut ap).unwrap(); + let ap = ap.unwrap(); + let mut heap: Option = None; + dev.CreateHeap(&D3D12_HEAP_DESC { SizeInBytes: 2 * TILE, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }, &mut heap).unwrap(); + let heap = heap.unwrap(); + let at = [ALIAS, 4 * GIB + TILE]; + let coords: Vec<_> = at.iter().map(|&o| D3D12_TILED_RESOURCE_COORDINATE { X: (o / TILE) as u32, ..Default::default() }).collect(); + let regions = [D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }; 2]; + let flags = [D3D12_TILE_RANGE_FLAG_NONE; 2]; + let offs = [0u32, 1]; + let counts = [1u32; 2]; + queue.UpdateTileMappings(&ap, 2, Some(coords.as_ptr()), Some(regions.as_ptr()), &heap, 2, Some(flags.as_ptr()), Some(offs.as_ptr()), Some(counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE); + let out = buf(&dev, 256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb = buf(&dev, 256 + 2 * 16, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap(); + let va = ap.GetGPUVirtualAddress(); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, va); + list.SetComputeRootUnorderedAccessView(1, va + 4 * GIB); + list.SetComputeRootUnorderedAccessView(2, va); + list.SetComputeRootUnorderedAccessView(3, out.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[ + transition(&ap, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + ]); + list.CopyBufferRegion(&rb, 0, &out, 0, 256); + list.CopyBufferRegion(&rb, 256, &ap, ALIAS, 16); + list.CopyBufferRegion(&rb, 272, &ap, 4 * GIB + TILE, 16); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + let mut q = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut q)).unwrap(); + let w = std::slice::from_raw_parts(q as *const u32, (256 + 32) / 4).to_vec(); + rb.Unmap(0, None); + println!("{name}: raw VA+0 @64K = {:#x} (want AAAA), raw VA+4G @64K = {:#x} (want BBBB)", w[0], w[1]); + println!("structured row 0x200020 = {:#x} (want BBBB), row 0x20 = {:#x} (want AAAA)", w[2], w[3]); + println!("copy @64K = {:x?} (want AAAA, 0..), copy @4G+64K = {:x?} (want BBBB, CCCC..)", &w[64..68], &w[68..72]); + // a second submission (nothing cached from the stores) reads both tiles back through + // the raw root UAVs: tells a wrapped tile mapping from a wrapping copy engine + let src2 = r#" +#define RS "UAV(u0), UAV(u1), UAV(u2), UAV(u3)" +RWByteAddressBuffer lo4 : register(u0); +RWByteAddressBuffer hi4 : register(u1); +RWByteAddressBuffer unused : register(u2); +RWByteAddressBuffer outb : register(u3); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { outb.Store4(0, uint4(lo4.Load2(0x10000), hi4.Load2(0x10000))); } +"#; + let dxil2 = super::dxc::compile(src2, "main", "cs_6_6", &[]).unwrap(); + let rs2: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil2).unwrap(); + let pso2: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs2), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil2.as_ptr() as _, BytecodeLength: dxil2.len() }, + ..Default::default() + }) + .unwrap(); + let out2 = buf(&dev, 256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb2 = buf(&dev, 256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + alloc.Reset().unwrap(); + list.Reset(&alloc, &pso2).unwrap(); + list.ResourceBarrier(&[transition(&ap, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + list.SetComputeRootSignature(&rs2); + list.SetComputeRootUnorderedAccessView(0, va); + list.SetComputeRootUnorderedAccessView(1, va + 4 * GIB); + list.SetComputeRootUnorderedAccessView(2, va); + list.SetComputeRootUnorderedAccessView(3, out2.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[transition(&out2, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&rb2, 0, &out2, 0, 256); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 2).unwrap(); + crate::gpu::fence::wait(&fence, 2, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + let mut q = std::ptr::null_mut(); + rb2.Map(0, None, Some(&mut q)).unwrap(); + let w2 = std::slice::from_raw_parts(q as *const u32, 4).to_vec(); + rb2.Unmap(0, None); + println!("second submission: VA+0 @64K = {:x?}, VA+4G @64K = {:x?}", &w2[0..2], &w2[2..4]); + } +} + +/// Experiment E2: DXC + driver time of one large synthetic compute program (~20 000 +/// instructions, ~2 800 memory accesses: s_load, buffer load / store, global load) with one +/// window, four windows through the root-UAV `switch`, and four windows from the descriptor +/// heap. A random literal per run keeps the driver's pipeline cache out of it. Run alone: +/// `cargo test --release -p xcl --lib e2_window_compile_time -- --ignored --nocapture` +#[test] +#[ignore] +fn e2_window_compile_time() { + use crate::gpu::rdna2::encode; + let Some((dev, name)) = device() else { return }; + if super::dxc::location().is_err() { + return; + } + let blocks: usize = std::env::var("XCL_E2_BLOCKS").ok().and_then(|v| v.parse().ok()).unwrap_or(700); + let reps: usize = std::env::var("XCL_E2_REPS").ok().and_then(|v| v.parse().ok()).unwrap_or(3); + let program = |salt: u32| -> Vec { + let mut v = Vec::new(); + let mut e = |n: &str, enc: &str, f: &[(&str, u64)], l: Option| v.extend(encode(n, enc, f, l).unwrap_or_else(|x| panic!("{n}: {x}"))); + e("S_MOV_B32", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 255)], Some(salt)); + for i in 0..blocks as u64 { + e("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 2), ("OFFSET", (i * 16) & 0xFFFF)], None); + e("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 2), ("SOFFSET", 128), ("IDXEN", 1)], None); + e("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 6), ("ADDR", 4), ("SADDR", 0x7D), ("OFFSET", (i * 4) & 0x7FF)], None); + for k in 0..12u64 { + e("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 256 + 1 + (k & 1) * 5), ("VSRC1", 2)], None); + e("V_MUL_LO_U16", "ENC_VOP3", &[("VDST", 3), ("SRC0", 256 + 2), ("SRC1", 30)], None); + } + e("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 2), ("VADDR", 0), ("SRSRC", 2), ("SOFFSET", 128), ("IDXEN", 1)], None); + } + e("S_ENDPGM", "ENC_SOPP", &[], None); + v + }; + let rs = super::pso::abi_root_signature(&dev, false).unwrap(); + let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 4, ..Default::default() }; + let forms = [("1 window", 1, false), ("4 windows, switch", 4, false), ("4 windows, heap", 4, true)]; + let mut seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u32; + println!("{name}: {blocks} blocks ({} instructions), {reps} runs each", 1 + blocks * 28); + for (label, windows, heap) in forms { + let (mut dxc_t, mut drv_t, mut sizes) = (Vec::new(), Vec::new(), (0, 0)); + for _ in 0..reps { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let t = super::translate(&program(seed), &super::Options { mode: super::Mode::Compute(cs.clone()), mem_windows: windows, heap_windows: heap, split_wave64: super::runner::split_wave64(), ..Default::default() }).unwrap(); + let t0 = std::time::Instant::now(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + dxc_t.push(t0.elapsed().as_secs_f64()); + let t1 = std::time::Instant::now(); + let _pso: ID3D12PipelineState = unsafe { + dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }) + } + .unwrap(); + drv_t.push(t1.elapsed().as_secs_f64()); + sizes = (t.hlsl.len(), dxil.len()); + } + let med = |v: &mut Vec| { + v.sort_by(|a, b| a.partial_cmp(b).unwrap()); + v[v.len() / 2] + }; + let (d, r) = (med(&mut dxc_t), med(&mut drv_t)); + println!("{label:>18}: HLSL {:>8} B, DXIL {:>8} B, DXC {d:6.2} s, driver {r:6.2} s, total {:6.2} s (DXC {dxc_t:.2?}, driver {drv_t:.2?})", sizes.0, sizes.1, d + r); + } +} + +/// Experiment E1b, run alone (it turns on the debug layer for the process): +/// `cargo test --release -p xcl --lib e1b_raw_views_under_debug_layer -- --ignored --nocapture`. +/// (1) a raw view of 4 GiB - 64 KiB over a 4 GiB reserved window (the heap-window form; one +/// audit expected the 2^27-element typed-buffer cap to reject it), (2) a raw 1 GiB view whose +/// FirstElement starts past 4 GiB in a 16 GiB reserved buffer (another audit's 1 GiB slices): +/// both written and read through `ResourceDescriptorHeap`, with what the debug layer says. +#[test] +#[ignore] +fn e1b_raw_views_under_debug_layer() { + unsafe { + match crate::gpu::agility::configuration_interface::(&CLSID_D3D12Debug) { + Ok(d) => d.EnableDebugLayer(), + Err(e) => { + println!("no debug layer: {e}"); + return; + } + } + } + let Some((dev, name)) = device() else { return }; + let src = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), UAV(u0), RootConstants(num32BitConstants=4, b0)" +RWByteAddressBuffer outb : register(u0); +cbuffer C : register(b0) { uint slot; uint at; uint tag; uint pad; }; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint l : SV_GroupThreadID) { + RWByteAddressBuffer w = ResourceDescriptorHeap[NonUniformResourceIndex(slot)]; + w.Store(at + 4u * l, tag | l); + DeviceMemoryBarrier(); + outb.Store(4u * l, w.Load(at + 4u * l)); +} +"#; + unsafe { + let dxil = super::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }) + .unwrap(); + let q: ID3D12InfoQueue = dev.cast().expect("info queue (debug layer on)"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let reserved = |bytes: u64| { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut r).unwrap(); + r.unwrap() + }; + let win = reserved(4 * GIB); + let big = reserved(16 * GIB); + let mut heap: Option = None; + dev.CreateHeap(&D3D12_HEAP_DESC { SizeInBytes: 3 * TILE, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }, &mut heap).unwrap(); + let heap = heap.unwrap(); + // window: its last covered tile; big: 5 GiB + 64 KiB (the slice's offset 64 KiB) and its 32-bit alias + let map = |r: &ID3D12Resource, at: u64, tile: u32| { + let c = D3D12_TILED_RESOURCE_COORDINATE { X: (at / TILE) as u32, ..Default::default() }; + let s = D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }; + queue.UpdateTileMappings(r, 1, Some(&c), Some(&s), &heap, 1, Some(&D3D12_TILE_RANGE_FLAG_NONE), Some(&tile), Some(&1), D3D12_TILE_MAPPING_FLAG_NONE); + }; + map(&win, 4 * GIB - 2 * TILE, 0); + map(&big, 5 * GIB + TILE, 1); + map(&big, GIB + TILE, 2); + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 2, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }) + .unwrap(); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let h0 = dh.GetCPUDescriptorHandleForHeapStart(); + let before = q.GetNumStoredMessages(); + dev.CreateUnorderedAccessView(&win, None::<&ID3D12Resource>, Some(&super::runner::raw_window_uav(4 * GIB)), h0); + let mut slice = super::runner::raw_window_uav(GIB); + slice.Anonymous.Buffer.FirstElement = 5 * GIB / 4; + dev.CreateUnorderedAccessView(&big, None::<&ID3D12Resource>, Some(&slice), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h0.ptr + inc }); + let after_views = q.GetNumStoredMessages(); + let out = buf(&dev, 512, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb = buf(&dev, 512, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap(); + list.SetDescriptorHeaps(&[Some(dh.clone())]); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, out.GetGPUVirtualAddress()); + // slot 0: top tile of the window (offset 0xFFFE0000); slot 1: offset 64 KiB of the slice at 5 GiB + list.SetComputeRoot32BitConstants(1, 3, [0u32, 0xFFFE_0000, 0x5A00_0000].as_ptr() as _, 0); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&rb, 0, &out, 0, 256); + list.ResourceBarrier(&[transition(&out, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + list.SetComputeRoot32BitConstants(1, 3, [1u32, 0x1_0000, 0x6B00_0000].as_ptr() as _, 0); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&rb, 256, &out, 0, 256); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + // the 32-bit alias of the slice's tile (1 GiB + 64 KiB) through a copy (offsets below + // 4 GiB copy correctly): untouched, or did the slice wrap? + let rb2 = buf(&dev, 256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + alloc.Reset().unwrap(); + list.Reset(&alloc, None).unwrap(); + list.ResourceBarrier(&[transition(&big, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&rb2, 0, &big, GIB + TILE, 256); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 2).unwrap(); + crate::gpu::fence::wait(&fence, 2, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let w = std::slice::from_raw_parts(p as *const u32, 128).to_vec(); + rb.Unmap(0, None); + rb2.Map(0, None, Some(&mut p)).unwrap(); + let alias = std::slice::from_raw_parts(p as *const u32, 64).to_vec(); + rb2.Unmap(0, None); + let n = q.GetNumStoredMessages(); + println!("{name}: debug layer messages: {} at view creation, {} in all", after_views - before, n); + for i in 0..n { + let mut len = 0usize; + let _ = q.GetMessage(i, None, &mut len); + let mut b = vec![0u8; len]; + let m = b.as_mut_ptr() as *mut D3D12_MESSAGE; + if q.GetMessage(i, Some(m), &mut len).is_ok() { + let m = &*m; + println!(" [{:?}] {}", m.Severity, std::ffi::CStr::from_ptr(m.pDescription as _).to_string_lossy()); + } + } + let win_ok = (0..64).all(|l| w[l] == 0x5A00_0000 | l as u32); + let slice_ok = (0..64).all(|l| w[64 + l] == 0x6B00_0000 | l as u32); + let alias_clean = alias.iter().all(|&x| x == 0); + println!("4 GiB - 64 KiB raw view, top tile: {}", if win_ok { "ok" } else { "WRONG" }); + println!("1 GiB raw slice at FirstElement 5 GiB: read back {}, 32-bit alias tile {}", if slice_ok { "ok" } else { "WRONG" }, if alias_clean { "untouched" } else { "WRITTEN (the slice wrapped at 4 GiB)" }); + println!("first words: window {:#x}, slice {:#x}, alias {:#x}", w[0], w[64], alias[0]); + } +} diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index b72eda37e..1594acb56 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4488,7 +4488,8 @@ impl Em { } } if windows > 1 { - h = windowed(&h, windows); + let coherent = if matches!(self.opt.mode, Mode::Compute(_)) { "globallycoherent " } else { "" }; + h = windowed(&h, windows, self.opt.heap_windows.then_some(coherent)); } h } @@ -4820,7 +4821,9 @@ const LOADX4_ONE_WINDOW: &str = "uint4 xcl_loadx4(uint4 a) { return uint4(mem.Lo /// Several memory windows: every `mem.Method(` of the program (and of the preludes) becomes /// an accessor `xcl_mMethod(` that switches on `xcl_w` between `mem` and `mem1`.., whose /// definitions replace the placeholder. -fn windowed(h: &str, windows: u32) -> String { +/// `heap`: Some(storage class) – the accessors take window k from the descriptor heap +/// (`Options::heap_windows`) instead of switching over the root UAVs. +fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String { let mut out = String::with_capacity(h.len() + 8192); let mut rest = h; while let Some(i) = rest.find("mem.") { @@ -4838,11 +4841,11 @@ fn windowed(h: &str, windows: u32) -> String { } } out.push_str(rest); - out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows), 1) + out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows, heap), 1) } /// The accessor functions: one per `mem` method (and overload) the translator emits. -fn mem_accessors(windows: u32) -> String { +fn mem_accessors(windows: u32, heap: Option<&str>) -> String { let mut sigs: Vec<(&str, String, &str, &str)> = vec![ ("uint", "Load".into(), "uint a", "a"), ("uint2", "Load2".into(), "uint a", "a"), @@ -4867,6 +4870,17 @@ fn mem_accessors(windows: u32) -> String { } } let mut s = String::new(); + if let Some(coherent) = heap { + // one access: window k is descriptor MEM_HEAP_BASE + k (a window the program does not + // have reads window 0, as the switch's default did) + let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + (xcl_w < {windows}u ? xcl_w : 0u))]", super::MEM_HEAP_BASE); + let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ XCL_MW; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}"); + for (ret, name, params, args) in sigs { + let r = if ret == "void" { "" } else { "return " }; + let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ XCL_MW; {r}m.{name}({args}); }}"); + } + return s; + } let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_w) {{ "); for k in 1..windows { let _ = write!(s, "case {k}u: return uint4(mem{k}.Load(a.x), mem{k}.Load(a.y), mem{k}.Load(a.z), mem{k}.Load(a.w)); "); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 30c33e9b0..0575a7df4 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -61,6 +61,16 @@ pub use emit::mesh_passthrough; pub mod runner; #[cfg(test)] mod tests; +#[cfg(test)] +mod aperture_tests; + +/// First descriptor of the memory windows in the shader-visible heap (`Options::heap_windows`): +/// window k is raw UAV `MEM_HEAP_BASE + k`. +pub const MEM_HEAP_BASE: u32 = 0; + +/// Flag in a memory-windows count (`pso::mem_windows`, the translation caches' keys): +/// `Options::heap_windows`. `translate` takes it out of `mem_windows`. +pub const HEAP_WINDOWS: u32 = 0x100; pub mod upper_lanes; use std::collections::{BTreeMap, BTreeSet}; @@ -486,6 +496,11 @@ pub struct Options { /// then exactly the single-window form); 2..4 add `mem1`.. (u3..) and pick the window of /// every access from the high address bits pub mem_windows: u32, + /// with `mem_windows` > 1: reach window k through descriptor `MEM_HEAP_BASE + k` of the + /// shader-visible heap (a raw UAV of the window, `ResourceDescriptorHeap`) – one access per + /// site instead of a `switch` over the root UAVs `mem`, `mem1`.., which inlines every + /// access once per window (HANDOFF: twice the DXC + driver time with 4 windows) + pub heap_windows: bool, /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) pub structured: bool, @@ -493,7 +508,7 @@ pub struct Options { impl Default for Options { fn default() -> Self { - Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, structured: true } + Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true } } } @@ -1290,6 +1305,13 @@ fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> BTreeMap Result { + let normalized; + let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { + normalized = Options { mem_windows: opt.mem_windows & !HEAP_WINDOWS, heap_windows: true, ..opt.clone() }; + &normalized + } else { + opt + }; let mut insts: Vec = Vec::new(); let mut off = 0usize; while off + 4 <= code.len() { diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b0c31a5ed..1d50090ac 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -73,9 +73,24 @@ pub fn fspx(blob: &[u8]) -> Option> { Some(Fspx { threads, rsrc1: u32_at(head, 0x14)?, rsrc2: u32_at(head, 0x18)?, code: &code[..4 * (end + 1)] }) } -/// Memory windows of the title's unified memory (1 without it). +/// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when +/// shaders take them from the descriptor heap (`heap_windows`). pub fn mem_windows() -> u32 { - crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32) + let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); + if n > 1 && heap_windows() { + n | super::HEAP_WINDOWS + } else { + n + } +} + +/// Whether translated shaders reach the memory windows through the shared descriptor heap +/// (`Options::heap_windows`; descriptors `MEM_HEAP_BASE`.. made by `console_heap::set_window_views`) +/// instead of a `switch` over root UAVs. On unless `XCL_HEAP_WINDOWS=0` or the views could not +/// be made (no shared heap: then the switch, as before). +pub fn heap_windows() -> bool { + static ENV: OnceLock = OnceLock::new(); + *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").map_or(true, |v| v != "0")) && !crate::hle::d3d12x::console_heap::window_views_failed() } /// A static sampler of a translated program: (S#, comparison) – see `Translation`. diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 751699614..1c0f276b7 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1183,6 +1183,24 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result, Some(&raw_window_uav(size as u64)), h); + } + list.SetDescriptorHeaps(&[Some(dh.clone())]); list.SetComputeRootSignature(&gpu.rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); @@ -1212,6 +1230,20 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result D3D12_UNORDERED_ACCESS_VIEW_DESC { + let bytes = bytes.min((1u64 << 32) - 0x1_0000); + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: (bytes / 4) as u32, StructureByteStride: 0, CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_RAW }, + }, + } +} + /// Create a committed resource from a description (validation of decoded descriptors). pub fn try_create_texture(desc: &D3D12_RESOURCE_DESC) -> Result<(), String> { let mut g = GPU.lock().unwrap(); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index e609a34cd..9e4010d6e 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2837,6 +2837,17 @@ fn gpu_mesh_mode_reads_memory_windows() { /// accesses in window 0. #[test] fn gpu_memory_windows_above_4_gib() { + memory_windows_above_4_gib(false); +} + +/// The same program with the windows taken from the descriptor heap (`Options::heap_windows`): +/// same results, and no `switch` over windows in the HLSL. +#[test] +fn gpu_memory_windows_from_the_heap() { + memory_windows_above_4_gib(true); +} + +fn memory_windows_above_4_gib(heap: bool) { if !gpu_ready() { return; } @@ -2867,8 +2878,10 @@ fn gpu_memory_windows_above_4_gib() { let p = prog(&refs); let one = translate(&p, &Options::default()).unwrap(); assert!(!one.hlsl.contains("mem1") && !one.hlsl.contains("xcl_w =") && !one.hlsl.contains("xcl_m"), "one window: the single-window HLSL"); - let t = translate(&p, &on_gpu(Options { mem_windows: 2, ..Default::default() })).unwrap(); + let t = translate(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() })).unwrap(); assert!(t.hlsl.contains("RWByteAddressBuffer mem1 : register(u3)")); + assert_eq!(t.hlsl.contains("switch (xcl_w)"), !heap, "heap windows: no switch over windows"); + assert_eq!(t.hlsl.contains("ResourceDescriptorHeap[NonUniformResourceIndex(0u + (xcl_w"), heap); let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); let hi = |a: u64| (a >> 32) as u32; let mut st = KernelState::default(); diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index ae4985aac..36efedbbc 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -805,6 +805,7 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis /// arguments the console's way – compute or graphics) and the argument table in unified /// memory, u1 res, u2… the memory windows; then the pipeline. unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { + super::list_x::ensure_view_heap(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); let first = *windows.first().ok_or("unified memory is not open on the GPU")?; diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 176973ea2..e2599fc70 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -27,6 +27,7 @@ use std::sync::Mutex; +use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; /// bytes of a CBV/SRV/UAV slot (T# / V#) and of a sampler slot (S#) @@ -157,13 +158,46 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { inc: dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), heap, cap, - next: 0, + // the memory windows' raw UAVs (`set_window_views`) come first + next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_WINDOWS as u32, free: Vec::new(), }); } true } +static WINDOW_VIEWS_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Whether the memory windows could not be put in the shared heap (`set_window_views`): +/// translated shaders then switch over root UAVs (`pso::heap_windows`). +pub fn window_views_failed() -> bool { + WINDOW_VIEWS_FAILED.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The memory windows' buffers `(resource, bytes)` as raw UAVs at `MEM_HEAP_BASE + k` of the +/// shared heap, made now if need be (`Options::heap_windows`: shaders take window k from there). +/// A window without a buffer gets window 0's. False (and the shaders keep the switch): no +/// shared heap. +pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) -> bool { + let ok = !windows.is_empty() && windows[0].0 != 0 && shared_heap(dev) && { + let g = GLOBAL.lock().unwrap(); + let s = g.as_ref().unwrap(); + for k in 0..crate::gpu::uma::MAX_WINDOWS { + let (raw, bytes) = windows.get(k).copied().filter(|w| w.0 != 0).unwrap_or(windows[0]); + let raw = raw as *mut std::ffi::c_void; + let Some(r) = ID3D12Resource::from_raw_borrowed(&raw) else { continue }; + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (s.cpu + (crate::gpu::recomp::MEM_HEAP_BASE as u64 + k as u64) * s.inc as u64) as usize }; + s.dev.CreateUnorderedAccessView(r, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(bytes as u64)), at); + } + true + }; + if !ok { + WINDOW_VIEWS_FAILED.store(true, std::sync::atomic::Ordering::Relaxed); + crate::xlog_warn!("memory windows: not in the shared descriptor heap – translated shaders switch over the windows' root UAVs"); + } + ok +} + /// `count` descriptors of the shared heap: the index of the first. None: no shared heap, or /// no room left in it. fn reserve_global(count: u32) -> Option { diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index b92d75584..ca2f95b2d 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -666,6 +666,8 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let mut layout: Option> = None; let mut table: Vec = Vec::new(); let mut pso: Option<*const ConsolePso> = None; + // heap windows (`pso::heap_windows`): a dispatch needs the shared heap even when the list set none + let mut heaps_set = false; let chunks: Vec> = st.chunks.iter().map(|(c, used)| c[..*used].chunks(4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).collect()).collect(); 'chunks: for words in &chunks { let mut at = 0usize; @@ -691,6 +693,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { } } list.SetDescriptorHeaps(&heaps); + heaps_set = true; at += 2 + 2 * n; } else if w0 == TRANSITIONS_MARKER { let n = get(1) as usize; @@ -794,6 +797,12 @@ pub unsafe fn close(obj: *mut c_void) -> Result { Some(r) => list.SetComputeRootSignature(r), None => list.SetComputeRootSignature(rs.as_ref().ok_or("no XCL ABI root signature")?), } + if !heaps_set && crate::gpu::recomp::pso::heap_windows() { + if let Some(g) = super::console_heap::global_heap() { + list.SetDescriptorHeaps(&[Some(g)]); + heaps_set = true; + } + } list.SetComputeRootUnorderedAccessView(0, va(io_at)); list.SetComputeRootUnorderedAccessView(1, va(res_at)); for k in 0..4 { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 0370f303d..23d02e4b7 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1728,6 +1728,26 @@ pub(super) unsafe fn pc_heaps(n: u32, heaps: *const usize) -> Vec(this, 28)(this, 1, raw.as_ptr()); + } +} + /// console #32 SetDescriptorHeaps (PC #28) pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n: u32, heaps: *const usize) { const PC_SET_DESCRIPTOR_HEAPS: usize = 28; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index d8c7bfd1e..be721356e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -269,6 +269,13 @@ unsafe fn open_uma(device: &ID3D12Device) { w0_va ); *UMA_HEAPS.lock().unwrap() = heaps; + // shaders take the windows from the shared descriptor heap (`pso::heap_windows`) + if n > 1 && crate::gpu::recomp::pso::heap_windows() { + let views: Vec<(usize, usize)> = bufs.iter().enumerate().map(|(k, b)| (b.0, u.window(k).1)).collect(); + if super::console_heap::set_window_views(device, &views) { + crate::xlog_info!("D3D12.X: memory windows from the shared descriptor heap (no per-access switch)"); + } + } *UMA_BUFFER.lock().unwrap() = bufs; } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 5c3027d7b..f49a81b33 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -715,7 +715,10 @@ pub fn run(path: &Path, args: &[String]) -> i32 { if args.iter().any(|a| a == "--precompile") { let only = args.iter().position(|a| a == "--only").and_then(|i| args.get(i + 1)).map(|s| s.to_ascii_lowercase()); let pipelines = args.iter().any(|a| a == "--pipelines"); - return precompile(&input, opt("--limit").unwrap_or(usize::MAX), opt("--windows").unwrap_or(4) as u32, opt("--split").map(|v| v != 0), only.as_deref(), pipelines, t0); + // the runtime's key: heap windows unless `XCL_HEAP_WINDOWS=0` (`pso::mem_windows`) + let windows = opt("--windows").unwrap_or(4) as u32; + let windows = if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows }; + return precompile(&input, opt("--limit").unwrap_or(usize::MAX), windows, opt("--split").map(|v| v != 0), only.as_deref(), pipelines, t0); } let agg = analyze(&input, recomp_on, compile, iface_on); drop(input); @@ -837,9 +840,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let graphics_split = split.unwrap_or_else(recomp::runner::graphics_wave32); let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w)); println!( - "precompiling {n} shaders into {} ({} compile threads; {windows} memory windows{})", + "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), recomp::dxc::compile_threads(), + windows & !recomp::HEAP_WINDOWS, + if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" }, if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } ); std::thread::scope(|s| { From 864ce8e4805ea9af2219ae96ed5c583ba75db7b2 Mon Sep 17 00:00:00 2001 From: Remington Wilcox <129909388+RemingtonWilcox@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:29:22 -0800 Subject: [PATCH 2/6] Tests: heap windows in dispatch_on and the fake draw list - runner::dispatch_on: a PSO built by the backend hook uses the runtime's window count, so with heap windows its accesses go through the descriptor heap; every window slot is now a raw view of the test's memory (gpu_compute_e2e read zeros through LDS). - draw_indexed_x test: the fake list gets SetDescriptorHeaps (#28), which bind now calls when the list set no heap (it called a null slot). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/runner.rs | 20 +++++++++++++++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 2 ++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 1c0f276b7..036932e7b 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1340,7 +1340,25 @@ fn dispatch_with( transition(&mem_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), ]); - let _bound = bind_resources(dev, &list, &[], &[])?; + let bound = bind_resources(dev, &list, &[], &[])?; + // A PSO built by the backend's hook uses the runtime's window count: with heap windows + // (`Options::heap_windows`) its accesses go to ResourceDescriptorHeap[MEM_HEAP_BASE + w], + // so every window slot is a raw view of `mem` (no textures here to share the heap with). + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: super::MEM_HEAP_BASE + 4, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .map_err(e)?; + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + for k in 0..4usize { + let mut h = dh.GetCPUDescriptorHandleForHeapStart(); + h.ptr += (super::MEM_HEAP_BASE as usize + k) * inc; + dev.CreateUnorderedAccessView(&mem_buf, None::<&ID3D12Resource>, Some(&raw_window_uav(mem_bytes)), h); + } + list.SetDescriptorHeaps(&[Some(dh.clone()), Some(bound._heaps[1].clone())]); list.SetComputeRootSignature(rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 23d02e4b7..e188bde57 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2944,12 +2944,14 @@ mod tests { } unsafe extern "system" fn fake_noop_ptr(_this: *mut c_void, _p: *mut c_void) {} unsafe extern "system" fn fake_noop_uav(_this: *mut c_void, _slot: u32, _va: u64) {} + unsafe extern "system" fn fake_set_heaps(_this: *mut c_void, _n: u32, _heaps: *const usize) {} let mut orig_vt = [0usize; 64]; orig_vt[1] = fake_add_ref as usize; orig_vt[2] = fake_release as usize; orig_vt[13] = fake_draw_indexed as usize; orig_vt[25] = fake_noop_ptr as usize; // SetPipelineState + orig_vt[28] = fake_set_heaps as usize; // SetDescriptorHeaps (memory windows from the heap) orig_vt[30] = fake_noop_ptr as usize; // SetGraphicsRootSignature orig_vt[42] = fake_noop_uav as usize; // SetGraphicsRootUnorderedAccessView orig_vt[43] = fake_set_ib as usize; From 33c92ddda08bfadc2184fa93c677afe9a12f5fe9 Mon Sep 17 00:00:00 2001 From: Remington Wilcox <129909388+RemingtonWilcox@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:47:01 -0800 Subject: [PATCH 3/6] Heap windows reach a sparse window's last tile The window views stopped at 4 GiB - 64 KiB on the assumption that a window's last tile is never handed out. Sparse windows do hand it out (sparse_reserve / sparse_alloc; a reservation across two windows always covers it), and through the view it read zeros and dropped stores. The view is now 2^30 - 1 dwords, the largest byte size a 32-bit field holds (AMD's V# NUM_RECORDS): only the window's last dword stays out of reach. E1c (RTX 3090, debug layer): 4 GiB - 64 KiB view 0/64 lanes at the last tile; 2^30 - 1 dwords 64/64 there and 63/64 at the last 256 bytes; exactly 2^30 dwords 64/64 too, no debug-layer messages (AMD not measured). gpu_raw_window_view_reaches_its_top now checks the last tile and its last dwords. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/aperture_tests.rs | 149 ++++++++++++++++++-- crates/xcl/src/gpu/recomp/runner.rs | 10 +- 2 files changed, 145 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/aperture_tests.rs b/crates/xcl/src/gpu/recomp/aperture_tests.rs index 4ebe0889e..7a433e77b 100644 --- a/crates/xcl/src/gpu/recomp/aperture_tests.rs +++ b/crates/xcl/src/gpu/recomp/aperture_tests.rs @@ -307,14 +307,15 @@ fn gpu_aperture_structured_rows_above_4_gib() { } /// The heap-window form (`Options::heap_windows`) on a real sparse window: a 4 GiB reserved -/// buffer seen through `runner::raw_window_uav` (4 GiB − 64 KiB) reaches its last usable tile. +/// buffer seen through `runner::raw_window_uav` reaches its last tile, which the sparse windows +/// hand out (a reservation across two windows covers it), up to its last dword but one. #[test] fn gpu_raw_window_view_reaches_its_top() { let Some((dev, name)) = device() else { return }; if super::dxc::location().is_err() { return; } - let top = (4 * GIB) - 2 * TILE; // the last tile the view covers + let top = (4 * GIB) - TILE; // the window's last tile let src = r#" #define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), UAV(u0)" RWByteAddressBuffer outb : register(u0); @@ -322,11 +323,13 @@ RWByteAddressBuffer outb : register(u0); [numthreads(64, 1, 1)] void main(uint l : SV_GroupThreadID) { RWByteAddressBuffer w = ResourceDescriptorHeap[NonUniformResourceIndex(0u)]; - w.Store(0xFFFE0000u + 4u * l, 0x5A000000u | l); + w.Store(0xFFFF0000u + 4u * l, 0x5A000000u | l); w.Store(4u * l, 0xA5000000u | l); + if (l < 63u) w.Store(0xFFFFFF00u + 4u * l, 0x3C000000u | l); DeviceMemoryBarrier(); - outb.Store(8u * l, w.Load(0xFFFE0000u + 4u * l)); + outb.Store(8u * l, w.Load(0xFFFF0000u + 4u * l)); outb.Store(8u * l + 4u, w.Load(4u * l)); + outb.Store(512u + 4u * l, l < 63u ? w.Load(0xFFFFFF00u + 4u * l) : 0u); } "#; unsafe { @@ -365,8 +368,8 @@ void main(uint l : SV_GroupThreadID) { .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 1, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }) .unwrap(); dev.CreateUnorderedAccessView(&win, None::<&ID3D12Resource>, Some(&super::runner::raw_window_uav(4 * GIB)), dh.GetCPUDescriptorHandleForHeapStart()); - let out = buf(&dev, 512, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); - let rb = buf(&dev, 512 + 256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + let out = buf(&dev, 768, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb = buf(&dev, 768 + 256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap(); list.SetDescriptorHeaps(&[Some(dh.clone())]); @@ -377,8 +380,8 @@ void main(uint l : SV_GroupThreadID) { transition(&win, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), ]); - list.CopyBufferRegion(&rb, 0, &out, 0, 512); - list.CopyBufferRegion(&rb, 512, &win, top, 256); + list.CopyBufferRegion(&rb, 0, &out, 0, 768); + list.CopyBufferRegion(&rb, 768, &win, top, 256); list.Close().unwrap(); queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); @@ -386,12 +389,15 @@ void main(uint l : SV_GroupThreadID) { crate::gpu::fence::wait(&fence, 1, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); let mut q = std::ptr::null_mut(); rb.Map(0, None, Some(&mut q)).unwrap(); - let w = std::slice::from_raw_parts(q as *const u32, 192).to_vec(); + let w = std::slice::from_raw_parts(q as *const u32, 256).to_vec(); rb.Unmap(0, None); for l in 0..64usize { assert_eq!(w[2 * l], 0x5A00_0000 | l as u32, "{name}: lane {l}, the window's top tile through the heap view"); assert_eq!(w[2 * l + 1], 0xA500_0000 | l as u32, "{name}: lane {l}, the window's first tile"); - assert_eq!(w[128 + l], 0x5A00_0000 | l as u32, "{name}: lane {l}, the top tile in memory"); + assert_eq!(w[192 + l], 0x5A00_0000 | l as u32, "{name}: lane {l}, the top tile in memory"); + if l < 63 { + assert_eq!(w[128 + l], 0x3C00_0000 | l as u32, "{name}: lane {l}, the window's last dwords"); + } } } } @@ -749,3 +755,126 @@ void main(uint l : SV_GroupThreadID) { println!("first words: window {:#x}, slice {:#x}, alias {:#x}", w[0], w[64], alias[0]); } } + +/// Experiment E1c, run alone (debug layer): can a heap view reach a sparse window's last +/// 64 KiB tile, which the windows hand out? Over a 4 GiB reserved window with only its last +/// tile mapped: (0) the 4 GiB - 64 KiB view, (1) 2^30 - 1 elements (4 GiB - 4 bytes, the +/// largest byte size a 32-bit field holds), (2) exactly 2^30 elements, (3) a 64 KiB view of +/// the last tile alone. Each slot is written and read at the start of the tile and at its +/// last dwords. +/// `cargo test --release -p xcl --lib e1c_window_view_last_tile -- --ignored --nocapture`. +#[test] +#[ignore] +fn e1c_window_view_last_tile() { + unsafe { + match crate::gpu::agility::configuration_interface::(&CLSID_D3D12Debug) { + Ok(d) => d.EnableDebugLayer(), + Err(e) => { + println!("no debug layer: {e}"); + return; + } + } + } + let Some((dev, name)) = device() else { return }; + let src = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), UAV(u0), RootConstants(num32BitConstants=4, b0)" +RWByteAddressBuffer outb : register(u0); +cbuffer C : register(b0) { uint slot; uint at; uint tag; uint pad; }; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint l : SV_GroupThreadID) { + RWByteAddressBuffer w = ResourceDescriptorHeap[NonUniformResourceIndex(slot)]; + w.Store(at + 4u * l, tag | l); + DeviceMemoryBarrier(); + outb.Store(4u * l, w.Load(at + 4u * l)); +} +"#; + unsafe { + let dxil = super::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, ..Default::default() }) + .unwrap(); + let q: ID3D12InfoQueue = dev.cast().expect("info queue (debug layer on)"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 4 * GIB, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut r).unwrap(); + let win = r.unwrap(); + let mut heap: Option = None; + dev.CreateHeap(&D3D12_HEAP_DESC { SizeInBytes: TILE, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }, &mut heap).unwrap(); + let heap = heap.unwrap(); + let c = D3D12_TILED_RESOURCE_COORDINATE { X: ((4 * GIB - TILE) / TILE) as u32, ..Default::default() }; + let s = D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }; + queue.UpdateTileMappings(&win, 1, Some(&c), Some(&s), &heap, 1, Some(&D3D12_TILE_RANGE_FLAG_NONE), Some(&0), Some(&1), D3D12_TILE_MAPPING_FLAG_NONE); + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 4, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }) + .unwrap(); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let h0 = dh.GetCPUDescriptorHandleForHeapStart(); + let view = |first: u64, n: u32| D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Buffer: D3D12_BUFFER_UAV { FirstElement: first, NumElements: n, StructureByteStride: 0, CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_RAW } }, + }; + let views = [view(0, ((4 * GIB - TILE) / 4) as u32), view(0, (1u32 << 30) - 1), view(0, 1u32 << 30), view((4 * GIB - TILE) / 4, (TILE / 4) as u32)]; + let mut created = Vec::new(); + for (k, v) in views.iter().enumerate() { + let before = q.GetNumStoredMessages(); + dev.CreateUnorderedAccessView(&win, None::<&ID3D12Resource>, Some(v), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h0.ptr + k * inc }); + created.push(q.GetNumStoredMessages() - before); + } + // (slot, offset in the view): the first dwords of the tile, then its last dwords + let top = 0xFFFF_0000u32; + let runs: Vec<(u32, u32)> = (0..3u32).flat_map(|k| [(k, top), (k, 0xFFFF_FF00)]).chain([(3, 0), (3, 0xFF00)]).collect(); + let out = buf(&dev, 256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb = buf(&dev, 256 * runs.len() as u64, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap(); + list.SetDescriptorHeaps(&[Some(dh.clone())]); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, out.GetGPUVirtualAddress()); + for (i, &(slot, at)) in runs.iter().enumerate() { + list.SetComputeRoot32BitConstants(1, 3, [slot, at, (0x10 + i as u32) << 24].as_ptr() as _, 0); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&rb, 256 * i as u64, &out, 0, 256); + list.ResourceBarrier(&[transition(&out, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + } + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let w = std::slice::from_raw_parts(p as *const u32, 64 * runs.len()).to_vec(); + rb.Unmap(0, None); + let names = ["4 GiB - 64 KiB", "2^30 - 1 elements", "2^30 elements", "last tile alone"]; + println!("{name}: debug-layer messages at creation per view: {created:?}"); + for (i, &(slot, at)) in runs.iter().enumerate() { + let good = (0..64).filter(|&l| w[64 * i + l] == ((0x10 + i as u32) << 24) | l as u32).count(); + println!(" {:<18} at {at:#010x}: {good}/64 lanes read back", names[slot as usize]); + } + let n = q.GetNumStoredMessages(); + for i in 0..n.min(10) { + let mut len = 0usize; + let _ = q.GetMessage(i, None, &mut len); + let mut b = vec![0u8; len]; + let m = b.as_mut_ptr() as *mut D3D12_MESSAGE; + if q.GetMessage(i, Some(m), &mut len).is_ok() { + println!(" [{:?}] {}", (*m).Severity, std::ffi::CStr::from_ptr((*m).pDescription as _).to_string_lossy()); + } + } + } +} diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 036932e7b..f282a9130 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1230,11 +1230,13 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result D3D12_UNORDERED_ACCESS_VIEW_DESC { - let bytes = bytes.min((1u64 << 32) - 0x1_0000); + let bytes = bytes.min((1u64 << 32) - 4); D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, ViewDimension: D3D12_UAV_DIMENSION_BUFFER, From 8b4e3983dfdf27afe5e865e0a60982e2266001ce Mon Sep 17 00:00:00 2001 From: Remington Wilcox <129909388+RemingtonWilcox@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:47:01 -0800 Subject: [PATCH 4/6] SetDescriptorHeaps(0, NULL): the shared heap is bound again before a translated draw Unbinding every heap left the list's record of bound heaps as it was, so ensure_view_heap saw a heap and did not bind the shared one: the next translated draw or dispatch read the memory windows (ResourceDescriptorHeap[0..3]) with no heap bound. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/list_x.rs | 55 ++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index e188bde57..6d4dc2bd0 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1752,11 +1752,15 @@ pub(super) unsafe fn ensure_view_heap(this: *mut c_void) { pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n: u32, heaps: *const usize) { const PC_SET_DESCRIPTOR_HEAPS: usize = 28; let f = pc::(this, PC_SET_DESCRIPTOR_HEAPS); - if heaps.is_null() || super::console_heap::global_heap().is_none() { - if !heaps.is_null() { - let given = std::slice::from_raw_parts(heaps, n as usize).to_vec(); - with_bindings(this, |b| b.heaps = given); - } + if heaps.is_null() || n == 0 { + // no heaps: nothing bound any more (`ensure_view_heap` binds the shared heap again + // before a translated draw or dispatch reads the memory windows from it) + with_bindings(this, |b| b.heaps.clear()); + return f(this, n, heaps); + } + if super::console_heap::global_heap().is_none() { + let given = std::slice::from_raw_parts(heaps, n as usize).to_vec(); + with_bindings(this, |b| b.heaps = given); return f(this, n, heaps); } let h = pc_heaps(n, heaps); @@ -2919,6 +2923,47 @@ mod tests { }); } + /// SetDescriptorHeaps(0, NULL) unbinds every heap: the list must not still count the + /// shared heap as bound, or a translated draw after it reads the memory windows + /// (`ResourceDescriptorHeap[0..3]`) from no heap at all. + #[test] + fn unbinding_all_heaps_lets_the_shared_heap_be_bound_again() { + #[repr(C)] + struct FakeList { + vt: *const usize, + calls: Mutex>>, + } + unsafe extern "system" fn fake_set_heaps(this: *mut c_void, n: u32, heaps: *const usize) { + let v = if heaps.is_null() { Vec::new() } else { std::slice::from_raw_parts(heaps, n as usize).to_vec() }; + (*(this as *const FakeList)).calls.lock().unwrap().push(v); + } + let mut orig_vt = [0usize; 64]; + orig_vt[28] = fake_set_heaps as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeList { vt: unsafe { ext_vt.as_ptr().add(1) }, calls: Mutex::new(Vec::new()) }); + let list = &*fake as *const FakeList as *mut c_void; + with_bindings(list, |b| b.heaps = vec![0x1234_0000]); + unsafe { + set_descriptor_heaps_x(list, 0, std::ptr::null()); + let mut bound = Vec::new(); + with_bindings(list, |b| bound = b.heaps.clone()); + assert!(bound.is_empty(), "no heap is bound after SetDescriptorHeaps(0, NULL)"); + assert_eq!(fake.calls.lock().unwrap().last(), Some(&Vec::new())); + ensure_view_heap(list); + with_bindings(list, |b| bound = b.heaps.clone()); + match super::super::console_heap::global_heap() { + Some(g) if crate::gpu::recomp::pso::heap_windows() => { + assert_eq!(bound, vec![g.as_raw() as usize], "the shared heap is bound again"); + assert_eq!(fake.calls.lock().unwrap().last(), Some(&vec![g.as_raw() as usize])); + } + _ => assert!(bound.is_empty()), + } + } + LISTS.lock().unwrap().as_mut().map(|m| m.remove(&(list as usize))); + } + #[test] fn draw_indexed_x_routes_through_bind_and_restores_index_buffer() { #[repr(C)] From 41d4506bb58e5d8d19030a548c39dbc5411f1938 Mon Sep 17 00:00:00 2001 From: Remington Wilcox <129909388+RemingtonWilcox@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:53:03 -0800 Subject: [PATCH 5/6] Heap windows: a pipeline the driver refuses with E_OUTOFMEMORY is built in the switch form NVIDIA 616.92 (RTX 5070 Ti, reported in #156) refuses some big programs whose descriptor-heap index depends on the memory window with E_OUTOFMEMORY, and builds the same programs in the switch form. A translated compute, graphics, mesh or GS pipeline whose driver call fails that way with heap windows is now translated again in the switch form (other cache keys; same root signature and binds) and built from that before the stand-in or the error path. Test: heap_window_out_of_memory_falls_back_to_the_switch_form injects the refusals through the CreateComputePipelineState hook, then dispatches the rebuilt pipeline and checks every thread's output. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/pso.rs | 21 +++++++- crates/xcl/src/hle/d3d12x/real.rs | 75 +++++++++++++++++++++++++++-- crates/xcl/tests/gpu_compute_e2e.rs | 42 ++++++++++++++++ 3 files changed, 133 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 1d50090ac..f9844b559 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -77,13 +77,32 @@ pub fn fspx(blob: &[u8]) -> Option> { /// shaders take them from the descriptor heap (`heap_windows`). pub fn mem_windows() -> u32 { let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); - if n > 1 && heap_windows() { + if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) { n | super::HEAP_WINDOWS } else { n } } +thread_local! { + /// this thread translates in the switch form (`in_switch_form`) + static SWITCH_FORM: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Run `f` with this thread's translations in the switch form over root UAVs (`mem_windows` +/// without `HEAP_WINDOWS`, so other cache keys): for a pipeline the driver would not build with +/// heap windows. The root signature and the binds are the same for both forms. +pub fn in_switch_form(f: impl FnOnce() -> R) -> R { + struct Restore(bool); + impl Drop for Restore { + fn drop(&mut self) { + SWITCH_FORM.with(|s| s.set(self.0)); + } + } + let _restore = Restore(SWITCH_FORM.with(|s| s.replace(true))); + f() +} + /// Whether translated shaders reach the memory windows through the shared descriptor heap /// (`Options::heap_windows`; descriptors `MEM_HEAP_BASE`.. made by `console_heap::set_window_views`) /// instead of a `switch` over root UAVs. On unless `XCL_HEAP_WINDOWS=0` or the views could not diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index be721356e..407bbec8c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -33,7 +33,7 @@ use windows_sys::core::GUID; use super::layout::{self, Iface}; use crate::stubs; -use crate::util::{HRESULT, E_INVALIDARG, E_NOINTERFACE, S_FALSE, S_OK}; +use crate::util::{HRESULT, E_INVALIDARG, E_NOINTERFACE, E_OUTOFMEMORY, S_FALSE, S_OK}; const DLL: &str = "d3d12_xs.dll"; const EXTRA_SLOTS: usize = 64; @@ -2938,10 +2938,10 @@ fn note_fallback(what: &str, hr: HRESULT, ok: bool) { type PsoFn = unsafe extern "system" fn(*mut c_void, *const c_void, *const GUID, *mut *mut c_void) -> HRESULT; unsafe fn finish_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let mut hr = f(this, desc, riid, ppv); + let mut hr = driver_pso(f, this, desc, riid, ppv); if hr == E_NOINTERFACE { let iid = pc_iid(Kind::PipelineState); - hr = f(this, desc, &iid, ppv); + hr = driver_pso(f, this, desc, &iid, ppv); } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { adopt(*ppv, Kind::PipelineState); @@ -2949,6 +2949,57 @@ unsafe fn finish_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *co hr } +thread_local! { + /// the driver ran out of memory on a pipeline with heap windows (`with_switch_fallback`) + static HEAP_WINDOW_OOM: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// heap-window driver calls still to fail with E_OUTOFMEMORY (`inject_heap_window_oom`) +static INJECTED_OOM: AtomicU64 = AtomicU64::new(0); +/// pipelines built in the switch form after the driver refused them with heap windows +static SWITCH_FORM_RETRIES: AtomicU64 = AtomicU64::new(0); + +/// Tests: the next `n` driver pipeline calls with heap windows fail with E_OUTOFMEMORY without +/// reaching the driver (0 stops it), as NVIDIA 616.92 refuses some big retail programs (#156). +#[doc(hidden)] +pub fn inject_heap_window_oom(n: u64) { + INJECTED_OOM.store(n, Ordering::SeqCst); +} + +/// Pipelines built in the switch form because the driver refused them with heap windows. +pub fn switch_form_retries() -> u64 { + SWITCH_FORM_RETRIES.load(Ordering::Relaxed) +} + +/// A driver pipeline call; E_OUTOFMEMORY while this thread translates with heap windows is +/// noted for `with_switch_fallback`. +unsafe fn driver_pso(f: PsoFn, this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let heap = crate::gpu::recomp::pso::mem_windows() & crate::gpu::recomp::HEAP_WINDOWS != 0; + let injected = heap && INJECTED_OOM.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)).is_ok(); + let hr = if injected { E_OUTOFMEMORY } else { f(this, desc, riid, ppv) }; + if hr == E_OUTOFMEMORY && heap { + HEAP_WINDOW_OOM.with(|o| o.set(true)); + } + hr +} + +/// Build a translated pipeline (`build`: a `translated_*` path); when the driver ran out of +/// memory on it with heap windows, translate it again in the switch form and build that. +/// NVIDIA 616.92 refuses some big programs whose heap index depends on the window with +/// E_OUTOFMEMORY in under a second, and builds the same programs in the switch form (#156). +fn with_switch_fallback(mut build: impl FnMut() -> R) -> R { + HEAP_WINDOW_OOM.with(|o| o.set(false)); + let r = build(); + if !HEAP_WINDOW_OOM.with(|o| o.replace(false)) { + return r; + } + let n = SWITCH_FORM_RETRIES.fetch_add(1, Ordering::Relaxed); + if n < 5 || n % 100 == 0 { + crate::xlog_warn!("D3D12.X: the driver ran out of memory on a pipeline with heap windows – building it in the switch form ({} so far)", n + 1); + } + crate::gpu::recomp::pso::in_switch_form(build) +} + thread_local! { /// translation errors noted during a cached-only attempt (`attempt`) static ATTEMPT_NOTES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; @@ -2966,6 +3017,10 @@ fn attempt(f: impl FnOnce() -> R) -> (R, bool) { } fn note_translation_error(e: String) { + // a refusal `with_switch_fallback` builds again in the switch form (it says so itself) + if HEAP_WINDOW_OOM.with(|o| o.get()) { + return; + } if crate::gpu::recomp::dxc::in_cached_only() { ATTEMPT_NOTES.with(|n| n.borrow_mut().push(e)); return; @@ -3106,6 +3161,10 @@ fn wait_for_commit() { } unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { + with_switch_fallback(|| translated_compute_pso_once(this, f, desc, riid, ppv)) +} + +unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return None; @@ -3159,6 +3218,10 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi } unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) +} + +unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return None; @@ -3697,7 +3760,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: cdesc.CS = bytecode(&tp.cs); let iid = pc_iid(Kind::PipelineState); let mut compute: *mut c_void = std::ptr::null_mut(); - let hc = fc(this, &cdesc as *const _ as *const c_void, &iid, &mut compute); + let hc = driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute); if hc < 0 || compute.is_null() { note_translation_error(format!("the driver rejected the compute pass of the console {kind} ({hc:#x})")); let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(*ppv as *const *const usize)).add(2)); @@ -3717,6 +3780,10 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: /// CreatePipelineState with a console MS: Some(hr) when it was a console mesh pipeline /// (translated, or E_INVALIDARG – console bytecode must not reach the driver). unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + with_switch_fallback(|| translated_mesh_stream_once(this, desc, riid, ppv)) +} + +unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { use crate::gpu::recomp::pso::{console_mesh, is_console}; if !crate::gpu::shader::readable(desc as usize, 16) { return None; diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 08a1233dc..ea660d6eb 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -128,7 +128,12 @@ fn console_wave64_compute_through_the_pso_hook_dispatch_and_read_back() { let raw = real::device_raw(); let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }.unwrap().clone(); println!("backend device: {}", real::stats().adapter); + mirror_program_through_the_hook(&dev); +} +/// Hand the wave64 mirror program to the CreateComputePipelineState hook, dispatch the +/// pipeline it built and check every thread's output. +fn mirror_program_through_the_hook(dev: &ID3D12Device) { // user SGPRs 2, TGID_X + TGID_Y, thread ids v0 + v1 let blob = console_cs(&program(), 2 << 1 | 1 << 7 | 1 << 8 | 1 << 11, [16, 8, 1]); assert!(xcl::gpu::xbox::is_xbox(&blob), "expected a console container"); @@ -175,6 +180,43 @@ fn console_wave64_compute_through_the_pso_hook_dispatch_and_read_back() { } } +/// A driver that refuses a pipeline with heap windows (E_OUTOFMEMORY, as NVIDIA 616.92 does +/// with some big retail programs, #156) gets the program again in the switch form, and the +/// pipeline from it runs correctly. The refusals are injected (`real::inject_heap_window_oom`). +#[test] +fn heap_window_out_of_memory_falls_back_to_the_switch_form() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if xcl::gpu::recomp::dxc::location().is_err() { + println!("no DXC – skipping"); + runner::skip_test("no DXC"); + return; + } + if xcl::hle::d3d12x::backend() != xcl::hle::d3d12x::Backend::Real { + println!("no real D3D12 device – skipping"); + runner::skip_test("no GPU"); + return; + } + let raw = real::device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }.unwrap().clone(); + if xcl::gpu::recomp::pso::mem_windows() & xcl::gpu::recomp::HEAP_WINDOWS == 0 { + println!("no heap windows (XCL_HEAP_WINDOWS=0 or no shared heap) – skipping"); + runner::skip_test("no heap windows"); + return; + } + struct StopInjecting; + impl Drop for StopInjecting { + fn drop(&mut self) { + real::inject_heap_window_oom(0); + } + } + let _stop = StopInjecting; + // every heap-window build fails, also the background one behind a stand-in + real::inject_heap_window_oom(u64::MAX); + let before = real::switch_form_retries(); + mirror_program_through_the_hook(&dev); + assert!(real::switch_form_retries() > before, "the pipeline was not rebuilt in the switch form"); +} + /// Cold DXIL cache: `CreateComputePipelineState` returns a stand-in immediately and compiles /// the real compute PSO on the background worker. The real PSO (and NOT the stand-in) must be /// registered in `TRANSLATED_COMPUTE` once the background build completes. From c74b03a08c9666de4e1c7f5433dee386765c4eb8 Mon Sep 17 00:00:00 2001 From: Remington Wilcox <129909388+RemingtonWilcox@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:08:27 -0800 Subject: [PATCH 6/6] Physical pages: homes released under AWAY, a freed page's home given back at once FreeTitlePhysicalPages dropped AWAY before it released a block's home; with plain-memory homes (MEM_RELEASE) a map, read or write of those pages on another thread could reach memory released under it. AWAY now stays held across the PHYS_BLOCKS section (the order AWAY -> PHYS_BLOCKS, as in the map calls). A page freed while its block lives on gives its lazy home (sparse window or plain memory) back at once instead of when the whole block goes. unmap_away looks the page's home up once. Tests: a_freed_page_gives_its_home_back, physical_pages_from_several_threads. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/kernelx.rs | 84 +++++++++++++++++++++++++++++++++-- 1 file changed, 80 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 690a5f038..3b80d26a8 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -874,9 +874,10 @@ unsafe fn unmap_away(away: &mut Away, at: usize) { return; } // (a home this call has not given back yet is still committed) + let own = page_home(page); let pending = away.gone.len(); - away.gone.retain(|&h| Some(h) != page_home(page)); - let home = if away.gone.len() < pending { page_home(page) } else { page_home(page).and_then(|h| home_again(h)) }; + away.gone.retain(|&h| Some(h) != own); + let home = if away.gone.len() < pending { own } else { own.and_then(|h| home_again(h)) }; if let Some(home) = home { std::ptr::copy_nonoverlapping(at as *const u8, home as *mut u8, PHYS_PAGE); } @@ -931,8 +932,12 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } - // freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes - if let Some(away) = AWAY.lock().unwrap().as_mut() { + // freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes. + // `AWAY` stays held while the homes go (the order AWAY → PHYS_BLOCKS, as in the map calls): + // a map, read or write of these pages on another thread must not reach a home released + // under it (a plain home is MEM_RELEASEd). + let mut held = AWAY.lock().unwrap(); + if let Some(away) = held.as_mut() { for i in 0..n { if let Some(at) = away.page.remove(&*arr.add(i)) { away.at.remove(&at); @@ -958,8 +963,20 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: } else { mem::VirtualFree(home as *mut c_void, 0, mem::MEM_RELEASE); } + } else { + // the block lives on: the freed page's home gives its memory back now (a lazy home + // is committed again when the page number is used: `home_again`) + let at = home + (page - first) * PHYS_PAGE; + if lazy_home(at) && committed_page(at) { + if u.is_sparse(at) { + crate::hle::d3d12x::sparse::decommitted(at, PHYS_PAGE); + } + mem::VirtualFree(at as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT); + } } } + drop(g); + drop(held); 1 } @@ -1662,6 +1679,65 @@ mod tests { } } + /// Freeing one page of a block that lives on gives that page's home back at once (a lazy + /// home: a sparse window's or plain memory); its sibling keeps its home and contents. + #[test] + fn a_freed_page_gives_its_home_back() { + unsafe { + if crate::gpu::uma::get().is_none() { + return; + } + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let homes = [page_home(pages[0]).unwrap(), page_home(pages[1]).unwrap()]; + if !lazy_home(homes[0]) { + return; // a coherent-window home is committed as a whole + } + assert!(write_physical_pages(&pages, 0, &[1u8; 2 * PHYS_PAGE])); + assert!(committed_page(homes[0]) && committed_page(homes[1])); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr()), 1); + assert!(!committed_page(homes[0]), "the freed page's home is decommitted"); + assert!(committed_page(homes[1]) && page_home(pages[1]) == Some(homes[1]), "its sibling stays"); + let mut back = [0u8; 4]; + assert!(read_physical_pages(&pages[1..], 0, &mut back) && back == [1; 4]); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr().add(1)), 1); + assert!(page_home(pages[1]).is_none()); + } + } + + /// Allocating, mapping, reading and freeing from several threads at once: + /// `FreeTitlePhysicalPages` holds `AWAY` while it releases homes, so no thread resolves a + /// page to a home being released. + #[test] + fn physical_pages_from_several_threads() { + if crate::gpu::uma::get().is_none() { + return; + } + let threads: Vec<_> = (0..4) + .map(|t| { + std::thread::spawn(move || unsafe { + for k in 0..64u32 { + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let tag = (t << 16 | k).to_le_bytes(); + assert!(write_physical_pages(&pages, 8, &tag)); + let r = MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, pages.as_mut_ptr()); + assert!(!r.is_null()); + let mut back = [0u8; 4]; + assert!(read_physical_pages(&pages, 8, &mut back)); + assert_eq!(back, tag); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + } + #[test] fn physical_pages_in_uma() { unsafe {