diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 91eb2ba351..491264b2fd 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -20,7 +20,7 @@ use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; use std::hash::{BuildHasherDefault, Hasher}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Mutex; +use std::sync::{Mutex, MutexGuard}; use windows::core::Interface; use windows::Win32::Foundation::{CloseHandle, HANDLE}; @@ -47,6 +47,8 @@ const UPLOAD_SLOTS: usize = 16; const ZERO_BUF: usize = 1 << 20; /// bytes of the GPU→CPU readback staging buffer const READBACK_STAGING: usize = 16 << 20; +/// bytes of the upload ring that are free before a part of the uploads starts (`upload_room`) +const RING_ROOM: usize = 1 << 20; const PAGE: usize = 0x1000; const PAGES_PER_TILE: usize = TILE / PAGE; @@ -91,11 +93,21 @@ struct TileEntry { holes: u16, /// per-4 KiB-page hashes of the 64-byte chunks last sent to the GPU (`None` = all zero) sent: [Option>; PAGES_PER_TILE], + /// changes (`next_tile_gen`) when the tile is mapped or pages of it are committed or + /// decommitted: a copy back taken before must not land in it (`copy_back`) + gen: u64, +} + +/// source of `TileEntry::gen`, never the same twice (a tile unmapped and mapped again included) +static TILE_GEN: AtomicU64 = AtomicU64::new(1); + +fn next_tile_gen() -> u64 { + TILE_GEN.fetch_add(1, Ordering::Relaxed) } impl TileEntry { fn with_holes(pool: (u32, u32), holes: u16) -> Self { - Self { pool, holes, sent: std::array::from_fn(|_| None) } + Self { pool, holes, sent: std::array::from_fn(|_| None), gen: next_tile_gen() } } } @@ -163,6 +175,9 @@ fn decommit_tiles( } p += PAGE; } + if newly_holed != 0 { + entry.gen = next_tile_gen(); + } if entry.holes == 0xFFFF { unmapped.push(t); } else if newly_holed != 0 { @@ -405,6 +420,111 @@ static STATE: Mutex> = Mutex::new(None); /// (a list's `Reset`, with `XCL_DRED=1` on every start): the two then waited for each other. static QUEUE: Mutex> = Mutex::new(None); +/// One copy back at a time (`readback_released`): the readback buffer and its list are in use +/// until the copy is done, and that is waited for with `STATE` released. Taken before `STATE`, +/// never under it. +static READBACK: Mutex<()> = Mutex::new(()); + +/// Wait, 5 s at most, until `fence` has reached `target` (true: it has; a removed device counts). +/// Not for a holder of `STATE`: `wait_released`. +unsafe fn wait_fence(fence: &ID3D12Fence, target: u64) -> bool { + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + thread_local! { + /// this thread's event for its waits (a wait given up leaves it registered with the + /// fence: it is never closed, and a wait looks at the fence again when it is set) + static EVENT: HANDLE = unsafe { CreateEventW(None, false, false, None) }.unwrap_or_default(); + } + let event = EVENT.with(|e| *e); + let start = std::time::Instant::now(); + loop { + let at = fence.GetCompletedValue(); + if at >= target { + return true; + } + let left = 5000u32.saturating_sub(start.elapsed().as_millis() as u32); + if left == 0 { + crate::xlog_warn!("sparse: the queue has not reached fence value {target} after 5 s (at {at})"); + return false; + } + if !event.is_invalid() && fence.SetEventOnCompletion(target, event).is_ok() { + WaitForSingleObject(event, left); + } else { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } +} + +/// Wait (`wait_fence`) until the state's queue has reached fence `value` with `STATE` released, +/// and take it again. The queue can stand still for as long as the GPU does, and the title's +/// other threads need the lock meanwhile – a submit, a commit, a `Map` (a retail title: a `Map` +/// waited 15 s for its copy back holding it, then a submit for room in the upload ring until the +/// title's watchdog ended it; a thread moving physical pages and the next `Map` stood at the +/// lock all that time). True: the queue of the same state got there. Anything the caller knew +/// of the state has to be looked at again. +unsafe fn wait_released(g: MutexGuard<'static, Option>, value: u64) -> (MutexGuard<'static, Option>, bool) { + let Some(fence) = g.as_ref().map(|s| s.fence.clone()) else { return (g, false) }; + drop(g); + let reached = wait_fence(&fence, value); + let g = lock_state(); + let same = g.as_ref().is_some_and(|s| s.fence.as_raw() == fence.as_raw()); + (g, reached && same) +} + +/// `upload_room(least)` of the state, waited for with `STATE` released (`wait_released`) – until +/// there is room if `patient`, else once. None: there is no state, or no room after that wait. +unsafe fn room_released(mut g: MutexGuard<'static, Option>, least: usize, patient: bool) -> (MutexGuard<'static, Option>, Option) { + loop { + let value = match g.as_mut().map(|s| s.upload_room(least)) { + None => return (g, None), + Some(Ok(room)) => return (g, Some(room)), + Some(Err(value)) => value, + }; + let (again, there) = wait_released(g, value); + g = again; + if !there && !patient { + return (g, None); + } + } +} + +/// Copy `ranges` (address, bytes) from sparse VRAM back into the CPU view, a readback buffer's +/// worth at a time: submitted, waited for with `STATE` released, and copied into the pages that +/// are still committed then. If the queue is not there after 5 s the CPU's view stays as it is +/// (the buffer does not hold the copy). The caller holds `READBACK`. +unsafe fn readback_released(mut g: MutexGuard<'static, Option>, ranges: &[(usize, usize)]) { + for &(a, n) in ranges { + let mut at = a; + while at < a + n { + let Some(s) = g.as_mut() else { return }; + // (a copy given up earlier: its list and the buffer are still in use) + let last = s.rb_last_fence; + if last != 0 && s.fence.GetCompletedValue() < last { + let (again, there) = wait_released(g, last); + g = again; + if !there { + return; + } + continue; + } + let Some((rb, p)) = s.readback_buf() else { return }; + let (next, parts) = s.readback_submit(&rb, at, a + n); + at = next; + if parts.is_empty() { + continue; + } + let value = s.value; + let (again, there) = wait_released(g, value); + g = again; + if !there { + return; + } + if let Some(s) = g.as_mut() { + s.copy_back(p, &parts); + } + } + } +} + /// (bytes of video memory in pool heaps, of those mapped) – `XCL_ACTIVITY` pub fn pool_bytes() -> (usize, usize) { let g = lock_state(); @@ -844,6 +964,44 @@ impl State { } } + /// The bytes of CPU pages (`least` or more; 0: only tile clears, which take none of the ring) + /// an `upload_zeros` and an `upload_dirty` can take now without waiting for the GPU: their + /// two command slots are free and the ring has that much room. Err: the fence value to wait + /// for first (`room_released`, not under the lock). Callers ask before each part of their + /// uploads, so the waits in `begin_slot` and `upload_dirty`, which hold the lock, are not met. + unsafe fn upload_room(&mut self, least: usize) -> Result { + if least == 0 && self.to_zero.is_empty() { + return Ok(0); + } + self.reclaim_ring(); + let completed = self.fence.GetCompletedValue(); + for k in 0..self.slots.len().min(2) { + let fv = self.slots[(self.next_slot + k) % self.slots.len()].fence_val; + if fv > completed { + return Err(fv); + } + } + // (a chunk that does not fit before the ring's end skips less than a page of it) + let room = (STAGING - (self.ring_write - self.ring_free) as usize).saturating_sub(PAGE); + match self.inflight.front() { + Some(&(fv, _)) if least > 0 && room < least.max(RING_ROOM) => Err(fv), + _ => Ok(room), + } + } + + /// The tiles and pages waiting to be cleared (`to_zero`) are, before CPU writes into them + /// are uploaded (overlapping CopyBufferRegion destinations: no WAW hazard). Returns them. + unsafe fn flush_zeros(&mut self) -> Vec<(usize, usize)> { + let zeroed = std::mem::take(&mut self.to_zero); + for &(a, n) in &zeroed { + self.clear_sent_range(a, n); + } + if !zeroed.is_empty() { + self.upload_zeros(&zeroed); + } + zeroed + } + /// Acquire the next upload command slot, waiting only if that slot's previous submission is /// still executing on the GPU, then reset its allocator and list. unsafe fn begin_slot(&mut self) -> usize { @@ -1005,84 +1163,79 @@ impl State { } } - /// 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)]) { - let Some((rb, p)) = self.readback_buf() else { return }; - let mut pending: Vec<(usize, usize, usize)> = Vec::new(); // (va, rb_off, chunk) - let mut used = 0usize; - let mut open = false; - let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| { - if *open { - *open = false; - if s.rb_list.Close().is_ok() { - if let Ok(l) = s.rb_list.cast::() { - super::title_textures::own_work(|| { - s.queue.ExecuteCommandLists(&[Some(l)]); - }); - } - } - s.signal(); - s.rb_last_fence = s.value; - s.wait_for(s.value); - s.reclaim_ring(); + /// `parts` (address, offset at `p`, bytes, tile's `gen` then) read back from video memory + /// into the CPU view (its committed pages), `sent` hashes following. A part whose tile was + /// mapped again or had pages committed or decommitted since its copy was taken (the wait for + /// it is made with `STATE` released) is left as it is: the copy holds what the tile had + /// before, and the CPU's view what it has now. + unsafe fn copy_back(&mut self, p: *const u8, parts: &[(usize, usize, usize, u64)]) { + for &(dst, off, len, gen) in parts { + if self.mapped.get(&(dst & !(TILE - 1))).is_none_or(|e| e.gen != gen) { + continue; } - 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; + 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); } - s.sync_sent_range(dst, len); + at += step; + src_off += step; } - pending.clear(); - *used = 0; - }; - for &(a, n) in ranges { - if n == 0 { + self.sync_sent_range(dst, len); + } + } + + /// A copy of what `[from, end)` has in sparse VRAM into the readback buffer `rb`, as much as + /// fits, submitted on the state's queue and signalled (`self.value`). Returns where it + /// stopped and the parts copied (address, offset in `rb`, bytes, tile's `gen`; a part is + /// in one tile), for `copy_back` once the + /// queue is there (`readback_released`). The copy before it is done (`rb_last_fence`): its + /// list is used again. Caller has already ordered `self.queue` after any GPU writes if needed. + unsafe fn readback_submit(&mut self, rb: &ID3D12Resource, from: usize, end: usize) -> (usize, Vec<(usize, usize, usize, u64)>) { + let mut parts: Vec<(usize, usize, usize, u64)> = Vec::new(); + let mut used = 0usize; + let mut cur = from; + while cur < end && used < READBACK_STAGING { + let tile = cur & !(TILE - 1); + let Some(wi) = self.window_index(cur) else { + cur = end; + break; + }; + let b = self.windows[wi].0; + let to_tile_end = (tile + TILE) - cur; + let Some(gen) = self.mapped.get(&tile).map(|e| e.gen) else { + cur += (end - cur).min(to_tile_end); continue; + }; + let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; + let chunk = (end - cur).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); + if parts.is_empty() { + let _ = self.rb_alloc.Reset(); + let _ = self.rb_list.Reset(&self.rb_alloc, None); } - let mut done = 0usize; - while done < n { - let cur = a + done; - let tile = cur & !(TILE - 1); - let Some(wi) = self.window_index(cur) else { break }; - let b = self.windows[wi].0; - let to_tile_end = (tile + TILE) - cur; - if !self.mapped.contains_key(&tile) { - done += (n - done).min(to_tile_end); - continue; - } - if used == READBACK_STAGING { - flush_and_copy(self, &mut open, &mut pending, &mut used, p); - } - let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; - let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); - if !open { - self.wait_for(self.rb_last_fence); - let _ = self.rb_alloc.Reset(); - let _ = self.rb_list.Reset(&self.rb_alloc, None); - open = true; + self.rb_list.CopyBufferRegion(rb, used as u64, &self.windows[wi].1, (cur - b) as u64, chunk as u64); + parts.push((cur, used, chunk, gen)); + used += chunk; + cur += chunk; + } + if !parts.is_empty() { + if self.rb_list.Close().is_ok() { + if let Ok(l) = self.rb_list.cast::() { + super::title_textures::own_work(|| { + self.queue.ExecuteCommandLists(&[Some(l)]); + }); } - self.rb_list.CopyBufferRegion(&rb, used as u64, &self.windows[wi].1, (cur - b) as u64, chunk as u64); - pending.push((cur, used, chunk)); - used += chunk; - done += chunk; } + self.signal(); + self.rb_last_fence = self.value; } - if open { - flush_and_copy(self, &mut open, &mut pending, &mut used, p); - } + (cur, parts) } /// Asynchronously zero `runs` (address, bytes) in sparse VRAM using the pre-zeroed `zero_buf` @@ -1235,6 +1388,7 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz if ranges.is_empty() { return; } + let _one = READBACK.lock().unwrap(); let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); @@ -1258,34 +1412,43 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz let _ = s.queue.Wait(&s.rb_fence, v); super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); } - s.readback_ranges(&merged); + readback_released(g, &merged); } /// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with /// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): flushes pending /// tile clears and unsubmitted CPU-changed chunks first so CPU writes are preserved, then -/// copies the range back from VRAM into CPU memory. +/// copies the range back from VRAM into CPU memory. The GPU is waited for with the state +/// unlocked; if the sparse queue is not there after 5 s, the CPU's view stays as it is. pub unsafe fn readback_now(va: usize, len: usize) { if len == 0 { return; } + let _one = READBACK.lock().unwrap(); let mut g = lock_state(); - let Some(s) = g.as_mut() else { return }; + let Some(mut s) = g.as_mut() else { return }; if s.window_index(va).is_none() { return; } - let zeroed = std::mem::take(&mut s.to_zero); - if !zeroed.is_empty() { - for &(a, n) in &zeroed { - s.clear_sent_range(a, n); - } - s.upload_zeros(&zeroed); - } - // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` + // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)`, a part at a + // time: as much as the upload ring has room for, scanned and uploaded in one hold of the lock let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); let mut pg = va & !(PAGE - 1); let end = va + len; + let mut left = 0usize; while pg < end { + if left < TILE { + s.upload_dirty(&dirty_runs); + dirty_runs.clear(); + // (no room after 5 s: no copy back over CPU writes that could not be sent first) + let (again, room) = room_released(g, TILE, false); + g = again; + let (Some(next), Some(room)) = (g.as_mut(), room) else { return }; + s = next; + left = room; + s.flush_zeros(); + } + left -= TILE; let t = pg & !(TILE - 1); let tile_end = (t + TILE).min(end); if let Some(entry) = s.mapped.get_mut(&t) { @@ -1304,7 +1467,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { if !dirty_runs.is_empty() { s.upload_dirty(&dirty_runs); } - s.readback_ranges(&[(va, len)]); + readback_released(g, &[(va, len)]); } /// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that @@ -1348,11 +1511,15 @@ impl State { let t = pg & !(TILE - 1); let tile_end = t.saturating_add(TILE).min(end); if let Some(entry) = self.mapped.get_mut(&t) { + let was = entry.holes; let mut p = pg; while p < tile_end { entry.holes &= !(1u16 << ((p - t) / PAGE)); p += PAGE; } + if entry.holes != was { + entry.gen = next_tile_gen(); + } } if tile_end <= pg { break; @@ -1456,7 +1623,9 @@ pub fn note_watch(t: std::time::Duration, pages: usize) { /// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB /// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video -/// memory, and `queue` GPU-waits for that and for new tile mappings. +/// memory, and `queue` GPU-waits for that and for new tile mappings. The pages go a part at a +/// time, each as large as the upload ring has room for: scanned and uploaded in one hold of the +/// lock, the room waited for with it released. pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) { let t0 = std::time::Instant::now(); let mut g = lock_state(); @@ -1467,21 +1636,37 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: } let t_locked = std::time::Instant::now(); PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Ordering::Relaxed); - let zero_runs = std::mem::take(&mut s.to_zero); - for &(a, n) in &zero_runs { - s.clear_sent_range(a, n); - } + let (again, room) = room_released(g, if dirty.is_empty() { 0 } else { page }, true); + g = again; + let (Some(mut s), Some(mut left)) = (g.as_mut(), room) else { return }; + // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. + let zero_runs = s.flush_zeros(); let mut dirty_runs = std::mem::take(&mut s.scratch_runs); dirty_runs.clear(); + // (runs, bytes) of the parts sent before the last + let mut sent = (0usize, 0usize); let mut i = 0; while i < dirty.len() { + if left < page { + // this part goes; the next has the room the ring has then + s.upload_dirty(&dirty_runs); + sent = (sent.0 + dirty_runs.len(), sent.1 + dirty_runs.iter().map(|r| r.1).sum::()); + dirty_runs.clear(); + let (again, room) = room_released(g, page, true); + g = again; + let (Some(next), Some(room)) = (g.as_mut(), room) else { return }; + s = next; + left = room; + s.flush_zeros(); + } let a = dirty[i]; let mut n = page; i += 1; - while i < dirty.len() && dirty[i] == a + n { + while i < dirty.len() && dirty[i] == a + n && n + page <= left { n += page; i += 1; } + left -= n; // only what has video memory (committed tiles of a sparse window) let mut x = a; while x < a + n { @@ -1503,11 +1688,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: } let t_scanned = std::time::Instant::now(); PHASES[1].fetch_add((t_scanned - t_locked).as_micros() as u64, Ordering::Relaxed); - PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); - // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. - if !zero_runs.is_empty() { - s.upload_zeros(&zero_runs); - } + PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len() + sent.0) as u64, Ordering::Relaxed); if !dirty_runs.is_empty() { s.upload_dirty(&dirty_runs); } @@ -1516,7 +1697,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: static CALLS: AtomicU64 = AtomicU64::new(0); static BYTES: AtomicU64 = AtomicU64::new(0); static MICROS: AtomicU64 = AtomicU64::new(0); - let bytes: usize = zero_runs.iter().chain(dirty_runs.iter()).map(|r| r.1).sum(); + let bytes: usize = zero_runs.iter().chain(dirty_runs.iter()).map(|r| r.1).sum::() + sent.1; let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; let b = BYTES.fetch_add(bytes as u64, Ordering::Relaxed) + bytes as u64; let us = MICROS.fetch_add(t0.elapsed().as_micros() as u64, Ordering::Relaxed) + t0.elapsed().as_micros() as u64; @@ -1981,7 +2162,10 @@ mod tests { 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)]); + let (rb, p) = s.readback_buf().expect("readback buffer"); + let (_, parts) = s.readback_submit(&rb, base, base + 2 * TILE); + s.wait_for(s.value); + s.copy_back(p, &parts); // 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()); diff --git a/crates/xcl/tests/sparse_lock_released.rs b/crates/xcl/tests/sparse_lock_released.rs new file mode 100644 index 0000000000..4dca1299c0 --- /dev/null +++ b/crates/xcl/tests/sparse_lock_released.rs @@ -0,0 +1,181 @@ +//! XCL's queue for the sparse windows (tile mappings, uploads of CPU writes, copies back) can +//! stand still for as long as the GPU does. A thread that waits for it – a `Map` for its copy +//! back (`sparse::readback_now`), a submit for room in the upload ring (`sparse::before_execute`) +//! – must not hold the sparse state's lock meanwhile: the title's other threads (a commit, the +//! next submit) need it, and what they do may be what lets the GPU go on. And what the waits +//! are for still holds: the `Map` returns with the GPU's bytes, the submit with all of its +//! uploads made. + +use std::sync::mpsc::channel; +use std::time::Duration; + +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 windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_DECOMMIT, PAGE_READWRITE}; + +use xcl::hle::d3d12x::sparse; + +const TILE: usize = 0x1_0000; +const PAGE: usize = 0x1000; +/// more than the upload ring holds (64 MiB) +const BIG: usize = 96 << 20; + +/// A commit and a submit on another thread, as the title's other threads make them: whether +/// they were through within 2 s. +unsafe fn others_get_the_lock(k: usize, queue: &ID3D12CommandQueue) -> bool { + let (tx, rx) = channel(); + let queue = queue.clone(); + let other = std::thread::spawn(move || { + let _ = sparse::alloc_in(k, TILE, TILE); + sparse::before_execute(&queue, &[], PAGE); + let _ = tx.send(()); + }); + let through = rx.recv_timeout(Duration::from_secs(2)).is_ok(); + // (joined by the caller's release of the queue; a thread left behind ends with the process) + if through { + other.join().unwrap(); + } + through +} + +#[test] +fn a_wait_for_the_sparse_queue_does_not_hold_the_state() { + 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 { + return xcl::gpu::recomp::runner::skip_test("no GPU"); + }; + let windows = sparse::init(&dev); + let Some(&(k, raw, _)) = windows.first() else { + return xcl::gpu::recomp::runner::skip_test("no GPU"); + }; + let base = xcl::gpu::uma::get().unwrap().window(k).0; + let raw = raw as *mut std::ffi::c_void; + let window = ID3D12Resource::from_raw_borrowed(&raw).unwrap(); + let (a, _) = sparse::alloc_in(k, TILE, TILE).expect("sparse allocation"); + let (big, _) = sparse::alloc_in(k, BIG, TILE).expect("sparse allocation"); + let sparse_queue = sparse::queue().expect("the sparse queue"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let other: 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 = |what: &str| { + value += 1; + queue.Signal(&fence, value).unwrap(); + fence.SetEventOnCompletion(value, ev).unwrap(); + assert_eq!(WaitForSingleObject(ev, 20_000), WAIT_OBJECT_0, "the title's queue did not finish: {what}"); + }; + + // a buffer of the title's (CPU-visible both ways) and a list of its queue + 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 buffer = |heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| { + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap(); + let r = r.unwrap(); + let mut p = std::ptr::null_mut(); + r.Map(0, None, Some(&mut p)).unwrap(); + (r, p as *mut u64) + }; + let (src, src_p) = buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let (dst, dst_p) = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + 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(); + + // 1. a Map. The GPU writes 8 bytes at `a` (the CPU's view holds zeros) + *src_p = 0x1122_3344_5566_7788; + list.CopyBufferRegion(window, (a - base) as u64, &src, 0, 8); + list.Close().unwrap(); + sparse::before_execute(&queue, &[], PAGE); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + wait("the GPU's write"); + // the sparse queue stands still, and a thread of the title's maps the bytes to read them + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + sparse_queue.Wait(&gate, 1).unwrap(); + let map = std::thread::spawn(move || { + sparse::readback_now(a, 8); + *(a as *const u64) + }); + std::thread::sleep(Duration::from_millis(500)); + let map_released = others_get_the_lock(k, &other); + gate.Signal(1).unwrap(); + let read = map.join().unwrap(); + + // 2. a submit with more CPU writes than the upload ring holds, the sparse queue still again + for i in (0..BIG).step_by(8) { + *((big + i) as *mut u64) = 0xA5A5_0000_0000_0000 | i as u64; + } + let dirty: Vec = (big..big + BIG).step_by(PAGE).collect(); + sparse_queue.Wait(&gate, 2).unwrap(); + let (tx, rx) = channel(); + let q = queue.clone(); + let submit = std::thread::spawn(move || { + sparse::before_execute(&q, &dirty, PAGE); + let _ = tx.send(()); + }); + std::thread::sleep(Duration::from_millis(500)); + let submit_released = others_get_the_lock(k, &other); + let waited = rx.try_recv().is_err(); + gate.Signal(2).unwrap(); + let uploaded = rx.recv_timeout(Duration::from_secs(20)).is_ok(); + assert!(uploaded, "the submit's uploads did not finish once the sparse queue went on"); + submit.join().unwrap(); + // what video memory holds at the start and the end of the block, after the queue's wait + al.Reset().unwrap(); + list.Reset(&al, None).unwrap(); + list.CopyBufferRegion(&dst, 0, window, (big - base) as u64, 8); + list.CopyBufferRegion(&dst, 8, window, (big + BIG - 8 - base) as u64, 8); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + wait("the copy of the uploads"); + + // 3. a Map whose tile is decommitted and committed again while its copy back waits: the + // copy holds what the tile had before, and must not land in the newly committed pages + let (c, _) = sparse::alloc_in(k, TILE, TILE).expect("sparse allocation"); + *src_p = 0x0BAD_0BAD_0BAD_0BAD; + al.Reset().unwrap(); + list.Reset(&al, None).unwrap(); + list.CopyBufferRegion(window, (c - base) as u64, &src, 0, 8); + list.Close().unwrap(); + sparse::before_execute(&queue, &[], PAGE); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + wait("the GPU's write before the decommit"); + sparse_queue.Wait(&gate, 3).unwrap(); + let map = std::thread::spawn(move || sparse::readback_now(c, 8)); + std::thread::sleep(Duration::from_millis(500)); + sparse::decommitted(c, TILE); + assert!(VirtualFree(c as *mut _, TILE, MEM_DECOMMIT) != 0); + assert!(!VirtualAlloc(c as *const _, TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); + sparse::committed(c, TILE); + gate.Signal(3).unwrap(); + map.join().unwrap(); + let recommitted = *(c as *const u64); + let _ = CloseHandle(ev); + + assert!( + map_released && submit_released, + "a commit and a submit on another thread waited for the sparse state's lock while its holder waited for the sparse queue \ + (through within 2 s – behind a Map: {map_released}, behind a submit: {submit_released})" + ); + assert_eq!(read, 0x1122_3344_5566_7788, "the Map returned without the GPU's write in the CPU's view"); + assert!(waited, "the submit was to wait for room in the upload ring: the test does not cover it"); + assert_eq!(*dst_p, 0xA5A5_0000_0000_0000, "the first CPU write of the submit is not in video memory"); + assert_eq!(*dst_p.add(1), 0xA5A5_0000_0000_0000 | (BIG - 8) as u64, "the last CPU write of the submit is not in video memory"); + assert_eq!(recommitted, 0, "a copy back taken before its tile was decommitted and committed again landed in the new pages"); + } +}