diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 3ff2a9793..50904c015 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2471,7 +2471,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, 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::CommandQueue => v.extend_from_slice(&[("Release", q_release as usize), ("Wait", q_wait 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(&[ ("Release", res_release as usize), @@ -5081,10 +5081,21 @@ unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { let n = f(this); if n == 0 { super::list_x::on_queue_release(this as usize); + super::sparse::forget_queue(this as usize); } n } +/// Wait: as on the PC; a title's wait is noted (`sparse::note_queue_wait`) +unsafe extern "system" fn q_wait(this: *mut c_void, fence: *mut c_void, value: u64) -> HRESULT { + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, 15)); + let hr = f(this, fence, value); + if hr >= 0 && !super::title_textures::is_own_work() { + super::sparse::note_queue_wait(this as usize, fence, value); + } + hr +} + unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); let n = f(this); @@ -5205,6 +5216,9 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a super::list_x::note_title_queue_wait(this as usize, a1, a2 as u64); } } + if older == 15 && hr >= 0 { + super::sparse::note_queue_wait(this as usize, a1 as *mut c_void, a2 as u64); + } hr as u32 as usize } 16 => { diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 0731890bf..351266fd5 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -204,9 +204,8 @@ struct State { value: u64, /// reusable auto-reset Win32 event for fence waits (no per-wait CreateEventW/CloseHandle) event: HANDLE, - /// fence signalled on title queues so `queue` waits before copying GPU writes back to CPU - rb_fence: ID3D12Fence, - rb_value: u64, + /// title queue → a fence it signals after the copies back of its GPU writes, its last value + rb_fences: FxHashMap, /// (window start, reserved buffer) of each sparse window windows: Vec<(usize, ID3D12Resource)>, /// video-memory pool heaps (None: given back, its index free for the next one) @@ -514,7 +513,6 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { 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 { @@ -537,8 +535,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { fence, value: 0, event, - rb_fence, - rb_value: 0, + rb_fences: FxHashMap::default(), windows, pools: Vec::new(), free: Vec::new(), @@ -1005,6 +1002,81 @@ impl State { } } + /// `parts` (address, offset at `p`, bytes) read back from video memory into the CPU view + /// (its committed pages), `sent` hashes following. + unsafe fn copy_back(&mut self, p: *const u8, parts: &[(usize, usize, usize)]) { + for &(dst, off, len) in parts { + let mut at = dst; + let mut src_off = off; + let end = dst + len; + while at < end { + let pg = at & !(PAGE - 1); + let t = pg & !(TILE - 1); + let idx = (pg - t) / PAGE; + let step = (pg + PAGE).min(end) - at; + if self.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { + std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); + } + at += step; + src_off += step; + } + self.sync_sent_range(dst, len); + } + } + + /// A copy of `ranges` (address, bytes) into a readback buffer, recorded on `queue` (after + /// what it has been given) and followed by a signal of that queue's own fence. + unsafe fn readback_on(&mut self, queue: &ID3D12CommandQueue, ranges: &[(usize, usize)]) -> Option { + let mut parts = Vec::new(); + let mut size = 0usize; + for &(a, n) in ranges { + let mut cur = a; + while cur < a + n { + let tile = cur & !(TILE - 1); + let step = (a + n).min(tile + TILE) - cur; + if self.mapped.contains_key(&tile) { + parts.push((cur, size, step)); + size += step; + } + cur += step; + } + } + if parts.is_empty() { + return None; + } + let ty = queue.GetDesc().Type; + let alloc: ID3D12CommandAllocator = self.dev.CreateCommandAllocator(ty).ok()?; + let list: ID3D12GraphicsCommandList = self.dev.CreateCommandList(0, ty, &alloc, None).ok()?; + let mut d = buffer_desc(size as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + let mut buf: Option = None; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + self.dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut buf).ok()?; + let buf = buf?; + // the fence before anything is submitted: from then on what the GPU uses stays alive + let q = queue.as_raw() as usize; + if !self.rb_fences.contains_key(&q) { + let f: ID3D12Fence = self.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + self.rb_fences.insert(q, (f, 0)); + } + for &(va, off, len) in &parts { + let wi = self.window_index(va)?; + list.CopyBufferRegion(&buf, off as u64, &self.windows[wi].1, (va - self.windows[wi].0) as u64, len as u64); + } + list.Close().ok()?; + let l: ID3D12CommandList = list.cast().ok()?; + let (fence, value) = self.rb_fences.get_mut(&q)?; + *value += 1; + let job = Readback { queue: q, fence: fence.clone(), value: *value, buf, parts, _list: (alloc, list) }; + super::title_textures::own_work(|| queue.ExecuteCommandLists(&[Some(l)])); + if queue.Signal(&job.fence, job.value).is_err() { + // nothing will tell when the copy is done: its buffer and list are never released + std::mem::forget(job); + return None; + } + Some(job) + } + /// Copy `ranges` (address, bytes) from sparse VRAM back into the CPU view and refresh /// `sent` hashes. Caller has already ordered `self.queue` after any GPU writes if needed. unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)]) { @@ -1027,24 +1099,7 @@ impl State { s.wait_for(s.value); s.reclaim_ring(); } - for &(dst, off, len) in pending.iter() { - // copy only committed (non-hole) bytes - let mut at = dst; - let mut src_off = off; - let end = dst + len; - while at < end { - let pg = at & !(PAGE - 1); - let t = pg & !(TILE - 1); - let idx = (pg - t) / PAGE; - let step = (pg + PAGE).min(end) - at; - if s.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { - std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); - } - at += step; - src_off += step; - } - s.sync_sent_range(dst, len); - } + s.copy_back(p, pending); pending.clear(); *used = 0; }; @@ -1222,15 +1277,18 @@ pub unsafe fn free(p: usize) -> bool { u.sparse_release(p).is_some() } -/// After `queue.ExecuteCommandLists`: copy GPU-written sparse ranges (e.g. `Write32/64`, -/// `FillMemoryWith32BitValueX`, `CopyMemoryToMemoryX`) back to their CPU view so CPU reads -/// and spin-waits see the GPU writes without clobbering `sent` hashes. /// The queue tile mappings go out on, once there is one. Answered without `STATE` (`QUEUE`): /// a caller may be inside a D3D12 call that a holder of `STATE` waits for. pub fn queue() -> Option { QUEUE.lock().unwrap().clone() } +/// After `queue.ExecuteCommandLists`: copy GPU-written sparse ranges (e.g. `Write32/64`, +/// `FillMemoryWith32BitValueX`, `CopyMemoryToMemoryX`) back to their CPU view so CPU reads +/// and spin-waits see the GPU writes without clobbering `sent` hashes. The copy runs on `queue` +/// after its lists and is waited for here, so the bytes are there when the title's call returns +/// – unless the queue may be held by a wait it was given (a fence a later submit signals: the +/// wait here would never end). Then a worker thread lands it once the GPU is there. pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)]) { if ranges.is_empty() { return; @@ -1252,12 +1310,128 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz _ => merged.push((a, n)), } } - s.rb_value += 1; - let v = s.rb_value; - if queue.Signal(&s.rb_fence, v).is_ok() { - let _ = s.queue.Wait(&s.rb_fence, v); + let Some(job) = s.readback_on(queue, &merged) else { return }; + drop(g); + let q = job.queue; + let mut unlanded = UNLANDED.lock().unwrap(); + let m = unlanded.get_or_insert_with(HashMap::new); + // (after an earlier one the worker has not landed: in order, so the worker too) + if may_be_held(q) || m.get(&q).is_some_and(|&n| n > 0) { + *m.entry(q).or_default() += 1; + drop(unlanded); + let _ = readback_worker().lock().unwrap().send(job); + return; } - s.readback_ranges(&merged); + drop(unlanded); + job.land(); +} + +/// title queue → GPU waits it was given that had not completed then +static WAITS: Mutex>>> = Mutex::new(None); +/// title queue → its copies back the worker has not landed yet +static UNLANDED: Mutex>> = Mutex::new(None); + +struct Held(ID3D12Fence, u64); + +// SAFETY: D3D12 objects are free-threaded +unsafe impl Send for Held {} + +/// The title's `queue` was told to wait until `fence` reaches `value`. +pub(super) unsafe fn note_queue_wait(queue: usize, fence: *mut c_void, value: u64) { + let Some(f) = ID3D12Fence::from_raw_borrowed(&fence) else { return }; + if f.GetCompletedValue() < value { + let mut g = WAITS.lock().unwrap(); + let w = g.get_or_insert_with(HashMap::new).entry(queue).or_default(); + // waits that completed since go here too, and of the waits for one fence only the + // highest value is kept (it completes last): a queue that waits every frame and never + // reads back would otherwise keep one entry, and the title's fence, per frame + w.retain(|h| h.0.GetCompletedValue() < h.1); + match w.iter_mut().find(|h| h.0 == *f) { + Some(h) => h.1 = h.1.max(value), + None => w.push(Held(f.clone(), value)), + } + } +} + +/// The title released `queue`: its waits are forgotten. +pub(super) fn forget_queue(queue: usize) { + if let Some(m) = WAITS.lock().unwrap().as_mut() { + m.remove(&queue); + } +} + +/// Whether a wait `queue` was given has not completed: its work may need a later submit to run. +fn may_be_held(queue: usize) -> bool { + let mut g = WAITS.lock().unwrap(); + let Some(w) = g.as_mut().and_then(|m| m.get_mut(&queue)) else { return false }; + w.retain(|h| unsafe { h.0.GetCompletedValue() } < h.1); + !w.is_empty() +} + +/// A copy back on a title queue: done when `fence` reaches `value`. +struct Readback { + queue: usize, + fence: ID3D12Fence, + value: u64, + buf: ID3D12Resource, + /// (address, offset in `buf`, bytes) + parts: Vec<(usize, usize, usize)>, + /// kept until the GPU is done with them + _list: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), +} + +// SAFETY: D3D12 objects are free-threaded; the rest is plain data +unsafe impl Send for Readback {} + +impl Readback { + /// Once the GPU is there (u64::MAX: the device is gone), into the CPU view. Returns only then: + /// the buffer and list are in use until it. + unsafe fn land(&self) { + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + if self.fence.GetCompletedValue() < self.value { + let event = CreateEventW(None, false, false, None).ok(); + while self.fence.GetCompletedValue() < self.value { + match event { + Some(e) if self.fence.SetEventOnCompletion(self.value, e).is_ok() => { + WaitForSingleObject(e, 10_000); + } + // no event: look again + _ => std::thread::sleep(std::time::Duration::from_millis(1)), + } + } + if let Some(e) = event { + let _ = CloseHandle(e); + } + } + let mut p = std::ptr::null_mut(); + if self.fence.GetCompletedValue() == u64::MAX || self.buf.Map(0, None, Some(&mut p)).is_err() { + return; + } + if let Some(s) = STATE.lock().unwrap().as_mut() { + s.copy_back(p as *const u8, &self.parts); + } + self.buf.Unmap(0, None); + } +} + +/// The thread that lands copies back in the CPU view, in submission order. +fn readback_worker() -> &'static Mutex> { + static W: std::sync::OnceLock>> = std::sync::OnceLock::new(); + W.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel::(); + let spawned = std::thread::Builder::new().name("xcl-sparse-readback".into()).spawn(move || unsafe { + for job in rx { + job.land(); + if let Some(n) = UNLANDED.lock().unwrap().as_mut().and_then(|m| m.get_mut(&job.queue)) { + *n -= 1; + } + } + }); + if let Err(e) = spawned { + crate::xlog_error!("sparse windows: no thread for copies back from video memory: {e}"); + } + Mutex::new(tx) + }) } /// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with @@ -1621,6 +1795,50 @@ mod tests { assert!(answered, "queue() waited for the sparse state's lock"); } + /// A queue that waits every frame and never reads back keeps one entry per fence it waits + /// for, not one per wait (#433 review: an entry and a fence reference per frame for the + /// whole run), and still counts as held while one of those waits has not completed. + #[test] + fn noted_queue_waits_stay_one_per_fence() { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + 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 (f, g): (ID3D12Fence, ID3D12Fence) = ( + dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"), + dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"), + ); + // a queue address no other test uses + let q = &f as *const ID3D12Fence as usize; + let len = || WAITS.lock().unwrap().as_ref().and_then(|m| m.get(&q)).map_or(0, |w| w.len()); + // frame i waits for f to reach i, which the frame before completed + for i in 1..=1000u64 { + f.Signal(i - 1).unwrap(); + note_queue_wait(q, f.as_raw(), i); + } + assert_eq!(len(), 1, "one entry for f"); + assert!(may_be_held(q), "f has not reached 1000"); + note_queue_wait(q, g.as_raw(), 5); + note_queue_wait(q, f.as_raw(), 999); + assert_eq!(len(), 2, "one entry for each fence"); + f.Signal(1000).unwrap(); + assert!(may_be_held(q), "g has not reached 5"); + g.Signal(5).unwrap(); + assert!(!may_be_held(q)); + note_queue_wait(q, g.as_raw(), 6); + forget_queue(q); + assert_eq!(len(), 0, "a released queue's waits are forgotten"); + } + } + /// A block freed on one thread while another allocates: its address goes back to the /// windows only once it is decommitted (released first, the decommit came after another /// thread had the same address again: that thread's writes faulted). @@ -1664,7 +1882,6 @@ mod tests { let dev = dev.expect("D3D12 device"); 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"); @@ -1675,8 +1892,7 @@ mod tests { fence, value: 0, event, - rb_fence, - rb_value: 0, + rb_fences: FxHashMap::default(), windows: Vec::new(), pools: Vec::new(), free: Vec::new(), @@ -1869,7 +2085,6 @@ mod tests { 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"); @@ -1881,8 +2096,7 @@ mod tests { fence, value: 0, event, - rb_fence, - rb_value: 0, + rb_fences: FxHashMap::default(), windows: vec![(base, reserved)], pools: Vec::new(), free: Vec::new(), @@ -1964,7 +2178,6 @@ mod tests { 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"); @@ -1976,8 +2189,7 @@ mod tests { fence, value: 0, event, - rb_fence, - rb_value: 0, + rb_fences: FxHashMap::default(), windows: vec![(base, reserved)], pools: Vec::new(), free: Vec::new(), diff --git a/crates/xcl/tests/sparse_readback_lands.rs b/crates/xcl/tests/sparse_readback_lands.rs new file mode 100644 index 000000000..a80400ed1 --- /dev/null +++ b/crates/xcl/tests/sparse_readback_lands.rs @@ -0,0 +1,83 @@ +//! What the GPU wrote into a sparse window is in the CPU's view when the title's own fence after +//! that work completes (`sparse::readback_after_execute`): a title waits for its fence and reads. + +use windows::core::Interface; +use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; +use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; +use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + +use xcl::hle::d3d12x::sparse; + +/// 20 times: a list writes 8 bytes of a sparse window, the title waits for its fence after it +/// and reads them at once. +#[test] +fn gpu_writes_are_there_when_the_titles_fence_completes() { + unsafe { + std::env::set_var("XCL_UMA_MB", "64"); + std::env::set_var("XCL_COHERENT_MB", "64"); + let Ok(dev) = xcl::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + println!("SKIPPED: no GPU"); + return; + }; + // the title's device: its queues and fences come with XCL's methods + xcl::hle::d3d12x::real::adopt(dev.as_raw(), xcl::hle::d3d12x::real::Kind::Device); + let windows = sparse::init(&dev); + let Some(&(k, raw, _)) = windows.first() else { + println!("SKIPPED: no sparse windows"); + return; + }; + let base = xcl::gpu::uma::get().unwrap().window(k).0; + let (a, _) = sparse::alloc_in(k, 0x1_0000, 0x1_0000).expect("sparse allocation"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let ev = CreateEventW(None, false, false, None).unwrap(); + let mut value = 0u64; + let mut wait = || { + value += 1; + queue.Signal(&fence, value).unwrap(); + fence.SetEventOnCompletion(value, ev).unwrap(); + assert_eq!(WaitForSingleObject(ev, 5000), WAIT_OBJECT_0, "the queue did not finish"); + }; + // as before each of the title's submits (the tile mappings), done + sparse::before_execute(&queue, &[], 0x1000); + wait(); + + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut src: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut src).unwrap(); + let src = src.unwrap(); + let mut p = std::ptr::null_mut(); + src.Map(0, None, Some(&mut p)).unwrap(); + let raw = raw as *mut std::ffi::c_void; + let window = ID3D12Resource::from_raw_borrowed(&raw).unwrap(); + let al: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &al, None).unwrap(); + list.Close().unwrap(); + for i in 0..20u64 { + let want = 0x1122_3344_0000_0000 | i; + *(p as *mut u64) = want; + al.Reset().unwrap(); + list.Reset(&al, None).unwrap(); + list.CopyBufferRegion(window, (a - base) as u64, &src, 0, 8); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + sparse::readback_after_execute(&queue, &[(a, 8)]); + wait(); + let got = *(a as *const u64); + assert_eq!(got, want, "round {i}: the CPU's view after the title's fence wait"); + } + let _ = CloseHandle(ev); + } +} diff --git a/crates/xcl/tests/sparse_readback_waits.rs b/crates/xcl/tests/sparse_readback_waits.rs new file mode 100644 index 000000000..7bd17f22f --- /dev/null +++ b/crates/xcl/tests/sparse_readback_waits.rs @@ -0,0 +1,106 @@ +//! A title's queue may GPU-wait for a fence that a later submit signals (async compute). When +//! its lists write sparse memory on the GPU, the copy back to the CPU's view +//! (`sparse::readback_after_execute`, after its ExecuteCommandLists) must not wait for them on +//! the CPU: the later submit, which lets them run, would never come. + +use windows::core::Interface; +use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; +use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; +use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + +use xcl::hle::d3d12x::sparse; + +/// The title's thread: queue A waits for F, runs a list writing 8 bytes of a sparse window, and +/// is read back; then queue B submits and signals F. A finishes within 5 s. +#[test] +fn a_readback_behind_a_wait_for_a_later_signal_does_not_hang() { + unsafe { + std::env::set_var("XCL_UMA_MB", "64"); + std::env::set_var("XCL_COHERENT_MB", "64"); + let Ok(dev) = xcl::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + println!("SKIPPED: no GPU"); + return; + }; + // the title's device: its queues and fences come with XCL's methods + xcl::hle::d3d12x::real::adopt(dev.as_raw(), xcl::hle::d3d12x::real::Kind::Device); + let windows = sparse::init(&dev); + let Some(&(k, raw, _)) = windows.first() else { + println!("SKIPPED: no sparse windows"); + return; + }; + let base = xcl::gpu::uma::get().unwrap().window(k).0; + let (a, _) = sparse::alloc_in(k, 0x1_0000, 0x1_0000).expect("sparse allocation"); + let qa: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let qb: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let f: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + // A's list: 8 bytes from a buffer of the title's into the window + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut src: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut src).unwrap(); + let src = src.unwrap(); + let mut p = std::ptr::null_mut(); + src.Map(0, None, Some(&mut p)).unwrap(); + *(p as *mut u64) = 0x1122_3344_5566_7788; + let raw = raw as *mut std::ffi::c_void; + let window = ID3D12Resource::from_raw_borrowed(&raw).unwrap(); + let al: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let la: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &al, None).unwrap(); + la.CopyBufferRegion(window, (a - base) as u64, &src, 0, 8); + la.Close().unwrap(); + let bl: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let lb: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &bl, None).unwrap(); + lb.Close().unwrap(); + sparse::before_execute(&qa, &[], 0x1000); + + // the title's thread + let (qa2, qb2, f2, done2) = (qa.clone(), qb.clone(), f.clone(), done.clone()); + let (la, lb) = (la.cast::().unwrap(), lb.cast::().unwrap()); + let title = std::thread::spawn(move || { + qa2.Wait(&f2, 1).unwrap(); + qa2.ExecuteCommandLists(&[Some(la)]); + sparse::readback_after_execute(&qa2, &[(a, 8)]); + qa2.Signal(&done2, 1).unwrap(); + sparse::before_execute(&qb2, &[], 0x1000); + qb2.ExecuteCommandLists(&[Some(lb)]); + qb2.Signal(&f2, 1).unwrap(); + }); + + let ev = CreateEventW(None, false, false, None).unwrap(); + done.SetEventOnCompletion(1, ev).unwrap(); + let finished = WaitForSingleObject(ev, 5000) == WAIT_OBJECT_0; + if !finished { + // let the queues go so the process can end + f.Signal(1).unwrap(); + } + title.join().unwrap(); + let _ = CloseHandle(ev); + assert!(finished, "queue A did not finish in 5 s: the readback waits on the CPU for A, which waits for B's later submit"); + // the GPU's write reaches the CPU's view + let got = *(a as *const u64); + let ev = CreateEventW(None, false, false, None).unwrap(); + let mut seen = got == 0x1122_3344_5566_7788; + for _ in 0..100 { + if seen { + break; + } + let _ = WaitForSingleObject(ev, 10); + seen = *(a as *const u64) == 0x1122_3344_5566_7788; + } + let _ = CloseHandle(ev); + assert!(seen, "the GPU's write did not reach the CPU's view: {got:#x}"); + } +}