diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index f647dbd2c..ab4f44373 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1315,22 +1315,39 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result = Vec::new(); + // a D3D12 without heaps over process memory (D3DMetal: E_NOTIMPL): each window is a + // buffer in video memory, filled from the window before the dispatch and copied back + // after it -- (upload, readback) per window + let mut copies: Vec<(ID3D12Resource, ID3D12Resource)> = Vec::new(); for &(base, size) in &arena.windows { - let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(base as *const std::ffi::c_void).map_err(|x| format!("OpenExistingHeapFromAddress: {x}"))?; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size as u64, - 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 | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, - ..Default::default() - }; - let mut mem_buf: Option = None; - dev.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut mem_buf).map_err(|x| format!("CreatePlacedResource: {x}"))?; - bufs.push(mem_buf.ok_or("arena")?); + let heap: ID3D12Heap = match dev3.OpenExistingHeapFromAddress(base as *const std::ffi::c_void) { + Ok(h) => h, + Err(x) if x.code() == windows::Win32::Foundation::E_NOTIMPL => { + let up = buffer(dev, size as u64, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).map_err(e)?; + std::ptr::copy_nonoverlapping(base, p as *mut u8, size); + up.Unmap(0, None); + bufs.push(buffer(dev, size as u64, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?); + copies.push((up, buffer(dev, size as u64, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?)); + continue; + } + Err(x) => return Err(format!("OpenExistingHeapFromAddress: {x}")), + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size as u64, + 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 | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, + ..Default::default() + }; + let mut mem_buf: Option = None; + dev.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut mem_buf).map_err(|x| format!("CreatePlacedResource: {x}"))?; + bufs.push(mem_buf.ok_or("arena")?); } let mem_buf = bufs[0].clone(); let pso: ID3D12PipelineState = dev @@ -1353,13 +1370,18 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result Result in_a (sparse VRAM) + arg_table constant 77 (Window 3) record_and_run(1, true); + gpu_wrote(); for l in 0..64usize { let got = *((out_buf + 4 * l) as *const u32); assert_eq!(got, 1000 + l as u32 + 77, "submit 1 lane {l} mismatch"); @@ -3589,12 +3600,21 @@ fn gpu_sparse_vram_descriptors_buffers_and_xmem() { *((in_b + 4 * 3) as *mut u32) = 9999; crate::hle::d3d12x::console_heap::write(&slot0, &vsharp(in_b)); record_and_run(2, false); + gpu_wrote(); for l in 0..64usize { let expected = if l == 3 { 9999 + 13 } else { 5000 + 2 * l as u32 + 13 }; let got = *((out_buf + 4 * l) as *const u32); assert_eq!(got, expected, "submit 2 (mutated sparse descriptor + XMem buffer) lane {l} mismatch"); } + // Submits 3..: a constant the CPU rewrites before every submit reaches the shader each time + for n in 0..40u32 { + *(arg_table as *mut u32) = 100 + n; + record_and_run(3 + n as u64, false); + gpu_wrote(); + assert_eq!(*(out_buf as *const u32), 5000 + 100 + n, "submit {} (constant rewritten in window 3)", 3 + n); + } + // Clean up crate::hle::d3d12x::console_heap::unregister(heap_obj); crate::hle::kernelx::XMemFreeDefault(in_a as *mut _, gfx_attrs); diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 82eac9e53..3f0b86499 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -13,6 +13,7 @@ //! 4095 MiB works (exactly 4 GiB is rejected), opening 4 GiB takes ~0.5 s. use std::collections::BTreeMap; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Mutex, OnceLock}; use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; @@ -48,6 +49,8 @@ pub struct Uma { inner: Mutex, /// free ranges of the sparse windows (address → length) and the reservations in them sparse_free: Mutex<(BTreeMap, BTreeMap)>, + /// the committed windows are not the GPU's memory: it has copies of them (`set_shadowed`) + shadowed: AtomicBool, /// XCL's own pool in window 0 for `Arena` blocks: (start, end, free blocks). The title /// cannot take it – a title that commits all of unified memory at start (Unicorn /// Overlord: 2046 of 2048 MB) left no room for draw arguments, and draws were skipped. @@ -197,6 +200,7 @@ impl Uma { win_allocs: vec![base, c_base], inner: Mutex::new(inner), sparse_free: Mutex::new(sparse_free), + shadowed: AtomicBool::new(false), pool: Mutex::new((0, 0, Vec::new())), }; u.reserve_pool(POOL); @@ -277,6 +281,23 @@ impl Uma { len > 0 && self.is_committed(p) && p.checked_add(len - 1).is_some_and(|e| self.window_of(e) == self.window_of(p)) } + /// The GPU could not open the committed windows as heaps (`OpenExistingHeapFromAddress` + /// not implemented: D3DMetal): each has a buffer in video memory instead, a copy that + /// `d3d12x::sparse` keeps in step like a sparse window's tiles. + pub fn set_shadowed(&self) { + self.shadowed.store(true, Ordering::Release); + } + + pub fn shadowed(&self) -> bool { + self.shadowed.load(Ordering::Acquire) + } + + /// Whether the GPU works on a copy of the memory at `p` (a sparse window, or a committed + /// one that is shadowed): what the GPU writes there the CPU sees only after a readback. + pub fn is_gpu_copy(&self, p: usize) -> bool { + self.is_sparse(p) || (self.shadowed() && self.is_committed(p)) + } + /// Address space for a title reservation of `size` bytes in the sparse windows (64 KiB /// aligned, first fit; not committed). Prefers windows 1+ so window 0 stays uncluttered for /// small allocations, falling back to all of the title's sparse space (never `desc_range`). @@ -403,6 +424,7 @@ impl Uma { win_allocs, inner: Mutex::new(inner), sparse_free: Mutex::new(Default::default()), + shadowed: AtomicBool::new(false), pool: Mutex::new((0, 0, Vec::new())), }); } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 336abd93f..3752f8f24 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -888,6 +888,11 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi 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")?; + // shadowed unified memory whose sparse windows could not be made (no reserved resources + // either): descriptor tables are read from window 0, and a null root descriptor is not bound + if first == 0 && u.shadowed() { + return Err("window 0 of unified memory has no buffer on the GPU".into()); + } let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) }); // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) let copy = |bytes: &[u8]| -> Result { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index afa4f91e4..7b6eec854 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -600,7 +600,7 @@ impl ListState { last.0 = last.0.min(va); last.1 = last.1.max(end); } - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) { + if crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(va as usize)) { if self.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); } @@ -953,6 +953,17 @@ fn note_write(list: usize, va: u64, size: u64) { LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size); } +/// A PC copy into `[offset, offset + n)` of console buffer `dst` whose memory the GPU only has +/// a copy of in a committed window (`Uma::shadowed`: readback buffers live there, and titles +/// read them through a pointer they keep mapped, without another Map): the bytes come back to +/// the CPU's view after the submit, like the lists' own memory writes. +fn note_copy_into(list: usize, dst: usize, offset: u64, n: u64) { + let Some(u) = crate::gpu::uma::get().filter(|u| u.shadowed()) else { return }; + let Some((p, bytes)) = real::console_buffer(dst).filter(|&(p, _)| u.is_committed(p)) else { return }; + let offset = offset.min(bytes as u64); + note_write(list, p as u64 + offset, n.min(bytes as u64 - offset)); +} + // --------------------------------------------------------------------------------------- // per-address GPU fence bridge for monotonic 64-bit Write64BitValue* -> Wait64BitValueX // --------------------------------------------------------------------------------------- @@ -3796,6 +3807,7 @@ pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst note_gpu_write("CopyBufferRegion", a + dst_off as usize, n); } } + note_copy_into(this as usize, dst, dst_off, n); pc::(this, PC_COPY_BUFFER_REGION)(this, dst, dst_off + real::buffer_delta(dst), src, src_off + real::buffer_delta(src), n) } @@ -3895,6 +3907,12 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds } } } + if let Some(l) = dst.as_ref().filter(|l| l.Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT) { + // (the rows of the footprint: at most what the copy writes) + let f = &l.Anonymous.PlacedFootprint; + let n = f.Footprint.RowPitch as u64 * f.Footprint.Height.max(1) as u64 * f.Footprint.Depth.max(1) as u64; + note_copy_into(this as usize, transmute_copy::<_, usize>(&l.pResource), f.Offset, n); + } let (Some(d), Some(s)) = (pc_location(dst), pc_location(src)) else { return }; pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); std::mem::forget((d, s)); // borrowed resource pointers @@ -3981,6 +3999,7 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi } let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src)); if dd == 0 && sd == 0 { + note_copy_into(this as usize, dst, 0, u64::MAX); return pc::(this, PC_COPY_RESOURCE)(this, dst, src); } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); @@ -4037,6 +4056,8 @@ pub(super) unsafe extern "system" fn end_query_x(this: *mut c_void, heap: usize, /// ResolveQueryData wants the destination). Buffers placed below their console address add /// `buffer_delta(dest)` to the destination offset. pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, heap: usize, ty: D3D12_QUERY_TYPE, first: u32, count: u32, dest: usize, offset: u64) { + // (8 bytes a query; pipeline statistics, the largest, are 11 values) + note_copy_into(this as usize, dest, offset, count as u64 * if ty == D3D12_QUERY_TYPE_PIPELINE_STATISTICS { 88 } else { 8 }); let pc_offset = offset.saturating_add(real::buffer_delta(dest)); type F = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); pc::(this, PC_RESOLVE_QUERY_DATA)(this, heap, ty, first, count, dest, pc_offset); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fed31e622..e223935f0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -290,40 +290,78 @@ 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())) } +/// `XCL_UMA_SHADOW`: 1 = the committed windows get GPU copies without asking for a heap over +/// them (to try the path on a GPU that has `OpenExistingHeapFromAddress`), 0 = never. +fn shadow_choice() -> Option { + std::env::var("XCL_UMA_SHADOW").ok().map(|v| v != "0") +} + unsafe fn open_uma(device: &ID3D12Device) { let Some(u) = crate::gpu::uma::get() else { *UMA_ERROR.lock().unwrap() = "no UMA region".into(); return; }; - let open = |k: usize| -> Result<(usize, u64, usize), String> { - let (base, size) = u.window(k); + let buffer = |size: usize, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let open = |k: usize| -> Result, String> { + if shadow_choice() == Some(true) { + return Ok(None); + } 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}"))?; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size as u64, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, - ..Default::default() + match dev3.OpenExistingHeapFromAddress::(u.window(k).0 as *const c_void) { + Ok(heap) => Ok(Some(heap)), + Err(e) if e.code() == windows::Win32::Foundation::E_NOTIMPL && shadow_choice() != Some(false) => { + *UMA_ERROR.lock().unwrap() = format!("OpenExistingHeapFromAddress (window {k}): {e}"); + Ok(None) + } + Err(e) => Err(format!("OpenExistingHeapFromAddress (window {k}): {e}")), + } + }; + let shadow = |k: usize| -> Result { + let desc = D3D12_HEAP_DESC { + SizeInBytes: u.window(k).1 as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, }; - let mut buf: Option = None; - 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)) + let mut heap: Option = None; + super::title_textures::own_work(|| device.CreateHeap(&desc, &mut heap)).map_err(|e| format!("CreateHeap (window {k}, {} MB of video memory): {e}", u.window(k).1 >> 20))?; + heap.ok_or_else(|| "CreateHeap".to_string()) }; let n = u.shader_windows(); let mut bufs: Vec<(usize, u64)> = vec![(0, 0); n]; let mut heaps: Vec> = vec![None; n]; + let mut shadows: Vec<(usize, ID3D12Resource)> = Vec::new(); for k in 0..n { if !u.is_committed_window(k) { continue; } - match open(k) { + let made = open(k).and_then(|heap| { + let shadowed = heap.is_none(); + let heap = match heap { + Some(h) => h, + None => shadow(k)?, + }; + let flags = if shadowed { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER }; + let mut buf: Option = None; + device.CreatePlacedResource(&heap, 0, &buffer(u.window(k).1, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; + let buf = buf.ok_or("CreatePlacedResource")?; + if shadowed { + shadows.push((k, buf.clone())); + } + let va = buf.GetGPUVirtualAddress(); + Ok((buf.into_raw() as usize, va, heap.into_raw() as usize)) + }); + match made { Ok((buf_raw, va, heap_raw)) => { bufs[k] = (buf_raw, va); heaps[k] = Some(heap_raw); @@ -335,7 +373,9 @@ unsafe fn open_uma(device: &ID3D12Device) { } } } - let check = if std::env::var("XCL_UMA_CHECK").is_ok_and(|v| v == "0") { + let check = if !shadows.is_empty() { + Ok("not run: the coherent window has a copy in video memory (no host-memory heaps on this D3D12)".into()) + } else if std::env::var("XCL_UMA_CHECK").is_ok_and(|v| v == "0") { Ok("off (XCL_UMA_CHECK=0)".into()) } else { check_uma_import(device, u, &bufs) @@ -359,6 +399,23 @@ unsafe fn open_uma(device: &ID3D12Device) { w0_va ); *UMA_HEAPS.lock().unwrap() = heaps; + for (k, buf) in &shadows { + let (base, size) = u.window(*k); + u.set_shadowed(); + if super::sparse::shadow_window(device, base, size, buf) { + crate::xlog_warn!( + "D3D12.X: UMA window {k} is not shared with the GPU ({}) \u{2013} {} MB of video memory at VA {:#x} stand for it: CPU writes are uploaded before each submit, GPU writes read back on Map and after the lists' memory writes", + match shadow_choice() { + Some(true) => "XCL_UMA_SHADOW=1", + _ => "OpenExistingHeapFromAddress is not implemented", + }, + size >> 20, + bufs[*k].1 + ); + } else { + crate::xlog_warn!("D3D12.X: UMA window {k} is not shared with the GPU and its copy in video memory is not kept in step"); + } + } // 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(); @@ -1316,11 +1373,19 @@ unsafe fn place_console_buffer_sparse(this: *mut c_void, d: &D3D12_RESOURCE_DESC None } +fn uma_shadowed() -> bool { + crate::gpu::uma::get().is_some_and(|u| u.shadowed()) +} + /// Sanitize a console buffer description and initial state for placement in a coherent /// cross-adapter UMA heap (`OpenExistingHeapFromAddress`). fn sanitize_coherent_buffer(desc: &D3D12_RESOURCE_DESC, state: usize) -> (D3D12_RESOURCE_DESC, u32) { let mut d = *desc; - d.Flags = D3D12_RESOURCE_FLAGS(d.Flags.0 & 0xFF) | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + d.Flags = D3D12_RESOURCE_FLAGS(d.Flags.0 & 0xFF); + // a shadowed window's heap is video memory, not a cross-adapter heap over process memory + if !uma_shadowed() { + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; (d, state as u32 & PC_RESOURCE_STATES) @@ -1370,6 +1435,10 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta return None; } UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + // a readback buffer in a shadowed window: what the GPU copied into it is in video memory + if readback_on_null_map && u.shadowed() { + note_sparse_readback(*ppv as usize); + } // Map must hand out the same memory the shaders read (checked once) static CHECKED: AtomicU64 = AtomicU64::new(0); if CHECKED.fetch_add(1, Ordering::Relaxed) == 0 { @@ -1415,7 +1484,9 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: return Some(hr); } let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?; - d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + if !u.shadowed() { + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; d.Width = (delta + bytes) as u64; @@ -1484,7 +1555,7 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v // a resource in unified memory: its console address (no PC mapping – the PC's would be // the start of the PC resource, before the address for a buffer placed below it) if let Some((p, bytes)) = console_buffer(this as usize) { - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(p)) { + if crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(p)) { if !range.is_null() { let r = *(range as *const D3D12_RANGE); if r.End > r.Begin { @@ -2799,7 +2870,7 @@ pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_v let d = super::device_x::pc_resource_desc(&x); let st = state as u32 & PC_RESOURCE_STATES; if let Some(hr) = place_at_title_address(this, block + offset, &d, st, clear as *const c_void, riid, ppv) { - if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && cpu_readback && crate::gpu::uma::get().is_some_and(|u| u.is_sparse(block + offset)) { + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && cpu_readback && crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(block + offset)) { let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); if st == D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 && (flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 as u32) == 0 { note_sparse_readback(*ppv as usize); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 0731890bf..fbe245f16 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -488,6 +488,93 @@ fn buffer_desc(bytes: u64) -> D3D12_RESOURCE_DESC { } } +unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) -> windows::core::Result { + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; + let mut slots = Vec::with_capacity(UPLOAD_SLOTS); + for _ in 0..UPLOAD_SLOTS { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; + list.Close()?; + let _ = list.SetName(windows::core::w!("xcl sparse upload list")); + let _ = alloc.SetName(windows::core::w!("xcl sparse upload allocator")); + slots.push(UploadSlot { alloc, list, fence_val: 0 }); + } + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None)?; + rb_list.Close()?; + let _ = rb_list.SetName(windows::core::w!("xcl sparse readback list")); + let _ = rb_alloc.SetName(windows::core::w!("xcl sparse readback allocator")); + let _ = queue.SetName(windows::core::w!("xcl sparse queue")); + Ok(State { + dev: dev.clone(), + queue, + fence, + value: 0, + event, + rb_fence, + rb_value: 0, + windows, + pools: Vec::new(), + free: Vec::new(), + retired: Vec::new(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + parked: FxHashMap::default(), + buffers: FxHashMap::default(), + to_zero: Vec::new(), + staging: None, + ring_write: 0, + ring_submitted: 0, + ring_free: 0, + inflight: VecDeque::new(), + zero_buf: None, + slots, + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + runs: None, + scratch_runs: Vec::new(), + }) +} + +/// pool heap number of the tiles of a shadowed window: they are the window's own buffer, not +/// pool tiles (never mapped, freed or pinned) +const SHADOW_POOL: u32 = u32::MAX; + +/// A committed window the GPU could not open as a heap (`real::open_uma`): `buf` in video +/// memory stands for `[base, base + size)` and is kept in step like the tiles of a sparse +/// window -- the CPU's writes (write-watch, changed 64-byte chunks) go to it before each +/// ExecuteCommandLists, GPU writes come back on Map and after the lists' memory operations. +/// All of it counts as mapped from the start: the window is committed. False: no queue for +/// the copies (the buffer then never sees the CPU's writes). +pub unsafe fn shadow_window(dev: &ID3D12Device, base: usize, size: usize, buf: &ID3D12Resource) -> bool { + let mut g = STATE.lock().unwrap(); + if g.is_none() { + // no sparse window was made (`init`): the copies still need the queue and the lists + match new_state(dev, Vec::new()) { + Ok(s) => *g = Some(s), + Err(e) => { + crate::xlog_warn!("shadowed window at {base:#x}: {e}"); + return false; + } + } + } + let Some(s) = g.as_mut() else { return false }; + s.windows.push((base, buf.clone())); + for (i, t) in (base..base + size).step_by(TILE).enumerate() { + s.mapped.insert(t, TileEntry::with_holes((SHADOW_POOL, i as u32), 0)); + } + s.runs = None; + MAPPED_GEN.fetch_add(1, Ordering::Release); + true +} + /// The sparse windows' buffers on `dev`: `(window_index, buffer_raw, gpu_va)` for each /// sparse window in `gpu::uma` (empty: no sparse windows). pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { @@ -511,60 +598,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { if out.is_empty() { return out; } - let made = (|| -> windows::core::Result { - let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; - let mut slots = Vec::with_capacity(UPLOAD_SLOTS); - for _ in 0..UPLOAD_SLOTS { - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; - list.Close()?; - let _ = list.SetName(windows::core::w!("xcl sparse upload list")); - let _ = alloc.SetName(windows::core::w!("xcl sparse upload allocator")); - slots.push(UploadSlot { alloc, list, fence_val: 0 }); - } - let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None)?; - rb_list.Close()?; - let _ = rb_list.SetName(windows::core::w!("xcl sparse readback list")); - let _ = rb_alloc.SetName(windows::core::w!("xcl sparse readback allocator")); - let _ = queue.SetName(windows::core::w!("xcl sparse queue")); - Ok(State { - dev: dev.clone(), - queue, - fence, - value: 0, - event, - rb_fence, - rb_value: 0, - windows, - pools: Vec::new(), - free: Vec::new(), - retired: Vec::new(), - mapped: FxHashMap::default(), - pinned: FxHashMap::default(), - parked: FxHashMap::default(), - buffers: FxHashMap::default(), - to_zero: Vec::new(), - staging: None, - ring_write: 0, - ring_submitted: 0, - ring_free: 0, - inflight: VecDeque::new(), - zero_buf: None, - slots, - next_slot: 0, - readback: None, - rb_alloc, - rb_list, - rb_last_fence: 0, - waited: FxHashMap::default(), - runs: None, - scratch_runs: Vec::new(), - }) - })(); + let made = new_state(dev, windows); match made { Ok(s) => { crate::xlog_info!("D3D12.X: {} sparse window(s) for the title's own memory (tiled buffers on video memory)", out.len()); diff --git a/crates/xcl/tests/predication_e2e.rs b/crates/xcl/tests/predication_e2e.rs index 95b84430d..776091a77 100644 --- a/crates/xcl/tests/predication_e2e.rs +++ b/crates/xcl/tests/predication_e2e.rs @@ -99,6 +99,60 @@ unsafe fn wait_fence(queue: &ID3D12CommandQueue, fence: &ID3D12Fence, value: &mu } } +/// Whether the host runs a copy that `SetPredication` should skip (D3DMetal 3.0 does: it skips +/// predicated draws, dispatches and ExecuteIndirect, not copies). A 4-byte copy under +/// EQUAL_ZERO on eight zero bytes, and the same copy unpredicated, into a readback buffer. +unsafe fn host_runs_predicated_copies(raw_dev: *mut c_void) -> bool { + let dev = ID3D12Device::from_raw_borrowed(&raw_dev).expect("backend device"); + // predicate (bytes 0..8) and copy source (bytes 8..12); GENERIC_READ includes PREDICATION + let upload = buffer( + dev, + 256, + D3D12_HEAP_TYPE_UPLOAD, + D3D12_RESOURCE_STATE_GENERIC_READ, + ); + let readback = buffer( + dev, + 256, + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let canary = 0x5843_4C50u32; + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).unwrap(); + (p as *mut u64).write(0); + (p as *mut u32).add(2).write(canary); + upload.Unmap(0, None); + + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .expect("probe CreateCommandQueue"); + let alloc: ID3D12CommandAllocator = dev + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .expect("probe CreateCommandAllocator"); + let list: ID3D12GraphicsCommandList = dev + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None) + .expect("probe CreateCommandList"); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + list.SetPredication(&upload, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); + list.CopyBufferRegion(&readback, 0, &upload, 8, 4); + list.SetPredication(None, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); + list.CopyBufferRegion(&readback, 4, &upload, 8, 4); + list.Close().expect("probe Close"); + let cl: ID3D12CommandList = list.cast().unwrap(); + queue.ExecuteCommandLists(&[Some(cl)]); + wait_fence(&queue, &fence, &mut 0); + + readback.Map(0, None, Some(&mut p)).expect("Map probe readback"); + let got = std::slice::from_raw_parts(p as *const u32, 2).to_vec(); + readback.Unmap(0, None); + assert_eq!(got[1], canary, "the unpredicated probe copy must run"); + got[0] == canary +} + struct ReadbackCtx<'a> { queue: &'a ID3D12CommandQueue, alloc: &'a ID3D12CommandAllocator, @@ -179,6 +233,11 @@ fn set_predication_buffer_state_and_kickoff() { runner::skip_test("no GPU UMA"); return; } + if unsafe { host_runs_predicated_copies(real::device_raw()) } { + println!("the host runs predicated copies – skipping"); + runner::skip_test("host ignores SetPredication for copies"); + return; + } let raw_dev = real::device_raw(); let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw_dev) }