diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 04b6b2f..35ba368 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -654,6 +654,11 @@ pub(super) fn on_release(list: usize) { } } +#[cfg(test)] +pub(super) fn has_list_state(list: usize) -> bool { + LISTS.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&list)) +} + /// Forget a released command allocator so `KickoffX` will not reset a list with a dead allocator. pub(super) fn on_allocator_release(alloc: usize) { if let Some(m) = LISTS.lock().unwrap().as_mut() { @@ -2023,10 +2028,12 @@ pub(super) unsafe extern "system" fn end_query_x(this: *mut c_void, heap: usize, /// command list #30 ResolveQueryData(heap, type, first, count, destination, offset) (PC #54): /// outer occlusion queries ended early are written over the resolved data (after it, in COPY_DEST as -/// ResolveQueryData wants the destination) +/// 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) { + 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, offset); + pc::(this, PC_RESOLVE_QUERY_DATA)(this, heap, ty, first, count, dest, pc_offset); if !is_occlusion(ty) { return; } @@ -2036,7 +2043,7 @@ pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, hea }; let dest = dest as *mut c_void; let Some(res) = ID3D12Resource::from_raw_borrowed(&dest).filter(|_| !visible.is_empty()) else { return }; - let at = res.GetGPUVirtualAddress() + offset; + let at = res.GetGPUVirtualAddress().saturating_add(pc_offset); let params: Vec = visible .iter() .flat_map(|&(i, v)| { @@ -2461,4 +2468,107 @@ mod tests { device_x::forget_base(pso_dyn_static); device_x::forget_base(pso_static_only); } + + #[test] + fn resolve_query_data_applies_buffer_delta_to_pc_resolve_and_occlusion_writeback() { + use std::cell::RefCell; + + thread_local! { + static RESOLVED: RefCell> = const { RefCell::new(Vec::new()) }; + static WRITES: RefCell> = const { RefCell::new(Vec::new()) }; + } + + unsafe extern "system" fn fake_resolve( + _this: *mut c_void, + heap: usize, + _ty: D3D12_QUERY_TYPE, + first: u32, + count: u32, + dest: usize, + offset: u64, + ) { + RESOLVED.with(|r| r.borrow_mut().push((heap, first, count, dest, offset))); + } + + unsafe extern "system" fn fake_write_immediate( + _this: *mut c_void, + count: u32, + params: *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, + _modes: *const D3D12_WRITEBUFFERIMMEDIATE_MODE, + ) { + let slice = std::slice::from_raw_parts(params, count as usize); + WRITES.with(|w| { + let mut w = w.borrow_mut(); + for p in slice { + w.push((p.Dest, p.Value)); + } + }); + } + + const BASE_GPU_VA: u64 = 0x1_0000_0000; + unsafe extern "system" fn fake_gpu_va(_this: *mut c_void) -> u64 { + BASE_GPU_VA + } + + #[repr(C)] + struct FakeCom { + vt: *const usize, + } + + let mut orig_list_vt = [0usize; 70]; + orig_list_vt[PC_RESOLVE_QUERY_DATA] = fake_resolve as usize; + orig_list_vt[PC_WRITE_BUFFER_IMMEDIATE] = fake_write_immediate as usize; + // Adopted objects store `orig` at `ext[-1]`. + let ext_list_vt = [orig_list_vt.as_ptr() as usize, 0usize]; + let mut fake_list = FakeCom { + // SAFETY: `ext_list_vt` has 2 elements; `.add(1)` points at `ext[0]` with `ext[-1] = orig`. + vt: unsafe { ext_list_vt.as_ptr().add(1) }, + }; + + let mut res_vt = [0usize; 16]; + res_vt[11] = fake_gpu_va as usize; + let mut fake_res = FakeCom { vt: res_vt.as_ptr() }; + + let heap = 0x5555_0001usize; + let dest = &mut fake_res as *mut FakeCom as usize; + let delta = 0x3400u64; + let title_offset = 0x100u64; + + real::set_test_buffer_delta(dest, Some(delta)); + VISIBLE.lock().unwrap().get_or_insert_with(HashMap::new).insert((heap, 2), VISIBLE_SAMPLES); + RESOLVED.with(|r| r.borrow_mut().clear()); + WRITES.with(|w| w.borrow_mut().clear()); + + unsafe { + resolve_query_data_x( + &mut fake_list as *mut FakeCom as *mut c_void, + heap, + D3D12_QUERY_TYPE_OCCLUSION, + 1, + 3, + dest, + title_offset, + ); + } + + real::set_test_buffer_delta(dest, None); + if let Some(m) = VISIBLE.lock().unwrap().as_mut() { + m.remove(&(heap, 2)); + } + + let expected_off = title_offset + delta; + RESOLVED.with(|r| { + assert_eq!(*r.borrow(), vec![(heap, 1, 3, dest, expected_off)]); + }); + WRITES.with(|w| { + let expected_va = BASE_GPU_VA + expected_off + 8; // query index 2 = slot (2 - 1) = +8 bytes + assert_eq!( + *w.borrow(), + vec![ + (expected_va, VISIBLE_SAMPLES as u32), + (expected_va + 4, (VISIBLE_SAMPLES >> 32) as u32), + ] + ); + }); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4bd7708..29f715e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -688,6 +688,16 @@ fn console_remap(kind: Kind) -> Vec<(usize, usize)> { /// console D3D12_DESCRIPTOR_HEAP_TYPE also used for CBV / SRV / UAV heaps const XBOX_EXTRA_CBV_SRV_UAV: u32 = 4; +/// Map a console `D3D12_DESCRIPTOR_HEAP_TYPE` to its PC equivalent. +#[inline] +fn pc_heap_type(ty: u32) -> u32 { + if ty == XBOX_EXTRA_CBV_SRV_UAV { + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 + } else { + ty + } +} + /// Where a class's console extensions start: the device's from #44 (`device_x`), the command /// list's from #60 (`list_x`). fn console_extensions(kind: Kind) -> Option { @@ -873,9 +883,7 @@ unsafe extern "system" fn heap_gpu_start_x(this: *mut c_void) -> u64 { unsafe extern "system" fn dev_create_descriptor_heap_x(this: *mut c_void, desc: *const [u32; 4], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let mut d = if desc.is_null() { [u32::MAX; 4] } else { *desc }; - if d[0] == XBOX_EXTRA_CBV_SRV_UAV { - d[0] = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32; - } + d[0] = pc_heap_type(d[0]); let desc = if desc.is_null() { desc } else { &d as *const [u32; 4] }; let sampler = d[0] == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32; if d[0] != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 && !sampler { @@ -927,7 +935,7 @@ unsafe extern "system" fn dev_create_descriptor_heap_x(this: *mut c_void, desc: } unsafe extern "system" fn dev_increment_size_x(this: *mut c_void, ty: u32) -> u32 { - let ty = if ty == XBOX_EXTRA_CBV_SRV_UAV { D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 } else { ty }; + let ty = pc_heap_type(ty); if ty == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 { return super::console_heap::SLOT; } @@ -1129,12 +1137,22 @@ unsafe fn place_console_buffer_sparse(this: *mut c_void, d: &D3D12_RESOURCE_DESC None } +/// 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.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Alignment = 0; + (d, state as u32 & PC_RESOURCE_STATES) +} + unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> Option { let u = crate::gpu::uma::get()?; if UMA_BUFFER.lock().unwrap().is_empty() || ppv.is_null() { return None; } - let mut d: D3D12_RESOURCE_DESC = std::ptr::read(desc as *const D3D12_RESOURCE_DESC); + let d: D3D12_RESOURCE_DESC = std::ptr::read(desc as *const D3D12_RESOURCE_DESC); if d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || d.Width == 0 { return None; } @@ -1159,13 +1177,11 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta } return None; }; - // the heap from OpenExistingHeapFromAddress is cross-adapter: row-major + this flag - d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; - d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - d.Alignment = 0; + // the heap from OpenExistingHeapFromAddress is cross-adapter: row-major + sanitized flags & state + let (d, st) = sanitize_coherent_buffer(&d, state); let k = u.window_of(p)?; let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?; - let hr = dev_create_placed_resource(this, heap, p - u.window(k).0, &d as *const _ as usize, state, clear, riid, ppv); + let hr = dev_create_placed_resource(this, heap, p - u.window(k).0, &d as *const _ as usize, st as usize, clear, riid, ppv); if hr < 0 || (*ppv).is_null() { u.free(p); static ONCE: AtomicU64 = AtomicU64::new(0); @@ -1243,6 +1259,21 @@ pub fn buffer_delta(res: usize) -> u64 { BUFFER_DELTA.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied()).unwrap_or(0) } +#[cfg(test)] +pub(super) fn set_test_buffer_delta(res: usize, delta: Option) { + let mut g = BUFFER_DELTA.lock().unwrap(); + match delta { + Some(d) => { + g.get_or_insert_with(HashMap::new).insert(res, d); + } + None => { + if let Some(m) = g.as_mut() { + m.remove(&res); + } + } + } +} + /// resource Release (every caller): a console buffer's unified memory goes with it /// Map: on the console every resource is CPU-visible memory. One in unified memory that the /// PC cannot map (a texture XCL keeps in step with it) gives its unified-memory address – what @@ -1478,6 +1509,7 @@ unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty: if d0.sampler != s0.sampler { return false; } + let ty = pc_heap_type(ty); let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, if d0.sampler { n } else { 2 * n }, d0.pc_srv, s0.pc_srv, ty); if !d0.sampler { @@ -1511,6 +1543,7 @@ fn note_mixed_copy() { /// #24 CopyDescriptorsSimple(n, dst, src, type) unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) { + let ty = pc_heap_type(ty); note_copy_call("CopyDescriptorsSimple", n, dst, src); if copy_console_slots(this, n, dst, src, ty) { return; @@ -1526,6 +1559,7 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 /// #23 CopyDescriptors(dst ranges, src ranges, type): range by range over console slots. #[allow(clippy::too_many_arguments)] unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dsts: *const u64, dsizes: *const u32, ns: u32, srcs: *const u64, ssizes: *const u32, ty: u32) { + let ty = pc_heap_type(ty); note_copy_call("CopyDescriptors", nd, if dsts.is_null() { 0 } else { *dsts }, if srcs.is_null() { 0 } else { *srcs }); use super::console_heap::{slot, SAMPLER_SLOT, SLOT}; let console = !dsts.is_null() && !srcs.is_null() && nd > 0 && slot(*dsts).is_some(); @@ -1815,6 +1849,11 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("ClearRenderTargetView", cl_clear_rtv as usize), ("ExecuteIndirect", cl_execute_indirect as usize), ]), + Kind::DmaList => v.extend_from_slice(&[ + ("Release", cl_release as usize), + ("Close", cl_close as usize), + ("Reset", cl_reset as usize), + ]), Kind::CommandQueue => v.extend_from_slice(&[("Release", q_release as usize), ("ExecuteCommandLists", q_execute_command_lists as usize)]), Kind::CommandAllocator => v.extend_from_slice(&[("Release", alloc_release as usize), ("Reset", alloc_reset as usize)]), Kind::Resource => v.extend_from_slice(&[ @@ -3831,4 +3870,182 @@ mod readback_routing_tests { assert!(!is_coherent_readback_buffer(&custom_wb, copy_dest, none, COHERENT_CUSTOM_WB_MAX + 0x1_0000)); assert!(is_cpu_readback_buffer(&custom_wb, copy_dest, none)); } + + /// Bug #4: `place_console_buffer` coherent fallback must strip console-only resource flags + /// and state bits before creating the cross-adapter placed resource. + #[test] + fn coherent_buffer_sanitizes_console_flags_and_state() { + let raw_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0x10_0000, + Width: 0x1_0000, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT(0x101), // console layout + Flags: D3D12_RESOURCE_FLAGS(0x0130_0000 | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0), + ..Default::default() + }; + let console_state = 0x0010_0000usize | (D3D12_RESOURCE_STATE_COPY_DEST.0 as usize); + + let (clean, st) = sanitize_coherent_buffer(&raw_desc, console_state); + assert_eq!(clean.Alignment, 0); + assert_eq!(clean.Layout, D3D12_TEXTURE_LAYOUT_ROW_MAJOR); + assert_eq!( + clean.Flags, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER + ); + assert_eq!(st, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32); + + // Verify against a real D3D12 device: raw console flags/state are rejected, sanitized succeeds. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + if let Ok(dev3) = dev.cast::() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + let mem = VirtualAlloc(std::ptr::null(), 0x1_0000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + assert!(!mem.is_null()); + if let Ok(heap) = dev3.OpenExistingHeapFromAddress::(mem) { + let mut unsanitized = raw_desc; + unsanitized.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + unsanitized.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + unsanitized.Alignment = 0; + let mut r_bad: Option = None; + assert!( + dev.CreatePlacedResource(&heap, 0, &unsanitized, D3D12_RESOURCE_STATES(console_state as i32), None, &mut r_bad).is_err(), + "PC D3D12 must reject unsanitized console flags/state" + ); + let mut r_ok: Option = None; + dev.CreatePlacedResource(&heap, 0, &clean, D3D12_RESOURCE_STATES(st as i32), None, &mut r_ok) + .expect("sanitized coherent buffer must succeed on PC D3D12"); + assert!(r_ok.is_some()); + drop(r_ok); + drop(heap); + } + assert_ne!(VirtualFree(mem, 0, MEM_RELEASE), 0); + } + } + } + + /// Bug #5: `CopyDescriptors` and `CopyDescriptorsSimple` must remap `XBOX_EXTRA_CBV_SRV_UAV` + /// (`4`) to `D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV` (`0`) on both console and PC paths. + #[test] + fn copy_descriptors_remaps_xbox_extra_cbv_srv_uav_to_pc_enum() { + use std::cell::RefCell; + + assert_eq!(pc_heap_type(XBOX_EXTRA_CBV_SRV_UAV), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32); + assert_eq!(pc_heap_type(0), 0); + assert_eq!(pc_heap_type(1), 1); + assert_eq!(pc_heap_type(2), 2); + assert_eq!(pc_heap_type(3), 3); + + thread_local! { + static SIMPLE_TYPES: RefCell> = const { RefCell::new(Vec::new()) }; + static RANGE_TYPES: RefCell> = const { RefCell::new(Vec::new()) }; + } + + unsafe extern "system" fn fake_copy_simple(_this: *mut c_void, _n: u32, _dst: u64, _src: u64, ty: u32) { + SIMPLE_TYPES.with(|v| v.borrow_mut().push(ty)); + } + #[allow(clippy::too_many_arguments)] + unsafe extern "system" fn fake_copy_ranges( + _this: *mut c_void, + _nd: u32, + _dsts: *const u64, + _dsizes: *const u32, + _ns: u32, + _srcs: *const u64, + _ssizes: *const u32, + ty: u32, + ) { + RANGE_TYPES.with(|v| v.borrow_mut().push(ty)); + } + + #[repr(C)] + struct FakeDev { + vt: *const usize, + } + + let mut orig_vt = [0usize; 32]; + orig_vt[23] = fake_copy_ranges as usize; + orig_vt[24] = fake_copy_simple as usize; + let ext_vt = [orig_vt.as_ptr() as usize, 0usize]; + let mut dev = FakeDev { + // SAFETY: `ext_vt` has 2 entries; `.add(1)` puts `orig_vt` at `ext[-1]`. + vt: unsafe { ext_vt.as_ptr().add(1) }, + }; + let dev_ptr = &mut dev as *mut FakeDev as *mut c_void; + + SIMPLE_TYPES.with(|v| v.borrow_mut().clear()); + RANGE_TYPES.with(|v| v.borrow_mut().clear()); + + unsafe { + // Non-console PC fallback paths + dev_copy_descriptors_simple_x(dev_ptr, 1, 0x1000, 0x2000, XBOX_EXTRA_CBV_SRV_UAV); + dev_copy_descriptors_simple_x(dev_ptr, 1, 0x1000, 0x2000, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32); + let (d, s, sz) = ([0x1000u64], [0x2000u64], [1u32]); + dev_copy_descriptors_x(dev_ptr, 1, d.as_ptr(), sz.as_ptr(), 1, s.as_ptr(), sz.as_ptr(), XBOX_EXTRA_CBV_SRV_UAV); + dev_copy_descriptors_x(dev_ptr, 1, d.as_ptr(), sz.as_ptr(), 1, s.as_ptr(), sz.as_ptr(), D3D12_DESCRIPTOR_HEAP_TYPE_RTV.0 as u32); + + // Console-slot paths (`copy_console_slots` invoked from both Simple and Ranges) + let heap_obj = 0x5555_DEADusize; + if crate::gpu::uma::get().is_some() + && super::super::console_heap::register(heap_obj, 4, 0x10_0000, 0, 32, false, false, false) + { + let start = super::super::console_heap::start(heap_obj).unwrap(); + let dst_h = start + super::super::console_heap::SLOT as u64; + dev_copy_descriptors_simple_x(dev_ptr, 1, dst_h, start, XBOX_EXTRA_CBV_SRV_UAV); + let (cd, cs, csz) = ([dst_h], [start], [1u32]); + dev_copy_descriptors_x(dev_ptr, 1, cd.as_ptr(), csz.as_ptr(), 1, cs.as_ptr(), csz.as_ptr(), XBOX_EXTRA_CBV_SRV_UAV); + super::super::console_heap::unregister(heap_obj); + + SIMPLE_TYPES.with(|v| assert_eq!(*v.borrow(), vec![0, 1, 0, 0])); + } else { + SIMPLE_TYPES.with(|v| assert_eq!(*v.borrow(), vec![0, 1])); + } + RANGE_TYPES.with(|v| assert_eq!(*v.borrow(), vec![0, 2])); + } + } + + /// Bug #6: `Kind::DmaList` must install `cl_release` so releasing a DMA command list removes + /// its entry from `list_x::LISTS`. + #[test] + fn dma_list_release_cleans_up_list_state() { + assert!( + overrides(Kind::DmaList).iter().any(|&(name, f)| name == "Release" && f == cl_release as usize), + "Kind::DmaList must override Release with cl_release" + ); + + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY).expect("copy alloc"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &alloc, None).expect("copy list"); + let raw = list.into_raw(); + let key = raw as usize; + + // Mirror `device_x::create_list`: adopt as CommandList, track via `list_x::on_create`, + // then re-adopt as `Kind::DmaList`. + adopt(raw, Kind::CommandList); + super::super::list_x::on_create(raw, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COPY); + readopt(raw, Kind::DmaList); + assert!(super::super::list_x::has_list_state(key), "DMA list must be tracked in list_x::LISTS"); + + // Invoke Release through the adopted vtable slot 2. + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*vt(raw).add(2)); + assert_eq!(release(raw), 0); + assert!(!super::super::list_x::has_list_state(key), "releasing DMA list must remove its list_x::LISTS entry"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 8917811..ff20199 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -26,7 +26,10 @@ use windows::core::Interface; use windows::Win32::Foundation::{CloseHandle, HANDLE}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; -use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_DECOMMIT, PAGE_READWRITE}; +use windows_sys::Win32::System::Memory::{ + VirtualAlloc, VirtualFree, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_DECOMMIT, PAGE_GUARD, + PAGE_NOACCESS, PAGE_READWRITE, +}; const TILE: usize = 0x1_0000; /// tiles of a video-memory pool heap (64 MiB) @@ -87,11 +90,103 @@ struct TileEntry { } impl TileEntry { - fn new(pool: (u32, u32)) -> Self { - Self { pool, holes: 0, sent: std::array::from_fn(|_| None) } + fn with_holes(pool: (u32, u32), holes: u16) -> Self { + Self { pool, holes, sent: std::array::from_fn(|_| None) } } } +/// Query actual OS page commitment across the 64 KiB tile at `tile`. +/// Bit `i` in the returned mask is set whenever 4 KiB page `tile + i * PAGE` is not committed +/// and accessible (`MEM_RESERVE`, `MEM_FREE`, `PAGE_NOACCESS`, `PAGE_GUARD`, etc.). +unsafe fn query_tile_holes(tile: usize) -> u16 { + let mut holes = 0xFFFFu16; + let end = tile.saturating_add(TILE); + let mut cur = tile; + while cur < end { + let mut mbi: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + // SAFETY: `VirtualQuery` inspects process virtual memory metadata without dereferencing `cur`. + let n = VirtualQuery(cur as *const c_void, &mut mbi, std::mem::size_of::()); + if n == 0 || mbi.RegionSize == 0 { + break; + } + let region_end = (mbi.BaseAddress as usize).saturating_add(mbi.RegionSize).min(end); + let accessible = mbi.State == MEM_COMMIT && mbi.Protect != 0 && (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) == 0; + if accessible { + let mut pg = cur; + while pg < region_end { + holes &= !(1u16 << ((pg - tile) / PAGE)); + pg += PAGE; + } + } + if region_end <= cur { + break; + } + cur = region_end; + } + holes +} + +/// Update `mapped`, `free`, and `to_zero` for a decommit of `[a, a + n)`. +/// Returns the base addresses of tiles that became completely uncommitted (`holes == 0xFFFF`) +/// and were removed from `mapped` (ready to be unmapped from their sparse window buffers). +fn decommit_tiles( + mapped: &mut FxHashMap, + pinned: &FxHashMap<(u32, u32), u32>, + free: &mut Vec<(u32, u32)>, + to_zero: &mut Vec<(usize, usize)>, + a: usize, + n: usize, +) -> Vec { + if n == 0 { + return Vec::new(); + } + let mut unmapped: Vec = Vec::new(); + let mut pg = a & !(PAGE - 1); + let end = a.saturating_add(n); + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = t.saturating_add(TILE).min(end); + if let Some(entry) = mapped.get_mut(&t) { + let mut newly_holed = 0u16; + let mut p = pg; + while p < tile_end { + let idx = (p - t) / PAGE; + entry.sent[idx] = None; + let bit = 1u16 << idx; + if entry.holes & bit == 0 { + entry.holes |= bit; + newly_holed |= bit; + } + p += PAGE; + } + if entry.holes == 0xFFFF { + unmapped.push(t); + } else if newly_holed != 0 { + for idx in 0..PAGES_PER_TILE { + if newly_holed & (1u16 << idx) != 0 { + to_zero.push((t + idx * PAGE, PAGE)); + } + } + } + } + if tile_end <= pg { + break; + } + pg = tile_end; + } + for &t in &unmapped { + if let Some(entry) = mapped.remove(&t) { + if !pinned.contains_key(&entry.pool) { + free.push(entry.pool); + } + } + } + if !unmapped.is_empty() { + to_zero.retain(|&(za, _)| mapped.contains_key(&(za & !(TILE - 1)))); + } + unmapped +} + struct UploadSlot { alloc: ID3D12CommandAllocator, list: ID3D12GraphicsCommandList, @@ -513,22 +608,30 @@ impl State { ); } - /// tiles of `[a, a + n)` get video memory (mapped in their window) - unsafe fn ensure_mapped(&mut self, a: usize, n: usize) { + /// tiles of `[a, a + n)` get video memory (mapped in their window); `initial_holes` supplies + /// the initial 16-bit hole mask for each newly mapped 64 KiB tile. + unsafe fn ensure_mapped(&mut self, a: usize, n: usize, mut initial_holes: impl FnMut(usize) -> u16) { + if n == 0 { + return; + } let first = a & !(TILE - 1); + let end = a.saturating_add(n); let mut new: Vec<(usize, (u32, u32))> = Vec::new(); let mut t = first; - while t < a + n { + while t < end { if !self.mapped.contains_key(&t) && self.window_index(t).is_some() { let Some((tile, reused)) = self.take_tile() else { break }; - self.mapped.insert(t, TileEntry::new(tile)); + self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t))); self.runs = None; if reused { self.to_zero.push((t, TILE)); } new.push((t, tile)); } - t += TILE; + match t.checked_add(TILE) { + Some(next) => t = next, + None => break, + } } if new.is_empty() { return; @@ -1036,30 +1139,20 @@ pub unsafe fn readback_now(va: usize, len: usize) { /// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that /// lie outside the range are not committed (holes); the range's pages are. pub unsafe fn committed(a: usize, n: usize) { + if n == 0 { + return; + } let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { EARLY.lock().unwrap().push((a, n)); return; }; - let tiles: Vec = (a & !(TILE - 1)..a + n).step_by(TILE).filter(|t| !s.mapped.contains_key(t)).collect(); - s.ensure_mapped(a, n); - for t in tiles { - if let Some(entry) = s.mapped.get_mut(&t) { - let mut mask = 0u16; - for i in 0..PAGES_PER_TILE { - let pg = t + i * PAGE; - if pg + PAGE <= a || pg >= a + n { - mask |= 1u16 << i; - } - } - entry.holes |= mask; - } - } + s.ensure_mapped(a, n, |_| 0xFFFF); let mut pg = a & !(PAGE - 1); - let end = a + n; + let end = a.saturating_add(n); while pg < end { let t = pg & !(TILE - 1); - let tile_end = (t + TILE).min(end); + let tile_end = t.saturating_add(TILE).min(end); if let Some(entry) = s.mapped.get_mut(&t) { let mut p = pg; while p < tile_end { @@ -1067,20 +1160,30 @@ pub unsafe fn committed(a: usize, n: usize) { p += PAGE; } } + if tile_end <= pg { + break; + } pg = tile_end; } } -/// The title decommitted `[a, a + n)`: its whole tiles give their video memory back (unless a -/// placed buffer still uses it). +/// The title decommitted `[a, a + n)`: tiles whose pages are all uncommitted (whether in one +/// full-tile decommit or incrementally via sub-tile decommits) give their video memory back +/// (unless a placed buffer still pins the pool tile). pub unsafe fn decommitted(a: usize, n: usize) { + if n == 0 { + return; + } let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { EARLY.lock().unwrap().retain(|&(x, m)| x + m <= a || x >= a + n); return; }; - let first = (a + TILE - 1) & !(TILE - 1); - let tiles: Vec = (first..(a + n) & !(TILE - 1)).step_by(TILE).filter(|t| s.mapped.contains_key(t)).collect(); + let tiles = decommit_tiles(&mut s.mapped, &s.pinned, &mut s.free, &mut s.to_zero, a, n); + if tiles.is_empty() { + return; + } + s.runs = None; let mut by_window: FxHashMap> = FxHashMap::default(); for &t in &tiles { if let Some(wi) = s.window_index(t) { @@ -1091,43 +1194,8 @@ pub unsafe fn decommitted(a: usize, n: usize) { let (b, r) = (s.windows[wi].0, s.windows[wi].1.clone()); s.unmap_tiles(&r, b, &ts); } - let unmapped_any = !tiles.is_empty(); - for t in tiles { - if let Some(entry) = s.mapped.remove(&t) { - s.runs = None; - if !s.pinned.contains_key(&entry.pool) { - s.free.push(entry.pool); - } - } - } - if unmapped_any { - MAPPED_GEN.fetch_add(1, Ordering::Release); - } - // pages of tiles that stay mapped: holes, their video memory cleared (sent: None = zero; - // the title finds zeros there when it commits them again) - let mut pg = a & !(PAGE - 1); - let end = a + n; - while pg < end { - let t = pg & !(TILE - 1); - let tile_end = (t + TILE).min(end); - if let Some(entry) = s.mapped.get_mut(&t) { - let mut p = pg; - while p < tile_end { - let idx = (p - t) / PAGE; - entry.sent[idx] = None; - let bit = 1u16 << idx; - if entry.holes & bit == 0 { - entry.holes |= bit; - s.to_zero.push((p, PAGE)); - } - p += PAGE; - } - } - pg = tile_end; - } - if unmapped_any { - s.signal(); - } + MAPPED_GEN.fetch_add(1, Ordering::Release); + s.signal(); } impl State { @@ -1263,8 +1331,11 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D let start = va & !(TILE - 1); let delta = va - start; let bytes = desc.Width as usize; + if bytes == 0 { + return None; + } s.window_index(start)?; - s.window_index(va + bytes - 1)?; + s.window_index(va.checked_add(bytes)?.checked_sub(1)?)?; let mut d = *desc; d.Width = (delta + bytes) as u64; d.Alignment = 0; @@ -1278,8 +1349,9 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D if hr < 0 || ppv.is_null() || (*ppv).is_null() { return None; } - // its tiles: the window's video memory at the same addresses - s.ensure_mapped(start, delta + bytes); + // its tiles: the window's video memory at the same addresses; probe actual OS commitment + // so uncommitted pages (e.g. [start, va) or reserved tails) stay marked as holes + s.ensure_mapped(start, delta + bytes, |t| query_tile_holes(t)); let tiles: Vec<(usize, (u32, u32))> = (start..va + bytes).step_by(TILE).filter_map(|t| s.mapped.get(&t).map(|e| (t, e.pool))).collect(); let raw = *ppv; let res = ID3D12Resource::from_raw_borrowed(&raw)?.clone(); @@ -1379,4 +1451,202 @@ mod tests { assert_eq!((a, n), (cap as u64, 4096)); assert_eq!(a as usize % cap, 0); } + + /// `query_tile_holes` marks reserved, free, and `PAGE_NOACCESS` pages as holes while clearing + /// bits only for committed, accessible 4 KiB pages. + #[test] + fn query_tile_holes_detects_reserved_noaccess_and_committed_pages() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + + unsafe { + // SAFETY: Reserving 2 tiles (128 KiB) with VirtualAlloc returns a 64 KiB-aligned VA. + let base = VirtualAlloc(std::ptr::null(), 2 * TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert!(base != 0 && base % TILE == 0); + + // Initially every page in both reserved tiles is a hole. + assert_eq!(query_tile_holes(base), 0xFFFF); + assert_eq!(query_tile_holes(base + TILE), 0xFFFF); + + // Commit pages 4..8 as PAGE_READWRITE and page 9 as PAGE_NOACCESS. + let p4 = VirtualAlloc((base + 4 * PAGE) as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE); + assert!(!p4.is_null()); + let p9 = VirtualAlloc((base + 9 * PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_NOACCESS); + assert!(!p9.is_null()); + + // Only bits 4..8 are cleared; reserved [0..4), PAGE_NOACCESS [9], and reserved [10..16) remain holes. + assert_eq!(query_tile_holes(base), 0xFFFF & !(0b1111u16 << 4)); + assert_eq!(query_tile_holes(base + TILE), 0xFFFF); + + // Commit pages 0..4 and confirm bits 0..4 clear too. + let p0 = VirtualAlloc(base as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE); + assert!(!p0.is_null()); + assert_eq!(query_tile_holes(base), 0xFF00); + + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + // Released (MEM_FREE) memory reports all holes. + assert_eq!(query_tile_holes(base), 0xFFFF); + } + } + + /// Mapping tiles for a placed buffer over partially-committed/reserved memory must preserve + /// uncommitted hole bits so `readback_ranges` / `sync_sent_range` do not access-violate, + /// and later commits clear those hole bits so subsequent writes scan cleanly. + #[test] + fn ensure_mapped_with_query_holes_skips_uncommitted_pages_on_readback() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + + // Reserve 2 tiles; commit only [base + 0x4000, base + 0x8000) to simulate a + // non-64KiB-aligned placed buffer with uncommitted prefix [base, base + 0x4000) and + // uncommitted second tile [base + TILE, base + 2*TILE). + let base = VirtualAlloc(std::ptr::null(), 2 * TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert!(base != 0 && base % TILE == 0); + assert!(!VirtualAlloc((base + 4 * PAGE) as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + + let mut reserved: Option = None; + dev.CreateReservedResource(&buffer_desc((2 * TILE) as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved) + .expect("CreateReservedResource"); + let reserved = reserved.expect("reserved buffer"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); + rb_list.Close().expect("rb_list close"); + + let mut s = State { + dev, + queue, + fence, + value: 0, + event, + rb_fence, + rb_value: 0, + windows: vec![(base, reserved)], + pools: Vec::new(), + free: Vec::new(), + mapped: FxHashMap::default(), + pinned: 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: Vec::new(), + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + runs: None, + scratch_runs: Vec::new(), + }; + + // Mirrors `place_buffer`: map both tiles probing real OS page commitment. + s.ensure_mapped(base, 2 * TILE, |t| query_tile_holes(t)); + assert_eq!(s.mapped[&base].holes, 0xFF0F, "uncommitted prefix and suffix pages must stay holes"); + assert_eq!(s.mapped[&(base + TILE)].holes, 0xFFFF, "fully reserved tile must have all 16 holes set"); + + // Reading back the full 2-tile span must not fault on uncommitted pages. + s.readback_ranges(&[(base, 2 * TILE)]); + + // Now incrementally commit [base, base + 4*PAGE) and clear its hole bits (as `committed` does). + assert!(!VirtualAlloc(base as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + let entry = s.mapped.get_mut(&base).unwrap(); + for i in 0..4 { + entry.holes &= !(1u16 << i); + } + assert_eq!(entry.holes, 0xFF00); + + // Writing to the newly committed page is detected by `scan_page`. + *(base as *mut u8) = 0x5A; + let mut dirty = Vec::new(); + let page0 = std::slice::from_raw_parts(base as *const u8, PAGE); + scan_page(page0, base, &mut entry.sent[0], &mut dirty); + assert_eq!(dirty, vec![(base, CHUNK)]); + + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + /// Sub-tile decommits (two 32 KiB halves, sixteen 4 KiB pages, or decommitting the last + /// remaining committed page) must unmap the tile and return unpinned pool tiles to `free` + /// once `holes` reaches `0xFFFF`, pruning stale `to_zero` entries for unmapped tiles. + #[test] + fn decommit_sub_tile_reclaims_pool_tile_when_all_pages_become_holes() { + let mut mapped: FxHashMap = FxHashMap::default(); + let mut pinned: FxHashMap<(u32, u32), u32> = FxHashMap::default(); + let mut free: Vec<(u32, u32)> = Vec::new(); + let mut to_zero: Vec<(usize, usize)> = Vec::new(); + + // 1. Two 32 KiB decommits across a full 64 KiB tile. + let t0 = 0x10_0000usize; + mapped.insert(t0, TileEntry::with_holes((0, 10), 0)); + assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t0, TILE / 2).is_empty()); + assert_eq!(mapped[&t0].holes, 0x00FF); + assert_eq!(to_zero.len(), 8); + assert!(free.is_empty()); + + let unmapped = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t0 + TILE / 2, TILE / 2); + assert_eq!(unmapped, vec![t0]); + assert!(!mapped.contains_key(&t0)); + assert_eq!(free, vec![(0, 10)]); + assert!(to_zero.is_empty(), "stale to_zero entries for the unmapped tile must be pruned"); + + // 2. Sixteen individual 4 KiB decommits in reverse order. + let t1 = 0x20_0000usize; + free.clear(); + mapped.insert(t1, TileEntry::with_holes((0, 11), 0)); + for i in (1..PAGES_PER_TILE).rev() { + let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t1 + i * PAGE, PAGE); + assert!(u.is_empty(), "tile still has committed pages after step {i}"); + } + assert!(free.is_empty()); + let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t1, PAGE); + assert_eq!(u, vec![t1]); + assert!(!mapped.contains_key(&t1)); + assert_eq!(free, vec![(0, 11)]); + assert!(to_zero.is_empty()); + + // 3. Pinned tile decommitted in two halves: unmapped from `mapped`, NOT returned to `free`. + let t2 = 0x30_0000usize; + free.clear(); + mapped.insert(t2, TileEntry::with_holes((0, 12), 0)); + pinned.insert((0, 12), 1); + assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t2, TILE / 2).is_empty()); + let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t2 + TILE / 2, TILE / 2); + assert_eq!(u, vec![t2]); + assert!(!mapped.contains_key(&t2)); + assert!(free.is_empty(), "pinned pool tile must not return to free list"); + assert!(to_zero.is_empty()); + + // 4. Single-committed-page tile decommit reclaims tile without dropping another tile's to_zero. + let t3 = 0x40_0000usize; + let t4 = 0x50_0000usize; + mapped.insert(t3, TileEntry::with_holes((0, 13), 0xFFFF & !(1u16 << 2))); + mapped.insert(t4, TileEntry::with_holes((0, 14), 0)); + assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t4, PAGE).is_empty()); + assert_eq!(to_zero, vec![(t4, PAGE)]); + let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t3 + 2 * PAGE, PAGE); + assert_eq!(u, vec![t3]); + assert_eq!(free, vec![(0, 13)]); + assert_eq!(to_zero, vec![(t4, PAGE)], "unrelated mapped tile's to_zero must remain"); + } }