From fe7d70bc3fd1ba667ca970eb329182a15f488dd5 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/4] Recompiler: memory windows from the descriptor heap, no per-access switch With more than one memory window every memory access of a translated shader was inlined once per window: a switch over the root UAVs mem, mem1.. Now window k is also a raw UAV at MEM_HEAP_BASE + k of the shared shader-visible heap, and an access is one ResourceDescriptorHeap load or store. - Options::heap_windows, and the HEAP_WINDOWS flag in the windows count, so that the translation and DXIL cache keys differ. Opt-in: on with XCL_HEAP_WINDOWS=1, unless the views could not be made (then the switch, as before). Off by default: two NVIDIA setups failed with it in review (the driver's compiler ending the process; a device removal when the views are made on an 8 GB card) that other machines do not show. - console_heap: the first 4 descriptors of the shared heap are the windows' raw views, 2^30 - 1 dwords at most: a sparse window's last 64 KiB tile is reachable, only the window's last dword is not. - Lists bind the shared heap before an ABI dispatch or draw when they set none. - xcl shaders --precompile uses the same key. - Tests: gpu_memory_windows_from_the_heap (the windows test in the heap form), gpu_raw_window_view_reaches_its_top (the view on a 4 GiB reserved buffer); the runner and the fake draw list bind the heap. - The windows' views are made after the shared heap's lock is released: the device may be an adopted one whose UAV hook takes the heaps' lock, which other paths take first (found and fixed by anes66 in review; test window_views_do_not_hold_global_during_device_calls). From #187 by Remington Wilcox (c3fb89e, 864ce8e, 33c92dd), closed without being merged: carried onto current main without that PR's aperture experiments and compile-time bench. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 Co-Authored-By: anes66 <37009523+anes66@users.noreply.github.com> --- crates/xcl/src/gpu/recomp/emit.rs | 26 ++- .../xcl/src/gpu/recomp/heap_window_tests.rs | 163 ++++++++++++++++++ crates/xcl/src/gpu/recomp/mod.rs | 24 ++- crates/xcl/src/gpu/recomp/pso.rs | 21 ++- crates/xcl/src/gpu/recomp/runner.rs | 54 +++++- crates/xcl/src/gpu/recomp/tests.rs | 29 +++- crates/xcl/src/hle/d3d12x/bind.rs | 1 + crates/xcl/src/hle/d3d12x/console_heap.rs | 86 ++++++++- crates/xcl/src/hle/d3d12x/console_list.rs | 9 + crates/xcl/src/hle/d3d12x/list_x.rs | 22 +++ crates/xcl/src/hle/d3d12x/real.rs | 7 + crates/xcl/src/shaders.rs | 9 +- 12 files changed, 438 insertions(+), 13 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/heap_window_tests.rs diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 216240bd2..8888caeda 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4703,7 +4703,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 } @@ -5092,7 +5093,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.") { @@ -5110,14 +5113,16 @@ 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. /// Only explicit windows `0..windows` touch GPU buffers; any out-of-range `xcl_w` hits /// `default` (reads return 0, stores/atomics are dropped and zero their `out` parameter) so /// out-of-UMA pointers can never wrap onto live memory windows. -fn mem_accessors(windows: u32) -> String { +/// `heap`: Some(storage class) – window k is taken from the descriptor heap +/// (`Options::heap_windows`) and the same rule is one comparison before the access. +fn mem_accessors(windows: u32, heap: Option<&str>) -> String { let mut sigs: Vec<(&str, String, &str, &str, &str)> = vec![ ("uint", "Load".into(), "uint a", "a", "return 0u;"), ("uint2", "Load2".into(), "uint a", "a", "return uint2(0u, 0u);"), @@ -5142,6 +5147,19 @@ 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; an `xcl_w` outside the windows + // does what the switch's `default` does + let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + xcl_w)]", super::MEM_HEAP_BASE); + let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] if (xcl_w >= {windows}u) {{ return uint4(0u, 0u, 0u, 0u); }} 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, def) in sigs { + let r = if ret == "void" { "" } else { "return " }; + // (the switch's `break` leaves the accessor) + let outside = def.replace("break;", "return;"); + let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ [branch] if (xcl_w >= {windows}u) {{ {outside} }} XCL_MW; {r}m.{name}({args}); }}"); + } + return s; + } let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_w) {{ "); let _ = write!(s, "case 0u: return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); "); for k in 1..windows { diff --git a/crates/xcl/src/gpu/recomp/heap_window_tests.rs b/crates/xcl/src/gpu/recomp/heap_window_tests.rs new file mode 100644 index 000000000..0c8abb3bf --- /dev/null +++ b/crates/xcl/src/gpu/recomp/heap_window_tests.rs @@ -0,0 +1,163 @@ +//! Memory windows from the descriptor heap (`Options::heap_windows`): the raw view a window gets +//! (`runner::raw_window_uav`) on a real 4 GiB reserved buffer. + +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; + +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 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))) + } +} + +/// The heap-window form (`Options::heap_windows`) on a real sparse window: a 4 GiB reserved +/// 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 { + super::runner::skip_test("no GPU"); + return; + }; + if super::dxc::location().is_err() { + super::runner::skip_test("no DXC"); + return; + } + 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); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint l : SV_GroupThreadID) { + RWByteAddressBuffer w = ResourceDescriptorHeap[NonUniformResourceIndex(0u)]; + 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(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 { + 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; + if let Err(e) = dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut win) { + // a software adapter (the CI's) makes no 4 GiB reserved buffer + println!("{name}: no 4 GiB reserved buffer ({e})"); + super::runner::skip_test("no GPU"); + return; + } + 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, 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())]); + 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, 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(); + 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).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[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"); + } + } + } +} diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 0f4a9049d..82876f01d 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 heap_window_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}; @@ -492,6 +502,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, @@ -499,7 +514,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 } } } @@ -1357,6 +1372,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 3fa375577..8568361b1 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -73,9 +73,26 @@ 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. Opt-in: on with `XCL_HEAP_WINDOWS=1`, unless the views +/// could not be made (no shared heap: then the switch, as before). Off by default: two NVIDIA +/// setups failed with it (the driver's compiler ending the process; a device removal when the +/// views are made on an 8 GB card) that other machines do not show. +pub fn heap_windows() -> bool { + static ENV: OnceLock = OnceLock::new(); + *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !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 c9748ab79..6876e48f3 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1303,6 +1303,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()); @@ -1332,6 +1350,22 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result D3D12_UNORDERED_ACCESS_VIEW_DESC { + let bytes = bytes.min((1u64 << 32) - 4); + 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(); @@ -1428,7 +1462,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/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 5a8d73539..56d71f0d1 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3183,6 +3183,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; } @@ -3213,8 +3224,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(); @@ -3256,6 +3269,17 @@ fn gpu_memory_windows_above_4_gib() { /// on `global_load`/`global_store` updates the target window accurately. #[test] fn gpu_memory_windows_reject_out_of_uma_aliasing() { + memory_windows_reject_out_of_uma_aliasing(false); +} + +/// The same with the windows taken from the descriptor heap (`Options::heap_windows`): an +/// address outside them reads 0 and drops its stores and atomics there too. +#[test] +fn gpu_heap_windows_reject_out_of_uma_aliasing() { + memory_windows_reject_out_of_uma_aliasing(true); +} + +fn memory_windows_reject_out_of_uma_aliasing(heap: bool) { if !gpu_ready() { return; } @@ -3309,7 +3333,8 @@ fn gpu_memory_windows_reject_out_of_uma_aliasing() { ]; let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); let p = prog(&refs); - 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_eq!(t.hlsl.contains("switch (xcl_w)"), !heap); let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); let mut st = KernelState::default(); diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index e0c1518fa..0ab287644 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -854,6 +854,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..0aea5c0ee 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,50 @@ 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 (device, cpu, inc) = { + let g = GLOBAL.lock().unwrap(); + let s = g.as_ref().unwrap(); + (s.dev.clone(), s.cpu, s.inc) + }; + // The device may be adopted: its UAV hook re-enters descriptor bookkeeping. + 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: (cpu + (crate::gpu::recomp::MEM_HEAP_BASE as u64 + k as u64) * inc as u64) as usize }; + device.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 { @@ -504,6 +542,52 @@ mod tests { assert!(free.is_empty()); } + #[test] + fn window_views_do_not_hold_global_during_device_calls() { + const CHILD: &str = "XCL_TEST_WINDOW_VIEWS_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::window_views_do_not_hold_global_during_device_calls", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use std::ffi::c_void; + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + static UNLOCKED: AtomicBool = AtomicBool::new(true); + static CALLS: AtomicU32 = AtomicU32::new(0); + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn create_uav(_this: *mut c_void, _resource: *mut c_void, _counter: *mut c_void, _desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, _at: D3D12_CPU_DESCRIPTOR_HANDLE) { + // The adopted device hook can re-enter descriptor bookkeeping. + UNLOCKED.fetch_and(GLOBAL.try_lock().is_ok(), Ordering::Relaxed); + CALLS.fetch_add(1, Ordering::Relaxed); + } + let mut vt = [0usize; 20]; + vt[1] = retain as usize; + vt[2] = retain as usize; + vt[19] = create_uav as usize; + let mut device = Object { vt: vt.as_ptr() }; + let mut heap = Object { vt: vt.as_ptr() }; + let mut resource = Object { vt: vt.as_ptr() }; + unsafe { + let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); + *GLOBAL.lock().unwrap() = Some(Global { + dev: dev.clone(), + heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), + cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, + next: crate::gpu::uma::MAX_WINDOWS as u32, free: Vec::new(), + }); + assert!(set_window_views(&dev, &[(&mut resource as *mut _ as usize, 0x10000)])); + assert_eq!(CALLS.load(Ordering::Relaxed), crate::gpu::uma::MAX_WINDOWS as u32); + assert!(UNLOCKED.load(Ordering::Relaxed), "device callback ran while GLOBAL was locked"); + *GLOBAL.lock().unwrap() = None; + } + } + #[test] fn slots_copy_and_release() { let Some(u) = crate::gpu::uma::get() else { return }; diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index b5021f595..3a3480f18 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -701,6 +701,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; @@ -726,6 +728,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; @@ -837,6 +840,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 cdf0c9e7c..de8f1ad07 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3445,6 +3445,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; @@ -4753,12 +4773,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; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 3ff2a9793..f9b7215c0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -359,6 +359,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 db0c70049..a2ee0de96 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 with `XCL_HEAP_WINDOWS=1` (`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); @@ -860,9 +863,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 cad94a252dc722792f1b9d0695800cba1e61a436 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 2/4] D3D12.X: SetDescriptorHeaps(0, NULL) clears the list's record of bound heaps 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. Test: unbinding_all_heaps_lets_the_shared_heap_be_bound_again. From #187 by Remington Wilcox (8b4e398). Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 --- 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 de8f1ad07..afa4f91e4 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3469,11 +3469,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); @@ -4748,6 +4752,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 927adcc0200c1a5c7814e71adfcbfdcb4ec2b5e0 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 3/4] D3D12.X: a pipeline the driver refuses with heap windows 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. From #187 by Remington Wilcox (41d4506). Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 --- 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 8568361b1..c63f8be85 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. Opt-in: on with `XCL_HEAP_WINDOWS=1`, unless the views diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index f9b7215c0..ac7ab4c4d 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; @@ -3314,10 +3314,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); @@ -3325,6 +3325,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()) }; @@ -3342,6 +3393,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; @@ -3552,6 +3607,10 @@ mod big_compile_tests { } 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; @@ -3891,6 +3950,10 @@ unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: } 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; @@ -4480,7 +4543,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)); @@ -4500,6 +4563,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 7b9a2490e..0d37e0b84 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -178,7 +178,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"); @@ -225,6 +230,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 (opt-in: XCL_HEAP_WINDOWS=1; 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 deb4b92b4a0ec8436a73c0683a9a0bd54f38985d Mon Sep 17 00:00:00 2001 From: imnicho Date: Tue, 24 Nov 2026 17:48:14 +0100 Subject: [PATCH 4/4] Recompiler: a heap window's view ends 32 bytes below 4 GiB A memory window in the heap form is a raw view of up to 4 GiB less one dword. The D3D12 runtime of Windows 11 23H2 (D3D12Core 10.0.22621) refuses a raw view that ends more than 4 GiB - 32 bytes from the start of its resource and removes the device: a title with XCL_HEAP_WINDOWS=1 lost its device at start there, before the first frame. Newer runtimes take the larger view. Found and measured by CharlyRien on PR #680 (threshold table, debug-layer message 345, the fix and its test run on an RTX 3090). raw_window_uav now caps the view at 4 GiB - 32 bytes: the last 32 bytes of a 4 GiB window read 0 and drop their stores in the heap form, where it was the last 4. The HLSL and the cache keys stay the same. gpu_raw_window_view_reaches_its_top checks up to the new end. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/gpu/recomp/heap_window_tests.rs | 9 +++++---- crates/xcl/src/gpu/recomp/runner.rs | 12 +++++++----- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/heap_window_tests.rs b/crates/xcl/src/gpu/recomp/heap_window_tests.rs index 0c8abb3bf..21d9088b4 100644 --- a/crates/xcl/src/gpu/recomp/heap_window_tests.rs +++ b/crates/xcl/src/gpu/recomp/heap_window_tests.rs @@ -59,7 +59,8 @@ fn device() -> Option<(ID3D12Device, String)> { /// The heap-window form (`Options::heap_windows`) on a real sparse window: a 4 GiB reserved /// 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. +/// hand out (a reservation across two windows covers it), up to its last 32 bytes (the view +/// ends there: an older D3D12 runtime removes the device for a raw view that ends above). #[test] fn gpu_raw_window_view_reaches_its_top() { let Some((dev, name)) = device() else { @@ -80,11 +81,11 @@ void main(uint l : SV_GroupThreadID) { RWByteAddressBuffer w = ResourceDescriptorHeap[NonUniformResourceIndex(0u)]; w.Store(0xFFFF0000u + 4u * l, 0x5A000000u | l); w.Store(4u * l, 0xA5000000u | l); - if (l < 63u) w.Store(0xFFFFFF00u + 4u * l, 0x3C000000u | l); + if (l < 56u) w.Store(0xFFFFFF00u + 4u * l, 0x3C000000u | l); DeviceMemoryBarrier(); 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); + outb.Store(512u + 4u * l, l < 56u ? w.Load(0xFFFFFF00u + 4u * l) : 0u); } "#; unsafe { @@ -155,7 +156,7 @@ void main(uint l : SV_GroupThreadID) { 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[192 + l], 0x5A00_0000 | l as u32, "{name}: lane {l}, the top tile in memory"); - if l < 63 { + if l < 56 { assert_eq!(w[128 + l], 0x3C00_0000 | l as u32, "{name}: lane {l}, the window's last dwords"); } } diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 6876e48f3..2327e0794 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1350,13 +1350,15 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result D3D12_UNORDERED_ACCESS_VIEW_DESC { - let bytes = bytes.min((1u64 << 32) - 4); + let bytes = bytes.min((1u64 << 32) - 32); D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, ViewDimension: D3D12_UAV_DIMENSION_BUFFER,