diff --git a/README.md b/README.md index 2a957e95e5..b180479940 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,10 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o masks and lane values ([`docs/wave64-on-wave32.md`](docs/wave64-on-wave32.md)) – slower than 64-lane waves, most for groups of several waves; wave64 vertex and pixel shaders that read lanes 32–63 can still differ there. Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42). +- **Title memory:** `XCL_UMA_WINDOWS=8` or `16` opts into a larger GPU-visible address range + for large title allocations. It requires the shared descriptor heap and heap-backed shaders. + The default is `4`, which supports the root-UAV fallback when the driver refuses a heap-backed + pipeline. `xcl shaders --precompile` reads the same setting. ```powershell cargo build --release --workspace # target\release\xcl.exe diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 608cbf6d23..f0bbac8f10 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -1533,7 +1533,8 @@ impl Em { /// whose high dword (bits 32..63) is `hi` (`xcl_w`, read by the `mem` accessors). fn window(&mut self, hi: &str) { if self.opt.mem_windows > 1 { - self.line(&format!("xcl_w = ({hi}) & 3u;")); + let mask = self.opt.mem_windows.next_power_of_two().max(crate::gpu::uma::MAX_WINDOWS as u32) - 1; + self.line(&format!("xcl_w = ({hi}) & {mask}u;")); } } @@ -4083,10 +4084,10 @@ impl Em { // other groups wrote) relies on GLC / cache invalidation on the console: keep the flat // memory coherent across the GPU there; graphics keeps the cached (faster) view let coherent = if matches!(self.opt.mode, Mode::Compute(_)) { "globallycoherent " } else { "" }; - let windows = self.opt.mem_windows.clamp(1, 4); + let windows = self.opt.mem_windows.max(1); let _ = writeln!(h, "{coherent}RWByteAddressBuffer mem : register(u2);"); if windows > 1 { - for k in 1..windows { + for k in 1..windows.min(crate::gpu::uma::MAX_WINDOWS as u32) { let _ = writeln!(h, "{coherent}RWByteAddressBuffer mem{k} : register(u{});", 2 + k); } h.push_str("static uint xcl_w = 0u;\n"); @@ -4526,7 +4527,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 } @@ -4915,7 +4917,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.") { @@ -4933,11 +4937,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"), @@ -4962,6 +4966,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/heap_window_tests.rs b/crates/xcl/src/gpu/recomp/heap_window_tests.rs new file mode 100644 index 0000000000..0c8abb3bf7 --- /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 34ac919bb1..9ea1edc75c 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -61,6 +61,21 @@ 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(crate) fn valid_window_count(windows: usize, heap: bool) -> bool { + windows <= crate::gpu::uma::MAX_WINDOWS + || (heap && windows.is_power_of_two() && windows <= crate::gpu::uma::MAX_HEAP_WINDOWS) +} pub mod upper_lanes; use std::collections::{BTreeMap, BTreeSet}; @@ -490,6 +505,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, @@ -497,7 +517,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 } } } @@ -1294,6 +1314,16 @@ 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 + }; + if !valid_window_count(opt.mem_windows as usize, opt.heap_windows) { + return Err(format!("unsupported shader memory layout: {} windows (heap: {})", opt.mem_windows, opt.heap_windows)); + } 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 99a30940c5..578e6be14e 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -73,9 +73,43 @@ 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() && !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 +/// 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 c7f9cc42f3..8f1c548b1f 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1300,6 +1300,25 @@ 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()); @@ -1329,6 +1348,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(); @@ -1425,7 +1460,26 @@ 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 slots = crate::gpu::uma::get().map_or(crate::gpu::uma::MAX_WINDOWS, |u| u.shader_windows().max(crate::gpu::uma::MAX_WINDOWS)); + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: super::MEM_HEAP_BASE + slots as u32, + 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..slots { + 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 a4f50929bb..3b0d378b86 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3183,18 +3183,54 @@ fn gpu_mesh_mode_reads_memory_windows() { /// accesses in window 0. #[test] fn gpu_memory_windows_above_4_gib() { + memory_windows_above_4_gib(2, 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(2, true); +} + +#[test] +fn gpu_memory_windows_beyond_the_root_uavs() { + memory_windows_above_4_gib(16, true); +} + +#[test] +fn expanded_heap_window_shaders_use_the_full_window_index() { + let p = prog(&[("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 1), ("OFFSET", 0)], None)]); + let dxc = super::dxc::location().is_ok(); + if !dxc { + runner::skip_test("no DXC"); + } + for windows in [8, 16] { + let t = translate(&p, &Options { mem_windows: windows | super::HEAP_WINDOWS, ..Default::default() }).unwrap(); + assert!(t.hlsl.contains(&format!(") & {}u;", windows - 1))); + assert!(t.hlsl.contains(&format!("xcl_w < {windows}u"))); + assert!(!t.hlsl.contains("register(u6)")); + assert!(translate(&p, &Options { mem_windows: windows, ..Default::default() }).is_err()); + if dxc { + super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + } + } +} + +fn memory_windows_above_4_gib(windows: usize, heap: bool) { if !gpu_ready() { return; } - let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); - let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64); - assert_eq!(w1 - w0, 1 << 32); + let arena = crate::gpu::uma::Uma::with_windows(windows, 1 << 20).unwrap(); + let k = windows - 1; + let (w0, target) = (arena.window(0).0 as u64, arena.window(k).0 as u64); + assert_eq!(target - w0, (k as u64) << 32); let word = |a: u64| unsafe { &mut *(a as *mut u32) }; - *word(w1 + 0x1000) = 0xC0FFEE; - *word(w1 + 0x1004) = 0x1234; + *word(target + 0x1000) = 0xC0FFEE; + *word(target + 0x1004) = 0x1234; for l in 0..64u64 { - *word(w1 + 0x2000 + 4 * l) = 1000 + l as u32; - *word(w1 + 0x4000 + 4 * l) = 5000 + l as u32; + *word(target + 0x2000 + 4 * l) = 1000 + l as u32; + *word(target + 0x4000 + 4 * l) = 5000 + l as u32; *word(w0 + 0x4000 + 4 * l) = 9; // same low address in window 0: must not be read } let glbl = |n: &'static str, f: &[(&str, u64)]| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { @@ -3213,36 +3249,38 @@ 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: windows as u32, 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(); - st.sgpr[2..4].copy_from_slice(&[(w1 + 0x1000) as u32, hi(w1)]); - st.sgpr[8..12].copy_from_slice(&[(w1 + 0x2000) as u32, hi(w1) & 0xFFFF | 4 << 16, 64, 0]); + st.sgpr[2..4].copy_from_slice(&[(target + 0x1000) as u32, hi(target)]); + st.sgpr[8..12].copy_from_slice(&[(target + 0x2000) as u32, hi(target) & 0xFFFF | 4 << 16, 64, 0]); st.sgpr[12..16].copy_from_slice(&[(w0 + 0x3000) as u32, hi(w0) & 0xFFFF | 4 << 16, 64, 0]); - st.sgpr[16..18].copy_from_slice(&[(w1 + 0x6000) as u32, hi(w1)]); + st.sgpr[16..18].copy_from_slice(&[(target + 0x6000) as u32, hi(target)]); for (l, r) in st.vgpr.iter_mut().enumerate() { let l = l as u64; r[0] = l as u32; r[2] = 7 * l as u32; r[3] = 0; // atomic offset: all lanes on one counter - r[4] = (w1 + 0x4000 + 4 * l) as u32; - r[5] = hi(w1); - r[8] = (w1 + 0x5000 + 4 * l) as u32; - r[9] = hi(w1); + r[4] = (target + 0x4000 + 4 * l) as u32; + r[5] = hi(target); + r[8] = (target + 0x5000 + 4 * l) as u32; + r[9] = hi(target); r[11] = 1; } let r = runner::run_in_arena(&dxil, &st, &arena).unwrap(); - assert_eq!((r.sgpr[20], r.sgpr[21]), (0xC0FFEE, 0x1234), "s_load from window 1"); - assert_eq!(r.sgpr[24..28], [1001, 1002, 1003, 1004], "s_buffer_load_dwordx4 from window 1"); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0xC0FFEE, 0x1234), "s_load from window {k}"); + assert_eq!(r.sgpr[24..28], [1001, 1002, 1003, 1004], "s_buffer_load_dwordx4 from window {k}"); for l in 0..64u64 { - assert_eq!(r.vgpr[l as usize][1], 1000 + l as u32, "lane {l}: buffer_load from window 1"); - assert_eq!(r.vgpr[l as usize][6], 5000 + l as u32, "lane {l}: global_load from window 1"); + assert_eq!(r.vgpr[l as usize][1], 1000 + l as u32, "lane {l}: buffer_load from window {k}"); + assert_eq!(r.vgpr[l as usize][6], 5000 + l as u32, "lane {l}: global_load from window {k}"); assert_eq!(*word(w0 + 0x3000 + 4 * l), 7 * l as u32, "lane {l}: buffer_store into window 0"); - assert_eq!(*word(w1 + 0x5000 + 4 * l), 7 * l as u32, "lane {l}: global_store into window 1"); + assert_eq!(*word(target + 0x5000 + 4 * l), 7 * l as u32, "lane {l}: global_store into window {k}"); } - assert_eq!(*word(w1 + 0x6000), 64, "global_atomic_add in window 1"); + assert_eq!(*word(target + 0x6000), 64, "global_atomic_add in window {k}"); assert_eq!(*word(w0 + 0x6000), 0, "nothing in window 0 at the same low address"); } diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 82eac9e534..87613bb926 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -3,10 +3,10 @@ //! that D3D12 can open as heaps (`ID3D12Device3::OpenExistingHeapFromAddress`), so the GPU //! works on them directly. //! -//! A heap is smaller than 4 GiB, so the memory is up to 4 *windows*: window k is one region -//! at `base + k · 4 GiB` with `base` 16 GiB-aligned. The window of a console GPU address is -//! then `(address >> 32) & 3` and its low 32 bits are the offset in that window's heap – the -//! recompiler's `mem` (window 0), `mem1` … buffers. Allocations never straddle windows. +//! A heap is smaller than 4 GiB, so memory is split into windows at `base + k · 4 GiB`. +//! The aperture has 4 windows by default and can grow to 8 or 16 with heap-backed shaders. +//! The base is aligned to the aperture size, so the shader takes the window index from the +//! high dword of the address and the byte offset from its low dword. //! //! Measured on Windows 11 + RX 9070 (2026-11-20): the heap must cover a fully committed //! `VirtualAlloc` allocation (a reservation with partial commit is rejected); up to @@ -26,7 +26,30 @@ pub const GRAIN: usize = 0x1_0000; pub const MAX_SIZE: usize = (4096 << 20) - GRAIN; /// distance between windows pub const WINDOW: usize = 1 << 32; +/// The legacy layout and the number of memory UAVs in the ABI root signature. pub const MAX_WINDOWS: usize = 4; +/// Maximum number of windows addressable through the shared descriptor heap. +pub const MAX_HEAP_WINDOWS: usize = 16; + +/// Exclusive upper bound for candidate window indices. +fn slot_limit(windows: usize) -> usize { + // Larger layouts stay below the title's 40-bit GPU address limit. + if windows > MAX_WINDOWS { 1 << (40 - 32) } else { 512 } +} + +pub(crate) fn configured_runtime_windows() -> usize { + let Ok(value) = std::env::var("XCL_UMA_WINDOWS") else { return MAX_WINDOWS }; + let windows = value.parse::().unwrap_or(0); + if !matches!(windows, MAX_WINDOWS | 8 | MAX_HEAP_WINDOWS) { + crate::xlog_warn!("UMA: XCL_UMA_WINDOWS must be 4, 8, or 16. Using {MAX_WINDOWS}"); + return MAX_WINDOWS; + } + if windows > MAX_WINDOWS && !crate::gpu::recomp::pso::heap_windows() { + crate::xlog_warn!("UMA: {windows} windows require heap-backed shaders. Using {MAX_WINDOWS}"); + return MAX_WINDOWS; + } + windows +} /// bytes of sparse window 0 only 32-bit descriptor heaps get (`Uma::desc_range`) const DESC_HEADROOM: usize = 512 << 20; @@ -42,7 +65,7 @@ enum WindowKind { pub struct Uma { base: usize, - kinds: [WindowKind; MAX_WINDOWS], + kinds: Vec, /// VirtualAlloc base pointers owned by this Uma (freed on Drop) win_allocs: Vec, inner: Mutex, @@ -167,9 +190,14 @@ impl Uma { /// `for_runtime` with a coherent window of up to `coherent` bytes (`coherent_hint`). pub fn for_runtime_with(size: usize, coherent: usize) -> Option { + Self::reserve_runtime(size, coherent, MAX_WINDOWS).or_else(|| Self::new(size)) + } + + fn reserve_runtime(size: usize, coherent: usize, windows: usize) -> Option { let committed = ((size.min(coherent.max(RUNTIME_COMMITTED_CAP)) + GRAIN - 1) & !(GRAIN - 1)).clamp(GRAIN, MAX_SIZE); - let sparse_len = (MAX_WINDOWS - 1) * WINDOW; - for slot in (4usize..512).step_by(MAX_WINDOWS) { + let coherent_index = windows - 1; + let sparse_len = coherent_index * WINDOW; + for slot in (windows..slot_limit(windows)).step_by(windows) { let base = slot << 32; let sp = unsafe { VirtualAlloc(base as *const std::ffi::c_void, sparse_len, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) }; if sp as usize != base { @@ -178,7 +206,7 @@ impl Uma { } continue; } - let c_base = base + (MAX_WINDOWS - 1) * WINDOW; + let c_base = base + sparse_len; let cp = unsafe { VirtualAlloc(c_base as *const std::ffi::c_void, committed, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }; if cp as usize != c_base { if !cp.is_null() { @@ -188,12 +216,14 @@ impl Uma { continue; } let mut inner = Inner::default(); - inner.free.insert((MAX_WINDOWS - 1) * WINDOW, committed); + inner.free.insert(sparse_len, committed); let mut sparse_free: (BTreeMap, BTreeMap) = Default::default(); sparse_free.0.insert(base, sparse_len); + let mut kinds = vec![WindowKind::Sparse; windows]; + kinds[coherent_index] = WindowKind::Committed(committed); let u = Uma { base, - kinds: [WindowKind::Sparse, WindowKind::Sparse, WindowKind::Sparse, WindowKind::Committed(committed)], + kinds, win_allocs: vec![base, c_base], inner: Mutex::new(inner), sparse_free: Mutex::new(sparse_free), @@ -202,22 +232,20 @@ impl Uma { u.reserve_pool(POOL); return Some(u); } - Uma::new(size) + None } /// The windows after the committed ones as one write-watched reservation (sparse windows). fn reserve_sparse_windows(&mut self) { let committed = self.windows(); - if committed >= MAX_WINDOWS { + if committed >= self.kinds.len() { return; } let start = self.base + committed * WINDOW; - let len = (MAX_WINDOWS - committed) * WINDOW; + let len = (self.kinds.len() - committed) * WINDOW; let p = unsafe { VirtualAlloc(start as *const std::ffi::c_void, len, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) }; if p as usize == start { - for k in committed..MAX_WINDOWS { - self.kinds[k] = WindowKind::Sparse; - } + self.kinds[committed..].fill(WindowKind::Sparse); self.win_allocs.push(start); self.sparse_free.lock().unwrap().0.insert(start, len); } else if !p.is_null() { @@ -286,7 +314,7 @@ impl Uma { } let size = (size.max(1) + GRAIN - 1) & !(GRAIN - 1); let mut g = self.sparse_free.lock().unwrap(); - let end = self.base + MAX_WINDOWS * WINDOW; + let end = self.base + self.kinds.len() * WINDOW; let lo = self.title_sparse_start(); if let Some(at) = take_sparse_in(&mut g, (self.base + WINDOW).max(lo), end, size, GRAIN, false) { return Some(at); @@ -325,7 +353,7 @@ impl Uma { let size = size.max(1).checked_next_multiple_of(GRAIN)?; let align = align.max(GRAIN).checked_next_power_of_two()?; let mut g = self.sparse_free.lock().unwrap(); - let end = self.base + MAX_WINDOWS * WINDOW; + let end = self.base + self.kinds.len() * WINDOW; let lo = self.title_sparse_start(); let above_0 = (self.base + WINDOW).max(lo); if size <= WINDOW { @@ -375,8 +403,9 @@ impl Uma { /// `windows` committed windows of `size` bytes each. pub fn with_windows(windows: usize, size: usize) -> Option { let size = ((size + GRAIN - 1) & !(GRAIN - 1)).clamp(GRAIN, MAX_SIZE); - let windows = windows.clamp(1, MAX_WINDOWS); - for slot in (4usize..512).step_by(MAX_WINDOWS) { + let windows = windows.clamp(1, MAX_HEAP_WINDOWS); + let aperture = windows.next_power_of_two().max(MAX_WINDOWS); + for slot in (aperture..slot_limit(aperture)).step_by(aperture) { let base = slot << 32; let mut got = Vec::new(); for k in 0..windows { @@ -390,7 +419,7 @@ impl Uma { } if got.len() == windows { let mut inner = Inner::default(); - let mut kinds = [WindowKind::None; MAX_WINDOWS]; + let mut kinds = vec![WindowKind::None; aperture]; let mut win_allocs = Vec::with_capacity(windows + 1); for k in 0..windows { inner.free.insert(k * WINDOW, size); @@ -447,9 +476,9 @@ impl Uma { /// contiguous sparse windows belong to a single reservation, while each committed window /// is its own allocation. pub fn watch_regions(&self) -> Vec<(usize, usize)> { - let mut out: Vec<(usize, usize)> = Vec::with_capacity(MAX_WINDOWS); + let mut out = Vec::with_capacity(self.kinds.len()); let mut k = 0; - while k < MAX_WINDOWS { + while k < self.kinds.len() { match self.kinds[k] { WindowKind::None => k += 1, WindowKind::Committed(s) => { @@ -459,7 +488,7 @@ impl Uma { WindowKind::Sparse => { let start = self.base + k * WINDOW; let mut len = 0usize; - while k < MAX_WINDOWS && matches!(self.kinds[k], WindowKind::Sparse) { + while k < self.kinds.len() && matches!(self.kinds[k], WindowKind::Sparse) { len += WINDOW; k += 1; } @@ -473,7 +502,7 @@ impl Uma { pub fn window_of(&self, p: usize) -> Option { let k = p.checked_sub(self.base)? / WINDOW; let (start, len) = self.window(k); - (k < MAX_WINDOWS && len > 0 && p - start < len).then_some(k) + (len > 0 && p - start < len).then_some(k) } pub fn contains(&self, p: usize) -> bool { @@ -726,7 +755,7 @@ pub fn note_coherent_need(bytes: usize) { impl Uma { /// The committed coherent window (None: none). pub fn committed_window(&self) -> Option { - (0..MAX_WINDOWS).find(|&k| self.is_committed_window(k)) + self.kinds.iter().position(|w| matches!(w, WindowKind::Committed(_))) } } @@ -736,10 +765,19 @@ pub fn get() -> Option<&'static Uma> { .get_or_init(|| { let mb = std::env::var("XCL_UMA_MB").ok().and_then(|v| v.parse::().ok()).unwrap_or(2048); let coherent = coherent_hint(); - let u = Uma::for_runtime_with((mb << 20).max(coherent), coherent); + let size = (mb << 20).max(coherent); + let windows = configured_runtime_windows(); + let u = if windows > MAX_WINDOWS { + Uma::reserve_runtime(size, coherent, windows).or_else(|| { + crate::xlog_warn!("UMA: could not reserve {windows} windows. Using the default layout"); + Uma::for_runtime_with(size, coherent) + }) + } else { + Uma::for_runtime_with(size, coherent) + }; match &u { Some(u) => { - let sparse_n = (0..MAX_WINDOWS).filter(|&k| u.is_sparse_window(k)).count(); + let sparse_n = u.kinds.iter().filter(|w| matches!(w, WindowKind::Sparse)).count(); crate::xlog_info!( "UMA: {} sparse VRAM window(s) ({} GiB VA) + {} MB coherent window at {:#x}", sparse_n, @@ -759,6 +797,29 @@ pub fn get() -> Option<&'static Uma> { mod tests { use super::*; + #[test] + fn expanded_runtime_windows_hold_large_sparse_reservations() { + let size = 24usize << 30; + let legacy = Uma::for_runtime(GRAIN).unwrap(); + assert!(legacy.sparse_reserve(size).is_none()); + drop(legacy); + + for windows in [8, MAX_HEAP_WINDOWS] { + let u = Uma::reserve_runtime(GRAIN, GRAIN, windows).unwrap(); + let last = windows - 1; + assert_eq!(u.shader_windows(), windows); + assert_eq!(u.base() % (windows * WINDOW), 0); + assert!(u.base() + windows * WINDOW <= 1 << 40); + assert_eq!(u.committed_window(), Some(last)); + assert_eq!(u.watch_regions(), vec![(u.base(), last * WINDOW), (u.window(last).0, GRAIN)]); + + let p = u.sparse_reserve(size).unwrap(); + assert_eq!(u.window_of(p), Some(1)); + assert_eq!(u.window_of(p + size - 1), Some(6)); + assert_eq!(u.sparse_alloc_in(0, GRAIN, GRAIN), Some((u.base() + GRAIN, GRAIN))); + } + } + /// Arena blocks come from XCL's pool while the title holds the rest of window 0, and go /// back to it when freed. #[test] diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index d68197e4aa..6aca691262 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -833,6 +833,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 176973ea22..11e7b63590 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,51 @@ 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_HEAP_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). +/// The legacy layout fills missing slots with window 0. The expanded layout needs every window. +pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) -> bool { + let count = windows.len().max(crate::gpu::uma::MAX_WINDOWS); + let complete = count <= crate::gpu::uma::MAX_WINDOWS || windows.iter().all(|w| w.0 != 0); + let ok = count <= crate::gpu::uma::MAX_HEAP_WINDOWS && complete && windows.first().is_some_and(|w| w.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..count { + 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: could not bind the windows in the shared descriptor heap"); + } + 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 +543,62 @@ 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 CONSECUTIVE: 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); + let k = CALLS.fetch_add(1, Ordering::Relaxed) + crate::gpu::recomp::MEM_HEAP_BASE; + CONSECUTIVE.fetch_and(at.ptr == 0x1000 + k as usize * 32, 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::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(), + }); + let window = (&mut resource as *mut _ as usize, 0x10000); + assert!(set_window_views(&dev, &[window])); + assert_eq!(CALLS.swap(0, Ordering::Relaxed), crate::gpu::uma::MAX_WINDOWS as u32); + let mut windows = [window; crate::gpu::uma::MAX_HEAP_WINDOWS]; + assert!(set_window_views(&dev, &windows)); + assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32); + windows[7] = (0, 0); + assert!(!set_window_views(&dev, &windows)); + assert_eq!(CALLS.load(Ordering::Relaxed), 0); + assert!(CONSECUTIVE.load(Ordering::Relaxed), "window descriptors must start at MEM_HEAP_BASE"); + 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 95568747fb..3c7f1fe270 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -695,6 +695,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; @@ -720,6 +722,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; @@ -830,6 +833,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 2080100306..2f3695728f 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1982,15 +1982,39 @@ 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; 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); @@ -3165,6 +3189,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)] @@ -3190,12 +3255,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 aed907586c..1c13350b2f 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; @@ -290,12 +290,18 @@ unsafe fn check_uma_import(device: &ID3D12Device, u: &crate::gpu::uma::Uma, bufs Ok(format!("ok, {} window(s), {} µs", probes.len(), t0.elapsed().as_micros())) } -unsafe fn open_uma(device: &ID3D12Device) { +unsafe fn open_uma(device: &ID3D12Device) -> Result<(), String> { let Some(u) = crate::gpu::uma::get() else { *UMA_ERROR.lock().unwrap() = "no UMA region".into(); - return; + return Ok(()); }; - let open = |k: usize| -> Result<(usize, u64, usize), String> { + let n = u.shader_windows(); + let expanded = n > crate::gpu::uma::MAX_WINDOWS; + let heap_windows = crate::gpu::recomp::pso::heap_windows(); + if expanded && (!heap_windows || !super::console_heap::shared_heap(device)) { + return Err("expanded UMA needs a shared descriptor heap. Set XCL_UMA_WINDOWS=4 to use the legacy layout".into()); + } + let open = |k: usize| -> Result<(ID3D12Resource, u64, ID3D12Heap), String> { let (base, size) = u.window(k); let dev3: ID3D12Device3 = device.cast().map_err(|e| format!("ID3D12Device3: {e}"))?; let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(base as *const c_void).map_err(|e| format!("OpenExistingHeapFromAddress (window {k}): {e}"))?; @@ -314,24 +320,28 @@ unsafe fn open_uma(device: &ID3D12Device) { device.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; let buf = buf.ok_or("CreatePlacedResource")?; let va = buf.GetGPUVirtualAddress(); - Ok((buf.into_raw() as usize, va, heap.into_raw() as usize)) + Ok((buf, va, heap)) }; - let n = u.shader_windows(); let mut bufs: Vec<(usize, u64)> = vec![(0, 0); n]; let mut heaps: Vec> = vec![None; n]; + let mut backing = Vec::new(); for k in 0..n { if !u.is_committed_window(k) { continue; } match open(k) { - Ok((buf_raw, va, heap_raw)) => { - bufs[k] = (buf_raw, va); - heaps[k] = Some(heap_raw); + Ok((buf, va, heap)) => { + bufs[k] = (buf.as_raw() as usize, va); + heaps[k] = Some(heap.as_raw() as usize); + backing.push((buf, heap)); } Err(e) => { crate::xlog_warn!("D3D12.X: UMA not available to the GPU: {e}"); + if expanded { + return Err(e); + } *UMA_ERROR.lock().unwrap() = e; - return; + return Ok(()); } } } @@ -342,6 +352,7 @@ unsafe fn open_uma(device: &ID3D12Device) { }; match &check { Ok(s) => crate::xlog_info!("D3D12.X: UMA import check: {s}"), + Err(e) if expanded => return Err(format!("expanded UMA import check failed: {e}")), Err(e) => crate::xlog_error!("D3D12.X: UMA import check: {e}"), } *UMA_IMPORT_CHECK.lock().unwrap() = check.unwrap_or_else(|e| e); @@ -351,6 +362,9 @@ unsafe fn open_uma(device: &ID3D12Device) { *slot = (*buf_raw, *va); } } + if expanded && bufs.iter().any(|&(buf, va)| buf == 0 || va == 0) { + return Err(format!("the GPU could not open all {n} UMA windows. Set XCL_UMA_WINDOWS=4 to use the legacy layout")); + } let w0_va = bufs.first().map_or(0, |b| b.1); crate::xlog_info!( "D3D12.X: UMA opened ({} sparse VRAM window(s), {} MB coherent window), window 0 buffer at VA {:#x}", @@ -358,8 +372,23 @@ unsafe fn open_uma(device: &ID3D12Device) { u.size() >> 20, w0_va ); + // shaders take the windows from the shared descriptor heap (`pso::heap_windows`) + if n > 1 && 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)"); + } else if expanded { + return Err("could not bind the expanded UMA layout. Set XCL_UMA_WINDOWS=4 to use the legacy layout".into()); + } + } + // The published coherent buffers and their heaps stay alive for the process lifetime. + for (buf, heap) in backing { + let _ = buf.into_raw(); + let _ = heap.into_raw(); + } *UMA_HEAPS.lock().unwrap() = heaps; *UMA_BUFFER.lock().unwrap() = bufs; + Ok(()) } pub fn stats() -> D3d12Stats { @@ -531,7 +560,7 @@ pub fn init() -> Result { let _ = q.RegisterMessageCallback(Some(debug_message), D3D12_MESSAGE_CALLBACK_FLAG_NONE, std::ptr::null_mut(), &mut cookie); } } - open_uma(&device); + open_uma(&device)?; super::device_x::probe_dynamic_depth_bias(&device); let raw = device.into_raw(); // one reference kept for the process lifetime adopt(raw, Kind::Device); @@ -3155,10 +3184,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); @@ -3166,6 +3195,64 @@ 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; + } + if crate::gpu::uma::get().is_some_and(|u| u.shader_windows() > crate::gpu::uma::MAX_WINDOWS) { + static WARNED: std::sync::Once = std::sync::Once::new(); + WARNED.call_once(|| { + crate::xlog_warn!("D3D12.X: the driver refused an expanded-window pipeline. Set XCL_UMA_WINDOWS=4 to allow switch-form retries"); + }); + 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()) }; @@ -3183,6 +3270,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; @@ -3333,6 +3424,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; @@ -3612,6 +3707,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; @@ -4201,7 +4300,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)); @@ -4221,6 +4320,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/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 62c0eb6b9b..e945f9d0e1 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -489,7 +489,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { return Vec::new(); } let Some(r) = r else { return Vec::new() }; - out.push((k, r.clone().into_raw() as usize, r.GetGPUVirtualAddress())); + out.push((k, r.as_raw() as usize, r.GetGPUVirtualAddress())); windows.push((base, r)); } if out.is_empty() { @@ -545,6 +545,10 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { })(); match made { Ok(s) => { + // UMA_BUFFER owns a reference to each window independently of this state. + for (_, r) in &s.windows { + let _ = r.clone().into_raw(); + } crate::xlog_info!("D3D12.X: {} sparse window(s) for the title's own memory (tiled buffers on video memory)", out.len()); // a state this replaces (the windows set up again) goes after the lock: the release of // its last buffers reaches `forget_buffer`, which takes the lock (#344) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 5c3027d7b0..20ce4d3385 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -715,7 +715,15 @@ 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_else(crate::gpu::uma::configured_runtime_windows); + let heap = windows > 1 && recomp::pso::heap_windows(); + if windows == 0 || !recomp::valid_window_count(windows, heap) { + eprintln!("--windows expects 1 through 4, or 8 or 16 with heap-backed shaders enabled"); + return 2; + } + let windows = if heap { windows as u32 | recomp::HEAP_WINDOWS } else { windows as u32 }; + 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); @@ -727,7 +735,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 { /// wait for DXC on first use. Resumable: cached programs are skipped. GS halves need their /// pipeline partner and are left to the runtime. /// The cache key is the HLSL, so the options are the runtime's: `windows` memory windows as a -/// title's unified memory has (`pso::mem_windows`, 4; `--windows 1` for a title without it), +/// title's unified memory has (`XCL_UMA_WINDOWS`, default 4, or `--windows` to override), /// and the split wave64 form when this machine's GPU (`XCL_ADAPTER`) runs only 32-lane waves /// (`pso::wave32_only_for_device`). Before, the programs were translated with one window and /// no split form, so a title asked for other HLSL and compiled everything again. Still @@ -837,9 +845,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| { diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 587c489ae4..7e3f0d0e9d 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -135,7 +135,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"); @@ -182,6 +187,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.