diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 8674cdacf..13b7d7107 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -87,6 +87,17 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { console_list::hold_until_reset(old, blocks); } +/// Continue on a distinct PC list using the same allocator and root arguments. The arena +/// moves with the recording; previously recorded commands still reference its allocations. +pub(super) fn continue_recording(from: *mut c_void, to: *mut c_void) { + let mut states = STATES.lock().unwrap(); + if let Some(m) = states.as_mut() { + if let Some(s) = m.remove(&(from as usize)) { + m.insert(to as usize, s); + } + } +} + /// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults /// with `pso` bound, keeping the current recording's allocator and UMA arena intact. pub(super) fn clear_state(list: *mut c_void, pso: usize) { diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index eb5200650..7f40b8b14 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -4,19 +4,21 @@ //! A console title marks its GPU progress with bottom-of-pipe writes into its own memory and //! waits on them (a retail game: plain `VirtualAlloc` memory, outside XCL's unified memory). //! The PC GPU cannot write there; dropped, the title waited for ever after its second frame. -//! Here each queue gets a fence of XCL's: after a submission whose lists carry such writes the -//! queue signals it, and a worker thread does the writes, in submission order, when the GPU is -//! there – what bottom of pipe means. +//! Each queue gets its own fence and worker (adapted from https://github.com/ivall/xcl/pull/562). +//! After a submission with such writes, the queue signals its fence and the worker writes in +//! submission order. A stalled queue cannot block completed writes from another queue. use std::collections::HashMap; use std::ffi::c_void; use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; -use std::sync::{mpsc, Mutex, OnceLock}; +use std::sync::{mpsc, Mutex}; +use std::time::Duration; -use windows::core::Interface; -use windows::Win32::Foundation::HANDLE; +use windows::core::{Interface, Owned}; use windows::Win32::Graphics::Direct3D12::*; -use windows_sys::Win32::System::Threading as th; +use windows::Win32::System::Threading::CreateEventW; + +use crate::gpu::fence::{self, FenceError}; /// A bottom-of-pipe write into memory outside unified memory, applied by the CPU once the /// queue's fence reaches the submission that recorded it. @@ -24,6 +26,8 @@ use windows_sys::Win32::System::Threading as th; pub(super) enum Write { /// Immediate dwords to store starting at `va`. Immediate(usize, Vec), + /// An immediate progress value, stored atomically after confirmed fence completion. + ImmediateU64(usize, u64), /// A 64-bit value resolved by the GPU into a persistently mapped READBACK buffer slot /// (`src`), copied atomically to `va` once the queue's fence completes. Holding `_buf` keeps /// the mapping alive until the worker finishes. @@ -31,54 +35,73 @@ pub(super) enum Write { } struct Job { - fence: ID3D12Fence, value: u64, writes: Vec, } -// SAFETY: the fence is a free-threaded COM object; the writes are plain data -unsafe impl Send for Job {} - -/// queue → its fence and the last value signalled +/// A queue's fence, last signalled value, and dedicated completion worker. struct QueueFence { fence: ID3D12Fence, value: u64, + tx: mpsc::Sender, } -unsafe impl Send for QueueFence {} - static FENCES: Mutex>> = Mutex::new(None); -/// how long the worker waits for one submission before writing anyway (a removed device, a -/// queue that never gets there) +/// Keep the bounded fallback for legacy writes; progress writes require confirmed completion. const WAIT_MS: u32 = 10_000; -fn worker() -> &'static Mutex> { - static W: OnceLock>> = OnceLock::new(); - W.get_or_init(|| { - let (tx, rx) = mpsc::channel::(); - let spawned = std::thread::Builder::new().name("xcl-cpu-writes".into()).spawn(move || unsafe { - let event = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()); - for job in rx { - if job.fence.GetCompletedValue() < job.value && job.fence.SetEventOnCompletion(job.value, HANDLE(event as *mut c_void)).is_ok() { - th::WaitForSingleObject(event, WAIT_MS); - } - for w in &job.writes { - match w { - Write::Immediate(va, words) => write_now(*va, words), - Write::ReadbackU64 { va, src, .. } => { - let value = (*(*src as *const AtomicU64)).load(Ordering::Acquire); - write_u64_now(*va, value); +fn spawn_queue_worker(dev: ID3D12Device, fence: ID3D12Fence, timeout_ms: u32) -> mpsc::Sender { + let (tx, rx) = mpsc::channel::(); + let spawned = std::thread::Builder::new().name("xcl-cpu-writes".into()).spawn(move || unsafe { + let event = CreateEventW(None, false, false, None).ok().map(|event| Owned::new(event)); + let handle = event.as_deref().copied(); + for job in rx { + let mut completed = fence::wait(&fence, job.value, &dev, handle, timeout_ms); + for w in &job.writes { + match w { + Write::Immediate(va, words) => write_now(*va, words), + Write::ImmediateU64(va, value) => { + if let Err(e) = &completed { + if !matches!(e, FenceError::Removed(_)) { + crate::xlog_warn!("D3D12.X: deferred 64-bit write at {va:#x}: {e}; still waiting for the producer"); + // The first event registration may still be active, or the event + // API may have failed. Sample the fence without registering again. + completed = loop { + match fence::completed_value(&fence, &dev) { + Ok(value) if value < job.value => std::thread::sleep(Duration::from_millis(20)), + result => break result.map(|_| ()), + } + }; + } + } + match &completed { + Ok(()) => write_u64_now(*va, *value), + Err(e) => { + crate::xlog_error!("D3D12.X: deferred 64-bit write at {va:#x} did not complete: {e}"); + super::real::stop_if_device_removed(); + } } } + Write::ReadbackU64 { va, src, .. } => { + let value = (*(*src as *const AtomicU64)).load(Ordering::Acquire); + write_u64_now(*va, value); + } } } - }); - if let Err(e) = spawned { - crate::xlog_error!("D3D12.X: no thread for the writes after the GPU: {e}"); } - Mutex::new(tx) - }) + }); + if let Err(e) = spawned { + crate::xlog_error!("D3D12.X: no thread for the writes after the GPU: {e}"); + } + tx +} + +/// Drop the queue's sender; its worker drains outstanding writes and closes its event. +pub(super) fn forget_queue(queue: usize) { + if let Some(m) = FENCES.lock().unwrap().as_mut() { + m.remove(&queue); + } } /// The dwords at `va`, if the memory is still there and writable. @@ -128,10 +151,18 @@ pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { return; } let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; - let job = { + enqueue(q, writes, |fence, value| q.Signal(fence, value)); +} + +unsafe fn enqueue( + q: &ID3D12CommandQueue, writes: Vec, + signal: impl FnOnce(&ID3D12Fence, u64) -> windows::core::Result<()>, +) { + let count = writes.len(); + { let mut g = FENCES.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); - let entry = match m.entry(queue as usize) { + let entry = match m.entry(q.as_raw() as usize) { std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), std::collections::hash_map::Entry::Vacant(v) => { let mut dev: Option = None; @@ -140,18 +171,19 @@ pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { } let Some(dev) = dev else { return }; let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return }; - v.insert(QueueFence { fence, value: 0 }) + let tx = spawn_queue_worker(dev, fence.clone(), WAIT_MS); + v.insert(QueueFence { fence, value: 0, tx }) } }; entry.value += 1; - if q.Signal(&entry.fence, entry.value).is_err() { + if signal(&entry.fence, entry.value).is_err() { return; } - Job { fence: entry.fence.clone(), value: entry.value, writes } - }; + // Enqueue before unlocking so concurrent producers keep fence signal order. + let _ = entry.tx.send(Job { value: entry.value, writes }); + } static FIRST: std::sync::Once = std::sync::Once::new(); - FIRST.call_once(|| crate::xlog_info!("D3D12.X: bottom-of-pipe writes outside unified memory are done by the CPU after the GPU ({} in the first submission)", job.writes.len())); - let _ = worker().lock().unwrap().send(job); + FIRST.call_once(|| crate::xlog_info!("D3D12.X: bottom-of-pipe writes outside unified memory are done by the CPU after the GPU ({count} in the first submission)")); } #[cfg(test)] @@ -160,17 +192,21 @@ mod tests { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; + unsafe fn test_device() -> Option { + let mut dev = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let warp: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).ok()?; + } + dev + } + /// The value lands after the queue has done what came before it. #[test] fn writes_land_after_the_queue() { unsafe { - let mut dev: Option = None; - if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap(); - let warp: IDXGIAdapter = factory.EnumWarpAdapter().unwrap(); - D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); - } - let dev = dev.unwrap(); + let dev = test_device().expect("D3D12 device (hardware or WARP)"); let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); let cell = Box::new([0u32; 2]); let va = cell.as_ptr() as usize; @@ -181,6 +217,7 @@ mod tests { assert!(t.elapsed().as_secs() < 5, "never written"); std::thread::yield_now(); } + forget_queue(q.as_raw() as usize); assert_eq!(*cell, [7, 9]); } } @@ -189,22 +226,10 @@ mod tests { #[test] fn readback_u64_lands_after_the_queue() { unsafe { - let mut dev: Option = None; - if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - let Ok(factory) = CreateDXGIFactory1::() else { - crate::gpu::recomp::runner::skip_test("no GPU"); - return; - }; - let Ok(warp) = factory.EnumWarpAdapter::() else { - crate::gpu::recomp::runner::skip_test("no GPU"); - return; - }; - if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - crate::gpu::recomp::runner::skip_test("no GPU"); - return; - } - } - let dev = dev.unwrap(); + let Some(dev) = test_device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); let hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; let rd = D3D12_RESOURCE_DESC { @@ -234,7 +259,110 @@ mod tests { assert!(t.elapsed().as_secs() < 5, "readback value never written"); std::thread::yield_now(); } + forget_queue(q.as_raw() as usize); assert_eq!(*dst, expected); } } + + #[test] + fn immediate_u64_survives_a_producer_fence_timeout() { + // Heap pages are writable, and the cells outlive even a failure to drain. + static CELLS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| Box::new((AtomicU32::new(0), AtomicU64::new(0), AtomicU32::new(0)))); + let wait_for_marker = |cell: &AtomicU32| { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while cell.load(Ordering::Acquire) != 1 { + if std::time::Instant::now() >= deadline { + return false; + } + std::thread::sleep(Duration::from_millis(1)); + } + true + }; + + unsafe { + let Some(dev) = test_device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (before, progress, after) = CELLS.as_ref(); + let expected = 0x1234_5678_9abc_def0; + let tx = spawn_queue_worker(dev, fence.clone(), 0); + assert!(tx.send(Job { + value: 1, + writes: vec![ + Write::Immediate(before.as_ptr() as usize, vec![1]), + Write::ImmediateU64(progress.as_ptr() as usize, expected), + Write::Immediate(after.as_ptr() as usize, vec![1]), + ], + }).is_ok()); + drop(tx); + + // The first legacy write proves the worker has passed its timeout without our signal. + let timed_out = wait_for_marker(before); + let pending = progress.load(Ordering::Acquire) == 0 && after.load(Ordering::Acquire) == 0; + fence.Signal(1).expect("complete the producer fence"); + + assert!(timed_out, "worker did not reach the timeout fallback"); + assert!(pending, "worker published progress or reordered writes before producer completion"); + assert!(wait_for_marker(after), "worker did not finish the job after producer completion"); + assert_eq!(progress.load(Ordering::Acquire), expected); + } + } + + #[test] + fn blocked_queue_does_not_stall_another_queues_writes() { + use std::time::{Duration, Instant}; + + // Heap pages are writable, and the destinations outlive even a failure to drain. + static CELLS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| Box::new([AtomicU32::new(0), AtomicU32::new(0)])); + let wait_for_write = |cell: &AtomicU32, expected| { + // Detect a shared worker before its 10 s fence timeout could drain both writes. + let deadline = Instant::now() + Duration::from_secs(5); + while cell.load(Ordering::Acquire) != expected { + if Instant::now() >= deadline { + return false; + } + std::thread::sleep(Duration::from_millis(1)); + } + true + }; + + unsafe { + let Some(dev) = test_device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let desc = D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }; + let a: ID3D12CommandQueue = dev.CreateCommandQueue(&desc).unwrap(); + let b: ID3D12CommandQueue = dev.CreateCommandQueue(&desc).unwrap(); + let [a_cell, b_cell] = CELLS.as_ref(); + + // The real queue keys and completion fences go through the same enqueue path as + // after(). Control the fences from the CPU so no GPU queue is held waiting. + let mut blocked = None; + enqueue(&a, vec![Write::Immediate(a_cell.as_ptr() as usize, vec![11])], |fence, value| { + blocked = Some((fence.clone(), value)); + Ok(()) + }); + let (fence_a, value_a) = blocked.expect("queue A completion fence"); + enqueue(&b, vec![Write::Immediate(b_cell.as_ptr() as usize, vec![22])], |fence, value| { + fence.Signal(value) + }); + + let b_written = wait_for_write(b_cell, 22); + let a_pending = fence_a.GetCompletedValue() < value_a && a_cell.load(Ordering::Acquire) == 0; + // Release A and disconnect both senders even when B was stalled. + let unblocked = fence_a.Signal(value_a); + forget_queue(a.as_raw() as usize); + forget_queue(b.as_raw() as usize); + unblocked.expect("signal queue A completion fence"); + + assert!(b_written, "queue B's completed write stalled behind queue A"); + assert!(a_pending, "queue A wrote before its completion fence was signaled"); + assert!(wait_for_write(a_cell, 11), "queue A did not write after its completion fence was signaled"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 208010030..a74ddeebb 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -29,7 +29,7 @@ use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use super::device_x::{self, DepthBias}; -use super::real; +use super::{real, title_list}; const PC_GET_TYPE: usize = 8; const PC_CLOSE: usize = 9; @@ -47,6 +47,7 @@ const PC_SET_PREDICATION: usize = 55; const PC_OM_SET_DEPTH_BOUNDS: usize = 62; const PC_WRITE_BUFFER_IMMEDIATE: usize = 66; const PC_QUEUE_EXECUTE_COMMAND_LISTS: usize = 10; +type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); /// Write64BitValueBottomOfPipeX flags 1 / 2, Write64BitValueTopOfPipeX flags 4 / 8: the value /// written is a GPU / system timestamp @@ -194,6 +195,10 @@ impl PendingWait { } } + unsafe fn progress_reached(&self) -> bool { + self.read_value().is_some_and(|current| current >= self.value) + } + unsafe fn is_satisfied(&self) -> bool { let Some(cur) = self.read_value() else { return true; @@ -515,6 +520,9 @@ unsafe fn restore_bindings(this: *mut c_void, b: &Bindings) { rt.single, if rt.dsv.is_some() { &d } else { std::ptr::null() }, ); + if let Some(&rt0) = rt.handles.first() { + super::present::note_rt0(this as usize, rt0); + } } } @@ -523,6 +531,8 @@ struct ListState { allocator: usize, list_type: Option, last_queue: Option, + /// Default title_list wrapper, on its active PC recording only. + title_owner: usize, /// Title's currently bound PSO (before dynamic depth-bias override) bound_pso: usize, /// Active `RSSetDepthBiasX` override (None = zero / disabled) @@ -539,6 +549,8 @@ struct ListState { /// Last `OMSetDepthBounds` values, restored after `KickoffX` depth_bounds: Option<(f32, f32)>, occlusion: Occlusion, + open_queries: Vec<(Query, D3D12_QUERY_TYPE)>, + split_barriers: u32, /// UMA address ranges written by this list since last Reset/KickoffX written_ranges: Vec<(u64, u64)>, /// Sparse-window `(va, bytes)` ranges written by memory ops (`Write32/64`, `Fill*`, @@ -546,6 +558,7 @@ struct ListState { sparse_writes: Vec<(usize, usize)>, /// External memory waits recorded on this list pending_waits: Vec, + progress_waits: Vec, /// bottom-of-pipe writes into memory the GPU does not see (`cpu_writes`) cpu_writes: Vec, /// Dedicated 256-byte buffer holding the current predicate value (created lazily in COMMON state). @@ -591,18 +604,39 @@ impl ListState { self.written_ranges.iter().any(|&(s, e)| va < e && s < end) } + fn has_waits(&self) -> bool { + !self.pending_waits.is_empty() || !self.progress_waits.is_empty() + } + fn clear_waits(&mut self) { - if !self.pending_waits.is_empty() { + if self.has_waits() { self.pending_waits.clear(); + self.progress_waits.clear(); PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); } } fn push_wait(&mut self, w: PendingWait) { - if self.pending_waits.is_empty() { + self.push_memory_wait(w, false); + } + + fn push_memory_wait(&mut self, w: PendingWait, progress: bool) { + if !self.has_waits() { PENDING_WAIT_LISTS.fetch_add(1, Ordering::AcqRel); } - self.pending_waits.push(w); + if progress { + self.progress_waits.push(w); + } else { + self.pending_waits.push(w); + } + } + + fn can_segment(&self) -> bool { + self.allocator != 0 + && self.occlusion.active.is_none() + && self.open_queries.is_empty() + && self.split_barriers == 0 + && self.sparse_writes.is_empty() } } @@ -688,7 +722,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C let m = g.get_or_insert_with(HashMap::new); let old = m.remove(&key); if let Some(ref old) = old { - if !old.pending_waits.is_empty() { + if old.has_waits() { PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); } if !old.sparse_writes.is_empty() { @@ -713,12 +747,19 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C } } +pub(super) fn set_title_owner(list: *mut c_void, owner: *mut c_void) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.title_owner = owner as usize; + } +} + /// Clean up all tracked state when a command list is released for good. pub(super) fn on_release(list: usize) { super::title_textures::list_reset(list); + super::present::forget_list(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); if let Some(old) = old { - if !old.pending_waits.is_empty() { + if old.has_waits() { PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); } if !old.sparse_writes.is_empty() { @@ -928,39 +969,72 @@ pub(super) unsafe fn cpu_writes_after(queue: *mut c_void, lists: &[*mut c_void]) super::cpu_writes::after(queue, writes); } -/// Submit `lists` through `submit`, splitting the batch before any list whose `Wait32/64BitValueX` -/// condition is not yet satisfied so earlier lists in the same batch can run on the GPU first. -pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], mut submit: impl FnMut(&[*mut c_void])) { +/// Submit PC lists in order, inserting queue gates before progress-wait segments. Legacy +/// waits still use the existing bounded CPU path. Ungated lists keep the native batching. +pub(super) unsafe fn execute_with_waits( + queue: *mut c_void, lists: &[*mut c_void], mut submit: impl FnMut(&[*mut c_void]), +) -> Result<(), String> { if lists.is_empty() || PENDING_WAIT_LISTS.load(Ordering::Acquire) == 0 { submit(lists); - return; + return Ok(()); } - let per_list: Vec> = { + let (per_list, last_sparse) = { let g = LISTS.lock().unwrap(); - lists - .iter() - .map(|&l| { - g.as_ref() - .and_then(|m| m.get(&(l as usize))) - .map(|s| s.pending_waits.clone()) - .unwrap_or_default() - }) - .collect() + let mut last_sparse = None; + let waits: Vec<_> = lists.iter().enumerate().map(|(i, &l)| { + let Some(s) = g.as_ref().and_then(|m| m.get(&(l as usize))) else { return Default::default() }; + if !s.sparse_writes.is_empty() { + last_sparse = Some(i); + } + (s.pending_waits.clone(), s.progress_waits.clone()) + }).collect(); + (waits, last_sparse) }; - let mut start = 0usize; - for (i, waits) in per_list.iter().enumerate() { - if waits.is_empty() || waits.iter().all(|w| w.is_satisfied()) { + let mut start = 0; + for (i, (legacy, progress)) in per_list.into_iter().enumerate() { + if progress.is_empty() && legacy.iter().all(|w| w.is_satisfied()) { continue; } if i > start { submit(&lists[start..i]); } - wait_all(waits); + wait_all(&legacy); + if !progress.is_empty() { + if last_sparse.is_some_and(|last| last >= i) { + // The synchronous sparse readback would block on this very queue, keeping + // the submission thread from submitting later producers on other queues. + wait_all(&progress); + } else { + super::wait_gate::arm(queue, move || progress.iter().all(|w| w.progress_reached()))?; + } + } start = i; } if start < lists.len() { submit(&lists[start..]); } + Ok(()) +} + +pub(super) unsafe fn submit_piece(queue: *mut c_void, lists: &[*mut c_void], exec: ExecFn) { + note_queue_for_lists(queue as usize, lists); + exec(queue, lists.len() as u32, lists.as_ptr()); + super::title_textures::submitted(lists); + readback_sparse_writes(queue, lists); + cpu_writes_after(queue, lists); +} + +pub(super) fn fail_submission(reason: String) -> ! { + real::stop_if_device_removed(); + let msg = format!("D3D12.X: cannot submit a progress-wait recording: {reason} – the title is stopped"); + crate::xlog_error!("{msg}"); + crate::report::write_final(Some(msg)); + crate::log::flush(); + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; + TerminateProcess(GetCurrentProcess(), crate::util::E_FAIL as u32); + } + std::process::abort() } // --------------------------------------------------------------------------------------- @@ -1098,7 +1172,10 @@ unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFF // the title's own memory: written by the CPU once the GPU is there if super::cpu_writes::writable(va as usize, n as usize) { if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { - s.cpu_writes.push(super::cpu_writes::Write::Immediate(va as usize, words.to_vec())); + s.cpu_writes.push(match words { + [lo, hi] => super::cpu_writes::Write::ImmediateU64(va as usize, (*hi as u64) << 32 | *lo as u64), + _ => super::cpu_writes::Write::Immediate(va as usize, words.to_vec()), + }); return; } } @@ -1232,13 +1309,9 @@ pub(super) unsafe extern "system" fn write64_bottom_x(this: *mut c_void, va: u64 write(this, va, &[value as u32, (value >> 32) as u32], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, W); } -/// Record a `Wait32BitValueX` or `Wait64BitValueX` memory wait on `list`. -/// -/// If an earlier write in the same open list already targeted an overlapping UMA range, the -/// `COMMON -> COPY_DEST -> COMMON` barrier around that write already orders subsequent work -/// on the GPU, so we do not stall before submission (which would deadlock waiting on our own -/// unsubmitted list). Otherwise the wait is evaluated on the CPU before `ExecuteCommandLists` -/// (or `KickoffX`) submits the list. +/// Eligible progress waits gate a PC piece at Execute. In particular, an earlier explicit +/// write may be what unblocks a different queue: close that prefix now, but do not submit it +/// or wait on the recording thread. Other waits retain the legacy list-level behavior. unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, value: u64, mask: u64, what: &str) { static N: AtomicU64 = AtomicU64::new(0); let n = width as u64; @@ -1246,7 +1319,8 @@ unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, va return warn(&N, what, format_args!("{va:#x} is not {n}-byte aligned")); } // (the wait reads the memory on the CPU: the title's own memory too, which `cpu_writes` fills) - if real::uma_window_buffer(va as usize, width as usize).is_none() && !crate::gpu::shader::readable(va as usize, width as usize) { + let in_uma = real::uma_window_buffer(va as usize, width as usize).is_some(); + if !in_uma && !crate::gpu::shader::readable(va as usize, width as usize) { return warn(&N, what, format_args!("{va:#x} is not readable memory")); } if compare_u64(comparison, 0, 0).is_none() { @@ -1258,12 +1332,35 @@ unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, va if comparison == D3D12_COMPARISON_FUNC_NEVER.0 as u32 { return warn(&N, what, format_args!("NEVER comparison at {va:#x} (skipped to avoid hang)")); } + let w = PendingWait { va, width, comparison, value, mask }; let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); - if s.has_prior_write(va, n) { - return; + let owner = s.title_owner as *mut c_void; + if !owner.is_null() && width == 8 && mask == u64::MAX + && comparison == D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32 + && !crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) + && (!in_uma || crate::gpu::shader::readable(va as usize, 8)) + && title_list::can_split(owner) && s.can_segment() + { + if let Some(ty @ (D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE)) = s.list_type { + // Tracked memory writes miss ordinary D3D12 work, such as copies and draws. + // Split even if the prefix might be empty, so the gate only holds the suffix. + let (alloc, pso) = (s.allocator, s.bound_pso); + drop(g); + let next = match split_recording(list, owner, alloc, ty, pso) { + Ok(next) => next, + Err(hr) => { + title_list::split_error(owner, hr); + return warn(&N, what, format_args!("cannot continue the recording ({hr:#x})")); + } + }; + LISTS.lock().unwrap().as_mut().unwrap().get_mut(&(next as usize)).unwrap().push_memory_wait(w, true); + return; + } + } + if !s.has_prior_write(va, n) { + s.push_wait(w); } - s.push_wait(PendingWait { va, width, comparison, value, mask }); } /// command list #71 Wait32BitValueX(address, comparison, value, mask, flags) @@ -1486,6 +1583,54 @@ pub unsafe extern "system" fn set_predication_buffer_x(this: *mut c_void, desc: apply_predication_copy(this, uma_buf, off, pb, D3D12_PREDICATION_OP(op_raw as i32)); } +unsafe fn split_recording( + this: *mut c_void, owner: *mut c_void, alloc: usize, ty: D3D12_COMMAND_LIST_TYPE, bound_pso: usize, +) -> Result<*mut c_void, crate::util::HRESULT> { + // A PC allocator can have only one open list. Create the continuation closed first, + // so allocation failure doesn't close or discard the current recording. + let dev = device_of(this).ok_or(crate::util::E_FAIL)?; + let dev4 = dev.cast::().map_err(|e| e.code().0)?; + let next: ID3D12GraphicsCommandList = dev4.CreateCommandList1(0, ty, D3D12_COMMAND_LIST_FLAG_NONE).map_err(|e| e.code().0)?; + before_close(this); + let ext = *(this as *const usize); + let close_hr = pc:: i32>(this, PC_CLOSE)(this); + real::preserve_vtable(this, ext); + if close_hr < 0 { + return Err(close_hr); + } + + let raw = next.as_raw(); + real::adopt(raw, real::Kind::CommandList); + let ext = *(raw as *const usize); + let init_pso = super::pso_async::resolve_for_bind(bound_pso); + let reset_hr = pc:: i32>(raw, PC_RESET)(raw, alloc, init_pso); + real::preserve_vtable(raw, ext); + if reset_hr < 0 { + return Err(reset_hr); + } + + { + let mut g = LISTS.lock().unwrap(); + let m = g.as_mut().unwrap(); + let prev = m.get_mut(&(this as usize)).unwrap(); + let mut continued = std::mem::take(prev); + *prev = ListState { + list_type: continued.list_type, + last_queue: continued.last_queue, + sparse_writes: std::mem::take(&mut continued.sparse_writes), + cpu_writes: std::mem::take(&mut continued.cpu_writes), + pending_waits: std::mem::take(&mut continued.pending_waits), + progress_waits: std::mem::take(&mut continued.progress_waits), + ..Default::default() + }; + m.insert(raw as usize, continued); + } + super::bind::continue_recording(this, raw); + restore_after_reopen(raw, dev.as_raw() as usize); + title_list::continue_on(owner, next.into_raw()); + Ok(raw) +} + /// command list #93 KickoffX(): flush commands recorded so far by closing the list, submitting /// it to a compatible live command queue, and resetting it on the same command allocator so /// recording can continue seamlessly until the title's normal `Close` + `ExecuteCommandLists`. @@ -1504,7 +1649,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { return; } let dev_raw = device_of(this).map_or(0, |d| d.as_raw() as usize); - let (alloc, queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, waits, sparse_writes) = { + let (alloc, queue, bound_pso, owner, active_query) = { let mut g = LISTS.lock().unwrap(); let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) else { if once(&NO_QUEUE, 4) { @@ -1518,6 +1663,38 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } return; } + let owner = s.title_owner as *mut c_void; + if !owner.is_null() && (!s.progress_waits.is_empty() || title_list::has_prefixes(owner)) { + // Unlike legacy KickoffX, never guess which queue owns a cross-queue dependency. + let queue = s.last_queue.filter(|&q| LIVE_QUEUES.lock().unwrap().iter().any(|info| info.queue == q)); + let eligible = s.can_segment() && title_list::can_split(owner); + let (alloc, pso) = (s.allocator, s.bound_pso); + drop(g); + if let Some(q) = queue.filter(|_| eligible) { + match split_recording(this, owner, alloc, ty, pso) { + Ok(next) => { + LISTS.lock().unwrap().as_mut().unwrap().get_mut(&(next as usize)).unwrap().written_ranges.clear(); + let q = q as *mut c_void; + let lists = title_list::take_kickoff(owner); + let exec: ExecFn = transmute_copy(&real::orig_fn(q, PC_QUEUE_EXECUTE_COMMAND_LISTS)); + super::title_textures::refresh(q); + if let Err(reason) = execute_with_waits(q, &lists, |piece| submit_piece(q, piece, exec)) { + fail_submission(reason); + } + for list in lists { + on_release(list as usize); + } + } + Err(hr) => { + title_list::split_error(owner, hr); + warn(&ERR, "KickoffX", format_args!("cannot continue the recording ({hr:#x})")); + } + } + } else if once(&NO_QUEUE, 4) { + crate::xlog_info!("D3D12.X: KickoffX – progress-wait recording cannot be flushed here; deferring to Close + ExecuteCommandLists"); + } + return; + } let Some(q) = pick_queue(s.last_queue, dev_raw, s.list_type.unwrap_or(ty)) else { if once(&NO_QUEUE, 4) { crate::xlog_info!("D3D12.X: KickoffX – no live queue of type {} yet, deferring to Close + ExecuteCommandLists", ty.0); @@ -1525,30 +1702,14 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { return; }; let active_query = s.occlusion.end_active_early(); - let waits = if s.pending_waits.is_empty() { - Vec::new() - } else { - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - std::mem::take(&mut s.pending_waits) - }; - let sparse_writes = s.clear_sparse_writes(); - s.written_ranges.clear(); - let cpu_writes = std::mem::take(&mut s.cpu_writes); - let pred_in_state = std::mem::replace(&mut s.pred_in_state, false); - let pred_buf = s.pred_buf.as_ref().map(|r| r.as_raw() as usize); - (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, waits, (sparse_writes, cpu_writes)) + (s.allocator, q, s.bound_pso, owner, active_query) }; - let (sparse_writes, cpu_writes) = sparse_writes; // End any active occlusion query before Close (PC forbids closing with an open query). if let Some(((h, i), qty)) = active_query { pc::(this, PC_END_QUERY)(this, h, qty, i); } - if pred_in_state { - if let Some(pb) = pred_buf { - transition(this, pb, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON); - } - } + before_close(this); let ext = *(this as *const usize); let close_hr = pc:: i32>(this, PC_CLOSE)(this); @@ -1557,13 +1718,23 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { return warn(&ERR, "KickoffX", format_args!("Close failed ({close_hr:#x})")); } + let (waits, sparse_writes, cpu_writes) = { + let mut g = LISTS.lock().unwrap(); + let s = g.as_mut().unwrap().get_mut(&(this as usize)).unwrap(); + let waits = std::mem::take(&mut s.pending_waits); + if !waits.is_empty() { + PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); + } + s.written_ranges.clear(); + (waits, s.clear_sparse_writes(), std::mem::take(&mut s.cpu_writes)) + }; + let q_raw = queue as *mut c_void; super::title_textures::refresh(q_raw); if !waits.is_empty() { wait_all(&waits); } - type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); let one = [this]; exec(q_raw, 1, one.as_ptr()); @@ -1582,45 +1753,42 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let reset_hr = pc:: i32>(this, PC_RESET)(this, alloc, init_pso); real::preserve_vtable(this, ext_closed); if reset_hr < 0 { + if !owner.is_null() { + title_list::split_error(owner, reset_hr); + } return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); } - let bindings = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).map(|s| s.bindings.clone()); - if let Some(b) = bindings { - restore_bindings(this, &b); - } + restore_after_reopen(this, dev_raw); +} - // Reset() cleared the PC list's native RSSetDepthBias state to (0, 0, 0) and bound init_pso. - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { - s.native_bias = DepthBias::ZERO; - s.using_fallback_pso = false; - s.pso_dirty = false; - } - let info = if bound_pso != 0 { device_x::base_depth_bias_info(bound_pso) } else { None }; +/// Restore XCL's tracked PC state after KickoffX or a recording-side wait split. +unsafe fn restore_after_reopen(this: *mut c_void, dev_raw: usize) { + let (bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, bindings) = { + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) else { return }; + (s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, + s.pred_buf.as_ref().map(|r| r.as_raw() as usize), std::mem::take(&mut s.bindings)) + }; + restore_bindings(this, &bindings); + + let mut native_bias = DepthBias::ZERO; let mut applied_native = false; - if let Some((true, static_bias)) = info { + if let Some((true, static_bias)) = device_x::base_depth_bias_info(bound_pso) { let target = depth_bias.unwrap_or(static_bias); - if target.is_zero() { - applied_native = true; - } else if try_native_depth_bias(this, target) { - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { - s.native_bias = target; - } + if target.is_zero() || try_native_depth_bias(this, target) { + native_bias = target; applied_native = true; } } else if bound_pso == 0 { if let Some(b) = depth_bias { if device_x::dynamic_depth_bias_supported(dev_raw as *mut c_void) && try_native_depth_bias(this, b) { - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { - s.native_bias = b; - } + native_bias = b; applied_native = true; } } } - if depth_bias.is_some() && !applied_native { - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { - s.pso_dirty = true; - } + let pso_dirty = depth_bias.is_some() && !applied_native; + if pso_dirty { DEPTH_BIAS_USED.store(true, Ordering::Release); } if let Some(ref view) = index_buffer { @@ -1632,9 +1800,13 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if let (Some(op), Some(pb)) = (predication, pred_buf) { transition(this, pb, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PREDICATION); pc::(this, PC_SET_PREDICATION)(this, pb, 0, op); - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { - s.pred_in_state = true; - } + } + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + s.bindings = bindings; + s.native_bias = native_bias; + s.using_fallback_pso = false; + s.pso_dirty = pso_dirty; + s.pred_in_state = predication.is_some() && pred_buf.is_some(); } } @@ -2121,7 +2293,7 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz return hr; } - let is_bundle = { + let (is_bundle, owner) = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); s.allocator = alloc; @@ -2133,6 +2305,8 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz s.index_buffer = None; s.depth_bounds = None; s.occlusion = Occlusion::default(); + s.open_queries.clear(); + s.split_barriers = 0; s.written_ranges.clear(); s.clear_sparse_writes(); s.clear_waits(); @@ -2140,8 +2314,11 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz s.predication = None; s.pred_in_state = false; s.bindings = Bindings::default(); - s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) + (s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE), s.title_owner as *mut c_void) }; + if !owner.is_null() { + title_list::on_reset(owner); + } super::title_textures::list_reset(this as usize); super::bind::reset(this, alloc, pso); if !is_bundle && pso != 0 { @@ -2232,6 +2409,17 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } out.push(b); } + if out.iter().any(|b| b[0] == 0 && b[1] != 0) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).filter(|s| s.title_owner != 0) { + for b in out.iter().filter(|b| b[0] == 0) { + match b[1] { + 1 => s.split_barriers += 1, + 2 => s.split_barriers = s.split_barriers.saturating_sub(1), + _ => {} + } + } + } + } if uav_transition && !any_uav { out.push([2, 0, 0, 0, 0, 0, 0, 0]); } @@ -2515,6 +2703,8 @@ pub(super) unsafe extern "system" fn begin_query_x(this: *mut c_void, heap: usiz if let Some(m) = VISIBLE.lock().unwrap().as_mut() { m.remove(&(heap, index)); } + } else if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).filter(|s| s.title_owner != 0) { + s.open_queries.push(((heap, index), ty)); } pc::(this, PC_BEGIN_QUERY)(this, heap, ty, index); } @@ -2535,6 +2725,10 @@ pub(super) unsafe extern "system" fn end_query_x(this: *mut c_void, heap: usize, VISIBLE.lock().unwrap().get_or_insert_with(HashMap::new).insert((heap, index), v); return; } + } else if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).filter(|s| s.title_owner != 0) { + if let Some(i) = s.open_queries.iter().position(|&q| q == ((heap, index), ty)) { + s.open_queries.swap_remove(i); + } } pc::(this, PC_END_QUERY)(this, heap, ty, index); } @@ -2569,6 +2763,10 @@ pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, hea pc::(this, PC_WRITE_BUFFER_IMMEDIATE)(this, params.len() as u32, params.as_ptr(), modes.as_ptr()); } +#[cfg(test)] +#[path = "list_x/wait_tests.rs"] +mod wait_tests; + #[cfg(test)] mod tests { use super::*; @@ -2780,22 +2978,22 @@ mod tests { let mut batches: Vec> = Vec::new(); unsafe { - execute_with_waits(&[l0, l1, l2], |chunk| { + execute_with_waits(std::ptr::null_mut(), &[l0, l1, l2], |chunk| { batches.push(chunk.iter().map(|&p| p as usize).collect()); // Simulate l0's GPU execution satisfying l1's wait! if chunk.contains(&l0) { cell.store(42, Ordering::Release); } - }); + }).unwrap(); } assert_eq!(batches, vec![vec![l0 as usize], vec![l1 as usize, l2 as usize]]); // Now that cell == 42 is already satisfied, the whole batch submits in one call. batches.clear(); unsafe { - execute_with_waits(&[l0, l1, l2], |chunk| { + execute_with_waits(std::ptr::null_mut(), &[l0, l1, l2], |chunk| { batches.push(chunk.iter().map(|&p| p as usize).collect()); - }); + }).unwrap(); } assert_eq!(batches, vec![vec![l0 as usize, l1 as usize, l2 as usize]]); diff --git a/crates/xcl/src/hle/d3d12x/list_x/wait_tests.rs b/crates/xcl/src/hle/d3d12x/list_x/wait_tests.rs new file mode 100644 index 000000000..d55a5df58 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/list_x/wait_tests.rs @@ -0,0 +1,264 @@ +use super::super::{bind, present, real, title_list}; +use super::{execute_with_waits, on_create, on_queue_create, submit_piece, wait64_x, write64_bottom_x}; +use crate::gpu::{fence, recomp::runner::skip_test}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; +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_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + +const TIMEOUT: Duration = Duration::from_secs(5); + +fn until(timeout: Duration, mut ready: impl FnMut() -> bool) -> bool { + let start = Instant::now(); + while !ready() { + if start.elapsed() >= timeout { + return false; + } + std::thread::sleep(Duration::from_millis(1)); + } + true +} + +unsafe fn buffer(dev: &ID3D12Device, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES) -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut resource = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut resource).unwrap(); + resource.unwrap() +} + +unsafe fn write_upload_words(upload: &ID3D12Resource, words: [u64; 2]) { + let mut p = std::ptr::null_mut(); + upload.Map(0, Some(&D3D12_RANGE { Begin: 0, End: 0 }), Some(&mut p)).unwrap(); + p.cast::<[u64; 2]>().write_unaligned(words); + upload.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 16 })); +} + +unsafe fn readback_words(readback: &ID3D12Resource) -> [u64; 2] { + let mut p = std::ptr::null_mut(); + readback.Map(0, Some(&D3D12_RANGE { Begin: 0, End: 16 }), Some(&mut p)).unwrap(); + let words = p.cast::<[u64; 2]>().read_unaligned(); + readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + words +} + +unsafe fn title_list(dev: &ID3D12Device, alloc: &ID3D12CommandAllocator, ty: D3D12_COMMAND_LIST_TYPE) -> ID3D12GraphicsCommandList { + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, alloc, None).unwrap(); + let pc = list.into_raw(); + real::adopt(pc, real::Kind::CommandList); + on_create(pc, alloc.as_raw() as usize, 0, ty); + bind::reset(pc, alloc.as_raw() as usize, 0); + let wrapped = ID3D12GraphicsCommandList::from_raw(title_list::wrap(pc)); + assert_ne!(wrapped.as_raw(), pc, "expected the default title list wrapper"); + wrapped +} + +#[test] +fn cross_queue_wait64_runs_at_its_recorded_position() { + const DIRECT: D3D12_COMMAND_LIST_TYPE = D3D12_COMMAND_LIST_TYPE_DIRECT; + const COMPUTE: D3D12_COMMAND_LIST_TYPE = D3D12_COMMAND_LIST_TYPE_COMPUTE; + const GE: u32 = D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32; + const READY_VALUE: u64 = 0x1_0000_0041; + const DONE_VALUE: u64 = 0x2_0000_0042; + const STALE: u64 = 0x0102_0304_0506_0708; + const UPDATED: u64 = 0xA1B2_C3D4_E5F6_0798; + + unsafe { + let mut dev = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + skip_test("no GPU"); + return; + } + let dev: ID3D12Device = dev.unwrap(); + let queue = |ty| -> ID3D12CommandQueue { + dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap() + }; + let (a, b) = (queue(DIRECT), queue(COMPUTE)); + let new_fence = || dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (a_tail, b_tail, release_b) = (new_fence(), new_fence(), new_fence()); + let reached = |f, at| fence::completed_value(f, &dev).is_ok_and(|v| v >= at); + let both_tails = |at| reached(&a_tail, at) && reached(&b_tail, at); + + let upload = buffer(&dev, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let value = buffer(&dev, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + let readback = buffer(&dev, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + write_upload_words(&upload, [STALE, UPDATED]); + + let init_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(DIRECT).unwrap(); + let init: ID3D12GraphicsCommandList = dev.CreateCommandList(0, DIRECT, &init_alloc, None).unwrap(); + init.CopyBufferRegion(&value, 0, &upload, 0, 8); + init.CopyBufferRegion(&readback, 0, &upload, 0, 8); + init.CopyBufferRegion(&readback, 8, &upload, 0, 8); + init.Close().unwrap(); + a.ExecuteCommandLists(&[Some(init.cast().unwrap())]); + a.Signal(&a_tail, 1).unwrap(); + assert!(until(TIMEOUT, || reached(&a_tail, 1)), "initial GPU copies did not finish"); + + for (queue, ty) in [(&a, DIRECT), (&b, COMPUTE)] { + real::adopt(queue.as_raw(), real::Kind::CommandQueue); + on_queue_create(queue.as_raw() as usize, dev.as_raw() as usize, ty); + } + let a_alloc = dev.CreateCommandAllocator(DIRECT).unwrap(); + let b_alloc = dev.CreateCommandAllocator(COMPUTE).unwrap(); + let (a_list, b_list) = (title_list(&dev, &a_alloc, DIRECT), title_list(&dev, &b_alloc, COMPUTE)); + // Use guest-style committed pages, not PE image sections that Wine can map + // as write-copy. Keep the allocation alive if a failed run leaves work pending. + let cells = VirtualAlloc(std::ptr::null(), 16, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast::<[AtomicU64; 2]>(); + assert!(!cells.is_null()); + let [ready_cell, done_cell] = &*cells; + let rescue = || { + ready_cell.store(READY_VALUE, Ordering::Release); + done_cell.store(DONE_VALUE, Ordering::Release); + }; + let ready = ready_cell.as_ptr() as u64; + let done = done_cell.as_ptr() as u64; + + // A GPU canary before the wait makes a recording-time prefix submit visible even if + // the deferred ready write has not yet landed on the CPU. + a_list.CopyBufferRegion(&readback, 8, &upload, 8, 8); + write64_bottom_x(title_list::active(a_list.as_raw()), ready, READY_VALUE, 0, 0); + wait64_x(title_list::active(a_list.as_raw()), done, GE, DONE_VALUE, 0, 0); + a_list.CopyBufferRegion(&readback, 0, &value, 0, 8); + a_list.Close().unwrap(); + + wait64_x(title_list::active(b_list.as_raw()), ready, GE, READY_VALUE, 0, 0); + b_list.CopyBufferRegion(&value, 0, &upload, 8, 8); + write64_bottom_x(title_list::active(b_list.as_raw()), done, DONE_VALUE, 0, 0); + b_list.Close().unwrap(); + + a.Signal(&a_tail, 2).unwrap(); + b.Signal(&b_tail, 2).unwrap(); + let recording_idle = until(TIMEOUT, || both_tails(2)); + let recording_untouched = recording_idle && readback_words(&readback) == [STALE, STALE] + && ready_cell.load(Ordering::Acquire) == 0 && done_cell.load(Ordering::Acquire) == 0; + if !recording_untouched { + rescue(); + let _ = until(TIMEOUT, || both_tails(2)); + present::forget_test_queue(a.as_raw()); + present::forget_test_queue(b.as_raw()); + } + assert!(recording_untouched, "recording or closing a list submitted GPU work: queue tails reached = {recording_idle}"); + + // Hold B's GPU work so A cannot legitimately finish early. Both XCL submissions + // happen on ONE thread, in consumer-first order, before releasing the external fence. + let (staged, held, unblocked, submit) = std::thread::scope(|s| { + b.Wait(&release_b, 1).unwrap(); + let submit = std::thread::Builder::new().spawn_scoped(s, || { + // Execute through the adopted queue's production hook, passing the wrappers. + (a.vtable().ExecuteCommandLists)(a.as_raw(), 1, &a_list.as_raw()); + (b.vtable().ExecuteCommandLists)(b.as_raw(), 1, &b_list.as_raw()); + a.Signal(&a_tail, 3).and_then(|_| b.Signal(&b_tail, 3)) + }); + let staged = submit.as_ref().is_ok_and(|t| { + until(TIMEOUT, || t.is_finished() && ready_cell.load(Ordering::Acquire) == READY_VALUE) + }); + let held = staged && !until(Duration::from_millis(100), || reached(&a_tail, 3)) + && done_cell.load(Ordering::Acquire) == 0; + let unblocked = release_b.Signal(1); + if !staged || unblocked.is_err() { + rescue(); + } + let submit = submit.map(|t| t.join()); + (staged, held, unblocked, submit) + }); + + let finished = until(TIMEOUT, || both_tails(3) && done_cell.load(Ordering::Acquire) == DONE_VALUE); + if !finished { + rescue(); + // Queue the drain markers after any work submitted before an error. + let _ = a.Signal(&a_tail, 4); + let _ = b.Signal(&b_tail, 4); + let _ = until(TIMEOUT, || both_tails(4)); + } + present::forget_test_queue(a.as_raw()); + present::forget_test_queue(b.as_raw()); + + unblocked.expect("release external producer fence"); + submit.expect("spawn submit thread").expect("submit thread panicked").expect("queue tail signals"); + assert!(staged, "consumer prefix did not publish ready with both submissions returned"); + let observed = finished.then(|| readback_words(&readback)); + assert_eq!(observed, Some([UPDATED, UPDATED]), "GPU wait chain timed out or copied stale data"); + assert!(held, "consumer or producer finished while producer's external fence was still held"); + assert_ne!(VirtualFree(cells.cast(), 0, MEM_RELEASE), 0); + } +} + +#[test] +fn ordinary_copy_runs_before_wait64_for_late_external_value() { + const DIRECT: D3D12_COMMAND_LIST_TYPE = D3D12_COMMAND_LIST_TYPE_DIRECT; + const GE: u32 = D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32; + const READY: u64 = 0x1_0000_0041; + const WORDS: [u64; 2] = [0x0102_0304_0506_0708, 0xA1B2_C3D4_E5F6_0798]; + + unsafe { + let mut dev = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + skip_test("no GPU"); + return; + } + let dev: ID3D12Device = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: DIRECT, ..Default::default() }).unwrap(); + let completion: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let reached = |at| fence::completed_value(&completion, &dev).is_ok_and(|v| v >= at); + let upload = buffer(&dev, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let prefix = buffer(&dev, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + let suffix = buffer(&dev, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + write_upload_words(&upload, WORDS); + let mut prefix_data = std::ptr::null_mut(); + prefix.Map(0, Some(&D3D12_RANGE { Begin: 0, End: 16 }), Some(&mut prefix_data)).unwrap(); + + let alloc = dev.CreateCommandAllocator(DIRECT).unwrap(); + let list = title_list(&dev, &alloc, DIRECT); + let ready = VirtualAlloc(std::ptr::null(), 8, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast::(); + assert!(!ready.is_null()); + list.CopyBufferRegion(&prefix, 0, &upload, 0, 16); + wait64_x(title_list::active(list.as_raw()), ready as u64, GE, READY, 0, 0); + list.CopyBufferRegion(&suffix, 0, &upload, 0, 16); + list.Close().unwrap(); + + let mut pieces = Vec::new(); + title_list::append_pieces(list.as_raw(), &mut pieces).unwrap(); + // Use the queue scheduler's native submission path, with a real completion fence + // after each batch so the CPU never reads a buffer still being written by the GPU. + let mut batches = 0; + let mut signal_error = None; + let submit = execute_with_waits(queue.as_raw(), &pieces, |chunk| { + submit_piece(queue.as_raw(), chunk, queue.vtable().ExecuteCommandLists); + batches += 1; + if let Err(err) = queue.Signal(&completion, batches) { + signal_error = Some(err); + } + }); + let tail = queue.Signal(&completion, batches + 1); + let observed_prefix = until(TIMEOUT, || reached(1)) + .then(|| prefix_data.cast::<[u64; 2]>().read_unaligned()); + let suffix_held = observed_prefix.is_some() && !until(Duration::from_millis(100), || reached(2)); + prefix.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + + // This is the external producer. Release even on RED so queued work can drain. + (*ready).store(READY, Ordering::Release); + let finished = tail.is_ok() && until(TIMEOUT, || reached(batches + 1)); + if finished { + assert_ne!(VirtualFree(ready.cast(), 0, MEM_RELEASE), 0); + } + submit.expect("submit recording"); + assert!(signal_error.is_none(), "signal batch completion: {signal_error:?}"); + tail.expect("signal queue tail"); + assert!(finished, "queue did not drain after the producer advanced"); + assert_eq!(observed_prefix, Some(WORDS), "ordinary copy did not finish before the producer advanced"); + assert_eq!(batches, 2, "expected a prefix and a continuation"); + assert!(suffix_held, "suffix completed before the producer advanced"); + assert_eq!(readback_words(&suffix), WORDS); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 3d0619897..1f9b541df 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -28,6 +28,7 @@ pub mod sparse; pub mod title_list; pub mod title_textures; pub mod vram; +mod wait_gate; use std::ffi::c_void; use std::sync::OnceLock; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 83a909468..f385cc838 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -215,6 +215,12 @@ pub fn note_rt0(list: usize, handle: usize) { LISTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(list, handle); } +pub(super) fn forget_list(list: usize) { + if let Some(lists) = LISTS.lock().unwrap().as_mut() { + lists.remove(&list); + } +} + /// Format the swap chain uses for a back buffer of `f` (None = not presentable). pub fn swap_format(f: DXGI_FORMAT) -> Option { Some(match f { @@ -247,6 +253,18 @@ pub fn known_queues() -> Vec { QUEUES.lock().unwrap().clone() } +#[cfg(test)] +pub(super) unsafe fn forget_test_queue(queue: *mut c_void) { + let queue = queue as usize; + let removed = { + let mut queues = QUEUES.lock().unwrap(); + queues.iter().position(|&q| q == queue).map(|i| queues.swap_remove(i)) + }; + if let Some(queue) = removed { + release(queue); + } +} + static EXECUTES: AtomicU64 = AtomicU64::new(0); /// (PresentX calls, ExecuteCommandLists calls) so far diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index be3a38a40..4cbdb4ea0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4647,6 +4647,7 @@ 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::cpu_writes::forget_queue(this as usize); } n } @@ -4858,21 +4859,25 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis stop_if_device_removed(); return; } + // A wrapped list can contain closed prefixes separated by recorded progress waits. + // Expand all lists before executing any of them, so an invalid Close cannot submit a prefix. + let mut mapped = Vec::with_capacity(n as usize); + for &list in std::slice::from_raw_parts(lists, n as usize) { + if let Some(pc) = super::console_list::pc_list(list) { + mapped.push(pc); + } else if super::title_list::backing(list).is_some() { + if let Err(hr) = super::title_list::append_pieces(list, &mut mapped) { + super::list_x::fail_submission(format!("command list {list:p} has an invalid recording ({hr:#x})")); + } + } else { + mapped.push(list); + } + } // textures in title memory the CPU wrote since: uploaded again first super::title_textures::refresh(this); - // console-shaped lists run as the PC lists they were translated into - let mapped: Vec<*mut c_void> = std::slice::from_raw_parts(lists, n as usize) - .iter() - .map(|&l| super::console_list::pc_list(l).or_else(|| super::title_list::backing(l)).unwrap_or(l)) - .collect(); - super::list_x::note_queue_for_lists(this as usize, &mapped); - super::list_x::execute_with_waits(&mapped, |chunk| { - f(this, chunk.len() as u32, chunk.as_ptr()); - super::list_x::readback_sparse_writes(this, chunk); - super::list_x::cpu_writes_after(this, chunk); - }); - // the next uploads into textures kept in step start from the states these lists leave - super::title_textures::submitted(&mapped); + if let Err(reason) = super::list_x::execute_with_waits(this, &mapped, |chunk| super::list_x::submit_piece(this, chunk, f)) { + super::list_x::fail_submission(reason); + } super::present::note_execute(this, &mapped); stop_if_device_removed(); } diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index de3dc7526..28d7826e1 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -9,10 +9,8 @@ //! has room: every inline write becomes the method call, and each method runs on the //! (adopted) PC list behind it – with all of XCL's console slot handling. //! -//! The object: the console fields, the PC list at `F_BACKING`; its vtable is a thunk per slot -//! (`mov rcx, [rcx + F_BACKING]` and on to the PC list's own vtable entry). QueryInterface -//! hands out the console object again, Release frees it with the PC list, and -//! ExecuteCommandLists runs the PC lists (`backing`). +//! Object and IUnknown methods use a stable PC list. Recording methods use the active PC list; +//! a progress wait can close that list and start a continuation without changing COM identity. use std::ffi::c_void; use std::sync::OnceLock; @@ -22,10 +20,11 @@ use windows_sys::core::GUID; use crate::util::HRESULT; const LIST_SLOTS: usize = 600; -/// the object: console fields up to `ROOM`, no-room "buffer" at `ROOM` (with slack after it -/// for code that would write before checking), the PC list at `F_BACKING` +/// Console fields up to `ROOM`, a no-room "buffer" with slack, then XCL's private fields. const OBJECT_BYTES: usize = 0x3000; const ROOM: usize = 0x1000; +const F_RECORDING: usize = 0x2F80; +const F_ACTIVE: usize = 0x2FF0; const F_BACKING: usize = 0x2FF8; const F_WRITE: usize = 0x18; const F_DISPATCH_END: usize = 0x28; @@ -37,15 +36,50 @@ const RING: usize = 64; struct Vtable(usize); -/// The console list vtable: QueryInterface / Release of their own, every other slot a thunk -/// to the PC list's entry. +#[derive(Default)] +struct Recording { + prefixes: Vec<*mut c_void>, + kicked: usize, + closed: bool, + error: HRESULT, + // State not kept by KickoffX restoration: bundle, raw predication, stream out, VRS. + untracked: bool, +} + +unsafe fn recording(this: *mut c_void) -> *mut Recording { + this.cast::().add(F_RECORDING).cast() +} + +unsafe fn root(this: *mut c_void) -> *mut c_void { + *this.cast::().add(F_BACKING).cast() +} + +pub(super) unsafe fn active(this: *mut c_void) -> *mut c_void { + *this.cast::().add(F_ACTIVE).cast() +} + +fn backing_field(slot: usize) -> usize { + if slot < 9 { F_BACKING } else { F_ACTIVE } +} + +fn changes_untracked_state(slot: usize) -> bool { + matches!(slot, 27 | 31 | 49 | 124 | 125) +} + +/// The console list vtable, with identity and Close methods of its own. fn vtable() -> usize { static V: OnceLock = OnceLock::new(); V.get_or_init(|| { let mut v = vec![0usize; LIST_SLOTS]; let trace = std::env::var_os("XCL_LIST_TRACE").is_some(); for (slot, e) in v.iter_mut().enumerate() { - *e = if trace { forward_traced(slot) } else { forward(slot) }; + *e = if trace { + forward_traced(slot, record) + } else if changes_untracked_state(slot) { + forward_traced(slot, block_split) + } else { + forward(slot) + }; } v[0] = qi as usize; v[2] = release as usize; @@ -55,10 +89,10 @@ fn vtable() -> usize { .0 } -/// `mov rcx, [rcx + F_BACKING]; mov rax, [rcx]; jmp [rax + slot * 8]` +/// `mov rcx, [rcx + field]; mov rax, [rcx]; jmp [rax + slot * 8]` fn forward(slot: usize) -> usize { let mut c = vec![0x48, 0x8B, 0x89]; - c.extend_from_slice(&(F_BACKING as u32).to_le_bytes()); + c.extend_from_slice(&(backing_field(slot) as u32).to_le_bytes()); c.extend_from_slice(&[0x48, 0x8B, 0x01, 0xFF, 0xA0]); c.extend_from_slice(&((slot * 8) as u32).to_le_bytes()); let p = crate::stubs::alloc_code(c.len()); @@ -68,8 +102,8 @@ fn forward(slot: usize) -> usize { p as usize } -/// `forward` after `record(this, slot)` (argument registers, xmm0–3 kept) -fn forward_traced(slot: usize) -> usize { +/// `forward` after calling `hook(this, slot)` (argument registers, xmm0–3 kept). +fn forward_traced(slot: usize, hook: unsafe extern "system" fn(*mut c_void, u32)) -> usize { let mut c: Vec = vec![0x51, 0x52, 0x41, 0x50, 0x41, 0x51]; // push rcx, rdx, r8, r9 c.extend_from_slice(&[0x48, 0x83, 0xEC, 0x68]); // sub rsp, 0x68 for (reg, off) in [(0x44u8, 0x20u8), (0x4C, 0x30), (0x54, 0x40), (0x5C, 0x50)] { @@ -77,8 +111,8 @@ fn forward_traced(slot: usize) -> usize { } c.push(0xBA); // mov edx, slot c.extend_from_slice(&(slot as u32).to_le_bytes()); - c.extend_from_slice(&[0x48, 0xB8]); // mov rax, record - c.extend_from_slice(&(record as usize as u64).to_le_bytes()); + c.extend_from_slice(&[0x48, 0xB8]); // mov rax, hook + c.extend_from_slice(&(hook as usize as u64).to_le_bytes()); c.extend_from_slice(&[0xFF, 0xD0]); // call rax for (reg, off) in [(0x44u8, 0x20u8), (0x4C, 0x30), (0x54, 0x40), (0x5C, 0x50)] { c.extend_from_slice(&[0xF3, 0x0F, 0x6F, reg, 0x24, off]); // movdqu xmmN, [rsp+off] @@ -86,7 +120,7 @@ fn forward_traced(slot: usize) -> usize { c.extend_from_slice(&[0x48, 0x83, 0xC4, 0x68]); // add rsp, 0x68 c.extend_from_slice(&[0x41, 0x59, 0x41, 0x58, 0x5A, 0x59]); // pop r9, r8, rdx, rcx c.extend_from_slice(&[0x48, 0x8B, 0x89]); - c.extend_from_slice(&(F_BACKING as u32).to_le_bytes()); + c.extend_from_slice(&(backing_field(slot) as u32).to_le_bytes()); c.extend_from_slice(&[0x48, 0x8B, 0x01, 0xFF, 0xA0]); c.extend_from_slice(&((slot * 8) as u32).to_le_bytes()); let p = crate::stubs::alloc_code(c.len()); @@ -97,17 +131,97 @@ fn forward_traced(slot: usize) -> usize { } unsafe extern "system" fn record(this: *mut c_void, slot: u32) { + if changes_untracked_state(slot as usize) { + block_split(this, slot); + } let at = (this as usize + F_RING_AT) as *mut usize; let k = *at % RING; *((this as usize + F_RING + 2 * k) as *mut u16) = slot as u16; *at += 1; } +unsafe extern "system" fn block_split(this: *mut c_void, _slot: u32) { + (*recording(this)).untracked = true; +} + +pub(super) unsafe fn can_split(this: *mut c_void) -> bool { + let r = &*recording(this); + !r.closed && r.error >= 0 && !r.untracked +} + +pub(super) unsafe fn split_error(this: *mut c_void, hr: HRESULT) { + (*recording(this)).error = hr; +} + +/// Keep the old PC list alive and start routing recording calls to `next`. +pub(super) unsafe fn continue_on(this: *mut c_void, next: *mut c_void) { + (*recording(this)).prefixes.push(active(this)); + *this.cast::().add(F_ACTIVE).cast() = next; +} + +/// For explicit KickoffX: flush newly closed prefixes, but keep the PC objects until Reset. +pub(super) unsafe fn take_kickoff(this: *mut c_void) -> Vec<*mut c_void> { + let r = &mut *recording(this); + let lists = r.prefixes[r.kicked..].to_vec(); + r.kicked = r.prefixes.len(); + lists +} + +pub(super) unsafe fn has_prefixes(this: *mut c_void) -> bool { + let r = &*recording(this); + r.kicked < r.prefixes.len() +} + +/// Expand a wrapped recording at Execute, not at a recording-side wait. +pub(super) unsafe fn append_pieces(this: *mut c_void, out: &mut Vec<*mut c_void>) -> Result<(), HRESULT> { + let r = &*recording(this); + if r.error < 0 { + return Err(r.error); + } + if has_prefixes(this) { + if !r.closed { + return Err(crate::util::E_INVALIDARG); + } + out.extend_from_slice(&r.prefixes[r.kicked..]); + } + out.push(active(this)); + Ok(()) +} + +/// Only a successful native Reset discards the preceding PC recordings. +pub(super) unsafe fn on_reset(this: *mut c_void) { + let r = &mut *recording(this); + let pc = root(this); + for prefix in r.prefixes.drain(..) { + if prefix == pc { + super::list_x::on_release(pc as usize); + super::bind::forget(pc); + } else { + release_pc(prefix); + } + } + r.kicked = 0; + r.closed = false; + r.error = 0; + r.untracked = false; +} + /// #9 Close: a failure is logged with the last methods called (`XCL_LIST_TRACE`) unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { - let pc = *((this as usize + F_BACKING) as *const *mut c_void); - let f: unsafe extern "system" fn(*mut c_void) -> HRESULT = std::mem::transmute(pc_slot(pc, 9)); - let hr = f(pc); + let r = recording(this); + let pc = active(this); + let hr = if (*r).error < 0 { + (*r).error + } else { + let f: unsafe extern "system" fn(*mut c_void) -> HRESULT = std::mem::transmute(pc_slot(pc, 9)); + let hr = f(pc); + if hr >= 0 { + (*r).closed = true; + } else if !(*r).closed && has_prefixes(this) { + (*r).error = hr; + } + hr + }; let n = *((this as usize + F_RING_AT) as *const usize); if hr < 0 && n > 0 { let first = n.saturating_sub(RING); @@ -134,16 +248,20 @@ pub unsafe fn wrap(pc: *mut c_void) -> *mut c_void { for f in [F_WRITE, F_DISPATCH_END, F_END] { *(o.add(f) as *mut usize) = room; } - *(o.add(F_BACKING) as *mut usize) = pc as usize; + let this = o.cast(); + recording(this).write(Recording::default()); + *o.add(F_BACKING).cast() = pc; + *o.add(F_ACTIVE).cast() = pc; + super::list_x::set_title_owner(pc, this); o as *mut c_void } -/// The PC list behind a console list object (None: not one). +/// The stable PC identity of a console list object (None: not one). pub fn backing(list: *mut c_void) -> Option<*mut c_void> { if list.is_null() || !crate::gpu::shader::readable(list as usize, 8) { return None; } - unsafe { (*(list as *const usize) == vtable()).then(|| *((list as usize + F_BACKING) as *const *mut c_void)) } + unsafe { (*(list as *const usize) == vtable()).then(|| root(list)) } } unsafe fn pc_slot(pc: *mut c_void, slot: usize) -> usize { @@ -161,7 +279,7 @@ const CONSOLE_LIST_IIDS: [(u32, u16, u16, [u8; 8]); 2] = [ ]; unsafe extern "system" fn qi(this: *mut c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let pc = *((this as usize + F_BACKING) as *const *mut c_void); + let pc = root(this); let f: unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(pc_slot(pc, 0)); if !riid.is_null() && !ppv.is_null() { let g = &*riid; @@ -179,13 +297,27 @@ unsafe extern "system" fn qi(this: *mut c_void, riid: *const GUID, ppv: *mut *mu hr } -/// Release: the console object goes with the PC list's last reference. -unsafe extern "system" fn release(this: *mut c_void) -> u32 { - let pc = *((this as usize + F_BACKING) as *const *mut c_void); +unsafe fn release_pc(pc: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(pc, 2)); - let n = f(pc); + f(pc) +} + +/// Release: the console object goes with the stable PC list's last reference. +unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let pc = root(this); + let n = release_pc(pc); if n == 0 { super::bind::forget(pc); + let r = recording(this).read(); + for prefix in r.prefixes { + if prefix != pc { + release_pc(prefix); + } + } + let last = active(this); + if last != pc { + release_pc(last); + } std::alloc::dealloc(this as *mut u8, std::alloc::Layout::from_size_align(OBJECT_BYTES, 64).unwrap()); } n diff --git a/crates/xcl/src/hle/d3d12x/wait_gate.rs b/crates/xcl/src/hle/d3d12x/wait_gate.rs new file mode 100644 index 000000000..6af36c7af --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/wait_gate.rs @@ -0,0 +1,173 @@ +//! Queue-side gates for recorded waits on CPU-visible progress values. + +use std::ffi::c_void; +use std::mem::{offset_of, size_of, transmute, ManuallyDrop}; +use std::sync::{mpsc, LazyLock}; +use std::time::{Duration, Instant}; + +use windows::core::{Interface, GUID, HRESULT}; +use windows::Win32::Foundation::E_POINTER; +use windows::Win32::Graphics::Direct3D12::*; + +use super::real; +use crate::gpu::fence::{self, FenceError}; + +const REACHED: u64 = 1; +const OPEN: u64 = 2; +const RETIRED: u64 = 3; +const POLL: Duration = Duration::from_millis(1); +const WARN_AFTER: Duration = Duration::from_secs(2); + +static TX: LazyLock, String>> = LazyLock::new(|| { + let (tx, rx) = mpsc::channel(); + std::thread::Builder::new().name("xcl-wait-gates".into()).spawn(move || monitor(rx)) + .map_err(|e| format!("starting the Wait64BitValueX monitor: {e}"))?; + Ok(tx) +}); + +struct Gate { + queue: usize, + device: ID3D12Device, + // D3D12 can still be using this fence until the queue passes the retirement signal. + // Only release it on confirmed retirement/removal, even if the worker exits unexpectedly. + fence: ManuallyDrop, + ready: Option bool + Send>>, + warn_at: Option, + retire_at: Option, +} + +enum Poll { + Pending, + Retired, + KeepFence, +} + +impl Gate { + fn failed(&self, error: FenceError) -> Poll { + crate::xlog_error!("D3D12.X: Wait64BitValueX gate on queue {:#x}: {error}", self.queue); + if matches!(error, FenceError::Removed(_)) { + real::stop_if_device_removed(); + Poll::Retired + } else { + // The queue may still refer to the fence even though we cannot service it. + Poll::KeepFence + } + } + + fn poll(&mut self) -> Poll { + let value = match unsafe { fence::completed_value(&self.fence, &self.device) } { + Ok(value) => value, + Err(e) => return self.failed(e), + }; + if self.retire_at.is_some_and(|target| value >= target) { + return Poll::Retired; + } + let Some(ready) = &self.ready else { return Poll::Pending }; + if value < REACHED || !ready() { + if self.warn_at.is_some_and(|at| Instant::now() >= at) { + self.warn_at = None; + let waiting_on = if value < REACHED { "preceding queue work" } else { "the memory condition" }; + crate::xlog_warn!("D3D12.X: Wait64BitValueX gate on queue {:#x} still waiting on {waiting_on} after {} s; leaving the queue blocked", self.queue, WARN_AFTER.as_secs()); + } + return Poll::Pending; + } + if let Err(e) = unsafe { self.fence.Signal(OPEN) } { + return self.failed(unsafe { fence::api_error(&self.device, "ID3D12Fence::Signal", e) }); + } + self.ready = None; + if self.retire_at.is_some() { Poll::Pending } else { Poll::KeepFence } + } +} + +fn monitor(rx: mpsc::Receiver) { + let mut pending = Vec::new(); + loop { + if pending.is_empty() { + let Ok(gate) = rx.recv() else { return }; + pending.push(gate); + } + pending.extend(rx.try_iter()); + let mut i = 0; + while i < pending.len() { + match pending[i].poll() { + Poll::Pending => i += 1, + Poll::Retired => drop(ManuallyDrop::into_inner(pending.swap_remove(i).fence)), + Poll::KeepFence => { pending.swap_remove(i); } + } + } + if !pending.is_empty() { + std::thread::sleep(POLL); + } + } +} + +unsafe fn private_fence(device: &ID3D12Device) -> windows::core::Result { + if !real::is_adopted(device.as_raw()) { + return device.CreateFence(0, D3D12_FENCE_FLAG_NONE); + } + // The title's CreateFence hook keeps its fences and signals them at shutdown. Neither + // applies to our private gates. + const SLOT: usize = offset_of!(ID3D12Device_Vtbl, CreateFence) / size_of::(); + type Create = unsafe extern "system" fn(*mut c_void, u64, D3D12_FENCE_FLAGS, *const GUID, *mut *mut c_void) -> HRESULT; + let create: Create = transmute(real::orig_fn(device.as_raw(), SLOT)); + let mut raw = std::ptr::null_mut(); + create(device.as_raw(), 0, D3D12_FENCE_FLAG_NONE, &ID3D12Fence::IID, &mut raw).ok()?; + if raw.is_null() { + return Err(E_POINTER.into()); + } + Ok(ID3D12Fence::from_raw(raw)) +} + +/// Insert a GPU queue wait at this submission point. After the queue reaches it, the monitor +/// opens it only when `ready` observes the requested value; the submitter is free to submit the +/// producer on another queue. +/// +/// `queue` must be a live native D3D12 command queue. `ready` must be safe to call on the monitor. +pub(super) unsafe fn arm(queue: *mut c_void, ready: impl Fn() -> bool + Send + 'static) -> Result<(), String> { + let q = ID3D12CommandQueue::from_raw_borrowed(&queue).ok_or("missing D3D12 command queue")?; + let mut device: Option = None; + q.GetDevice(&mut device).map_err(|e| format!("GetDevice: {e}"))?; + let device = device.ok_or("GetDevice returned no D3D12 device")?; + let fence = private_fence(&device).map_err(|e| fence::api_error(&device, "CreateFence", e).to_string())?; + let tx = TX.as_ref().map_err(Clone::clone)?; + + // Bypass the console layout dispatch: the queue slots are PC slots and the fence is not + // registered as a title fence. + const WAIT_SLOT: usize = offset_of!(ID3D12CommandQueue_Vtbl, Wait) / size_of::(); + const SIGNAL_SLOT: usize = offset_of!(ID3D12CommandQueue_Vtbl, Signal) / size_of::(); + type QueueOp = unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT; + let adopted = real::is_adopted(queue); + let pc = |slot, native: QueueOp| -> QueueOp { + if adopted { transmute(real::orig_fn(queue, slot)) } else { native } + }; + let signal = pc(SIGNAL_SLOT, q.vtable().Signal); + signal(queue, fence.as_raw(), REACHED).ok() + .map_err(|e| fence::api_error(&device, "ID3D12CommandQueue::Signal (prefix)", e).to_string())?; + let wait = pc(WAIT_SLOT, q.vtable().Wait)(queue, fence.as_raw(), OPEN).ok(); + let armed = wait.is_ok(); + let retire_at = if !armed { + // The prefix marker was still queued and must finish before the fence is released. + Some(REACHED) + } else { + // The queue cannot signal RETIRED until it consumes the wait. If the signal fails to + // queue, still service the committed wait and keep the fence alive. + match signal(queue, fence.as_raw(), RETIRED).ok() { + Ok(()) => Some(RETIRED), + Err(e) => { + let e = fence::api_error(&device, "ID3D12CommandQueue::Signal (retirement)", e); + crate::xlog_error!("D3D12.X: could not queue retirement for Wait64BitValueX gate on queue {queue:p}: {e}"); + None + } + } + }; + let wait = wait.map_err(|e| fence::api_error(&device, "ID3D12CommandQueue::Wait", e).to_string()); + tx.send(Gate { + queue: queue as usize, + device, + fence: ManuallyDrop::new(fence), + ready: armed.then(|| Box::new(ready) as Box bool + Send>), + warn_at: Some(Instant::now() + WARN_AFTER), + retire_at, + }).map_err(|_| "Wait64BitValueX monitor stopped after submitting to the queue; cannot service the gate".to_owned())?; + wait +} diff --git a/crates/xcl/tests/disasm_e2e.rs b/crates/xcl/tests/disasm_e2e.rs index 675862afe..f23ad01c3 100644 --- a/crates/xcl/tests/disasm_e2e.rs +++ b/crates/xcl/tests/disasm_e2e.rs @@ -41,3 +41,40 @@ fn disasm_honors_byte_range_options() { assert!(String::from_utf8(output.stderr).unwrap().contains(flag)); } } + +#[test] +fn disasm_prints_vop3_literal_and_advances_pc() { + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let shader = + std::env::temp_dir().join(format!("xcl-disasm-literal-{}-{nonce}.bin", std::process::id())); + // V_BFE_U32 with a literal in SRC2, followed by S_ENDPGM. + // https://github.com/llvm/llvm-project/blob/llvmorg-22.1.0/llvm/test/MC/AMDGPU/vop3-literal.s#L22-L23 + std::fs::write( + &shader, + [0x00, 0x00, 0x48, 0xd5, 0x01, 0x03, 0xfc, 0x03, 0x39, 0x30, 0x00, 0x00, 0x00, 0x00, 0x81, 0xbf], + ) + .unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_xcl")) + .arg("disasm") + .arg(&shader) + .args(["--offset", "0"]) + .output(); + std::fs::remove_file(&shader).unwrap(); + + let output = output.unwrap(); + assert!(output.status.success(), "{:?}", output); + let listing = String::from_utf8(output.stdout).unwrap(); + assert_eq!( + listing.lines().skip(1).collect::>(), + [ + format!( + " 00000000: {:<52} 00 00 48 d5 01 03 fc 03 39 30 00 00", + "v_bfe_u32 v0, v1, s1, 0x3039" + ), + format!(" 0000000c: {:<52} 00 00 81 bf", "s_endpgm"), + ] + ); +}