From 0f4117c50f01c2c1a6cd84a6d4a4cbf58679cb1f Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 20:49:00 -0300 Subject: [PATCH 01/16] D3D12.X: reuse staging buffers and command lists for async title texture uploads Avoid per-batch CPU stalls, upload-buffer churn, and command list allocation in title texture uploads by reusing a per-device async Uploader (fence-ordered GPU waits on consuming queues, dynamic 4-64 MiB staging chunks mapped once per chunk, capped idle pool/allocator recycling, and dedicated pinning on queue.Signal failure). Track Uploader's in-flight destination COM references so res_release detaches title-dropped textures from title_textures immediately (while deferring vram::forget until the GPU copy completes), order vram::Pages unmap/remap tile updates after the async upload fence without UPLOADERS/PAGES lock inversion, drop retired COM objects outside UPLOADERS, and clear queue wait tracking on both queue creation and release. --- crates/xcl/src/gpu/texture.rs | 719 +++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 9 + crates/xcl/src/hle/d3d12x/title_textures.rs | 254 ++++++- crates/xcl/src/hle/d3d12x/vram.rs | 64 +- 4 files changed, 1022 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index 1008d7693..6c9cf5c35 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -225,6 +225,414 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items Ok(failed) } +/// COM objects retired by `Uploader` that callers should drop outside any locks (such as +/// `UPLOADERS`), preventing `Release()` hooks from re-entering while locks are held. +#[derive(Default)] +pub struct Released { + resources: Vec, + allocs: Vec, + lists: Vec, +} + +static INFLIGHT_DEST_TOTAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static INFLIGHT_DESTS: std::sync::Mutex>> = std::sync::Mutex::new(None); + +fn inc_inflight_dest(res: usize) { + let mut g = INFLIGHT_DESTS.lock().unwrap(); + let count = g.get_or_insert_with(std::collections::HashMap::new).entry(res).or_insert(0); + *count += 1; + INFLIGHT_DEST_TOTAL.fetch_add(1, std::sync::atomic::Ordering::Release); +} + +fn dec_inflight_dest(res: usize) { + let mut g = INFLIGHT_DESTS.lock().unwrap(); + if let Some(m) = g.as_mut() { + if let Some(c) = m.get_mut(&res) { + *c -= 1; + if *c == 0 { + m.remove(&res); + } + INFLIGHT_DEST_TOTAL.fetch_sub(1, std::sync::atomic::Ordering::Release); + } + } +} + +/// Number of COM references currently held by active `Uploader` instances for in-flight copies +/// targeting raw `ID3D12Resource` pointer `res`. +pub fn inflight_dest_refs(res: usize) -> u32 { + if INFLIGHT_DEST_TOTAL.load(std::sync::atomic::Ordering::Acquire) == 0 { + return 0; + } + INFLIGHT_DESTS.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied()).unwrap_or(0) +} + +/// Reusable asynchronous texture uploader for one device: one command list, allocators and +/// staging upload buffers recycled once the GPU passes their fence value, and a single fence +/// that consuming queues wait on via `ID3D12CommandQueue::Wait` instead of stalling the CPU. +pub struct Uploader { + dev: ID3D12Device, + fence: ID3D12Fence, + value: u64, + /// Closed command list reused across batches (`None` before first use or after a close error). + list: Option, + /// Command allocators and the fence value their last submission signals. + allocs: std::collections::VecDeque<(ID3D12CommandAllocator, u64)>, + /// Staging upload buffers currently in flight: `(fence_value, buffer, bytes)`. + busy: std::collections::VecDeque<(u64, ID3D12Resource, u64)>, + /// Destination textures held alive until the GPU finishes copying into them (a title may + /// drop its own reference while the async copy is still in flight). + dests: std::collections::VecDeque<(u64, ID3D12Resource)>, + /// Recycled staging upload buffers ready for reuse, oldest first: `(bytes, buffer)`. + free: Vec<(u64, ID3D12Resource)>, + free_bytes: u64, + /// Objects from submissions where `queue.Signal` failed after `ExecuteCommandLists`: kept + /// out of the FIFO queues so they never head-of-line block later batches. + pinned_bufs: Vec, + pinned_dests: Vec, + pinned_allocs: Vec, +} + +// SAFETY: D3D12 device, fence, command list, allocator, and resource interfaces are free-threaded; +// all mutation goes through `&mut self`. +unsafe impl Send for Uploader {} + +/// Minimum staging buffer size for small mid-frame uploads (glyph/UI updates). +const UPLOADER_MIN_CHUNK: u64 = 4 << 20; +/// Maximum staging buffer size for multi-texture packing chunks. +const UPLOADER_MAX_CHUNK: u64 = 64 << 20; +/// Oversized one-off buffers above this size are not retained in the idle pool. +const UPLOADER_MAX_RETAIN: u64 = 128 << 20; +/// Maximum total bytes of idle staging buffers retained for reuse. +const UPLOADER_FREE_CAP: u64 = 256 << 20; +/// Maximum idle command allocators retained after a loading burst. +const UPLOADER_MAX_IDLE_ALLOCS: usize = 4; +/// D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. +const PLACEMENT_ALIGN: u64 = 512; + +fn pick_free_buffer(free: &[(u64, T)], min_bytes: u64) -> Option { + let cap = min_bytes.saturating_mul(2); + free.iter() + .enumerate() + .filter(|(_, (bytes, _))| *bytes >= min_bytes && *bytes <= cap) + .min_by_key(|(_, (bytes, _))| *bytes) + .map(|(i, _)| i) +} + +fn chunk_alloc_size(size: u64, remaining_batch: u64) -> u64 { + let target = remaining_batch.clamp(UPLOADER_MIN_CHUNK, UPLOADER_MAX_CHUNK); + let min_bytes = size.max(target); + if min_bytes <= UPLOADER_MAX_RETAIN { + min_bytes.checked_next_power_of_two().unwrap_or(min_bytes) + } else { + min_bytes.checked_next_multiple_of(1 << 20).unwrap_or(min_bytes) + } +} + +fn return_free_buffer(free: &mut Vec<(u64, T)>, free_bytes: &mut u64, buf: T, bytes: u64, evicted: &mut Vec) { + if bytes > UPLOADER_MAX_RETAIN || bytes > UPLOADER_FREE_CAP { + evicted.push(buf); + return; + } + while free_bytes.saturating_add(bytes) > UPLOADER_FREE_CAP { + // Evict the largest idle buffer (oldest first on ties) so oversized buffers cannot starve normal reuse. + let Some((idx, _)) = free + .iter() + .enumerate() + .max_by(|(ia, (ba, _)), (ib, (bb, _))| ba.cmp(bb).then_with(|| ib.cmp(ia))) + else { + break; + }; + let (ebytes, ebuf) = free.remove(idx); + *free_bytes -= ebytes; + evicted.push(ebuf); + } + if free_bytes.saturating_add(bytes) <= UPLOADER_FREE_CAP { + *free_bytes += bytes; + free.push((bytes, buf)); + } else { + evicted.push(buf); + } +} + +fn estimate_upload_bytes(subs: &[Subresource]) -> u64 { + subs.iter().fold(0u64, |acc, s| { + let pitch = (s.row_bytes as u64).checked_next_multiple_of(256).unwrap_or(u64::MAX); + let sub = pitch + .saturating_mul(s.rows as u64) + .saturating_mul(s.depth as u64) + .checked_next_multiple_of(PLACEMENT_ALIGN) + .unwrap_or(u64::MAX); + acc.saturating_add(sub) + }) +} + +fn next_staging_offset(used: u64, size: u64, capacity: u64) -> Option<(u64, u64)> { + let aligned = used.checked_next_multiple_of(PLACEMENT_ALIGN)?; + let end = aligned.checked_add(size)?; + (end <= capacity).then_some((aligned, end)) +} + +struct ActiveChunk { + buf: ID3D12Resource, + ptr: *mut u8, + cap: u64, + used: u64, +} + +impl Uploader { + pub unsafe fn new(dev: &ID3D12Device) -> Result { + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?; + Ok(Uploader { + dev: dev.clone(), + fence, + value: 0, + list: None, + allocs: Default::default(), + busy: Default::default(), + dests: Default::default(), + free: Vec::new(), + free_bytes: 0, + pinned_bufs: Vec::new(), + pinned_dests: Vec::new(), + pinned_allocs: Vec::new(), + }) + } + + /// Fence and value that consuming queues must GPU-wait on to observe all uploads submitted so far. + pub fn done_at(&self) -> (&ID3D12Fence, u64) { + (&self.fence, self.value) + } + + /// Reclaim completed destination refs, staging buffers, and excess idle allocators, appending + /// COM objects to drop into `released` so callers can drop them outside any locks. + pub unsafe fn recycle_deferred(&mut self, released: &mut Released) -> Result { + let done = fence::completed_value(&self.fence, &self.dev).map_err(|e| format!("texture copy: {e}"))?; + while self.dests.front().is_some_and(|(v, _)| *v <= done) { + let (_, res) = self.dests.pop_front().unwrap(); + dec_inflight_dest(windows::core::Interface::as_raw(&res) as usize); + released.resources.push(res); + } + while self.busy.front().is_some_and(|(v, _, _)| *v <= done) { + let (_, buf, bytes) = self.busy.pop_front().unwrap(); + return_free_buffer(&mut self.free, &mut self.free_bytes, buf, bytes, &mut released.resources); + } + let idle_allocs = self.allocs.iter().take_while(|(_, v)| *v <= done).count(); + for _ in UPLOADER_MAX_IDLE_ALLOCS..idle_allocs { + if let Some((alloc, _)) = self.allocs.pop_front() { + released.allocs.push(alloc); + } + } + Ok(done) + } + + unsafe fn take_mapped( + dev: &ID3D12Device, + free: &mut Vec<(u64, ID3D12Resource)>, + free_bytes: &mut u64, + size: u64, + remaining_batch: u64, + released: &mut Released, + ) -> Result { + let target = remaining_batch.clamp(UPLOADER_MIN_CHUNK, UPLOADER_MAX_CHUNK); + let min_bytes = size.max(target); + let (buf, cap) = if let Some(i) = pick_free_buffer(free, min_bytes) { + let (bytes, buf) = free.remove(i); + *free_bytes -= bytes; + (buf, bytes) + } else { + let bytes = chunk_alloc_size(size, remaining_batch); + (buffer(dev, bytes)?, bytes) + }; + let no_read = D3D12_RANGE { Begin: 0, End: 0 }; + let mut p = std::ptr::null_mut(); + if let Err(e) = buf.Map(0, Some(&no_read), Some(&mut p)) { + released.resources.push(buf); + return Err(err(e)); + } + Ok(ActiveChunk { buf, ptr: p as *mut u8, cap, used: 0 }) + } + + unsafe fn finish_chunk( + chunk: ActiveChunk, + used: &mut Vec<(ID3D12Resource, u64)>, + free: &mut Vec<(u64, ID3D12Resource)>, + free_bytes: &mut u64, + released: &mut Released, + ) { + let written = D3D12_RANGE { Begin: 0, End: usize::try_from(chunk.used).unwrap_or(usize::MAX) }; + chunk.buf.Unmap(0, Some(&written)); + if chunk.used > 0 { + used.push((chunk.buf, chunk.cap)); + } else { + return_free_buffer(free, free_bytes, chunk.buf, chunk.cap, &mut released.resources); + } + } + + /// Record and submit a batch of texture uploads asynchronously on `queue` without stalling + /// the CPU. Consuming queues must GPU-wait on `done_at()` before sampling the targets. + pub unsafe fn upload( + &mut self, + queue: &ID3D12CommandQueue, + items: &[(ID3D12Resource, Vec, Vec)], + ) -> Result, String> { + let mut released = Released::default(); + let r = self.upload_deferred(queue, items, &mut released); + drop(released); + r + } + + /// Like `upload`, but appends all retired COM objects into `released` so callers holding an + /// outer lock can drop them after releasing the lock. + pub unsafe fn upload_deferred( + &mut self, + queue: &ID3D12CommandQueue, + items: &[(ID3D12Resource, Vec, Vec)], + released: &mut Released, + ) -> Result, String> { + if items.is_empty() { + return Ok(Vec::new()); + } + let done = self.recycle_deferred(released)?; + let alloc = match self.allocs.front() { + Some((_, v)) if *v <= done => { + let (a, _) = self.allocs.pop_front().unwrap(); + if let Err(e) = a.Reset() { + released.allocs.push(a); + return Err(err(e)); + } + a + } + _ => self.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(err)?, + }; + let list = match self.list.take() { + Some(l) => { + if let Err(e) = l.Reset(&alloc, None) { + self.allocs.push_front((alloc, done)); + released.lists.push(l); + return Err(err(e)); + } + l + } + None => match self.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None) { + Ok(l) => l, + Err(e) => { + self.allocs.push_front((alloc, done)); + return Err(err(e)); + } + }, + }; + let item_ests: Vec = items.iter().map(|(_, subs, _)| estimate_upload_bytes(subs)).collect(); + let mut remaining_est: u64 = item_ests.iter().copied().fold(0u64, u64::saturating_add); + let mut used: Vec<(ID3D12Resource, u64)> = Vec::new(); + let mut dests: Vec = Vec::new(); + let mut failed = Vec::new(); + let mut cur: Option = None; + for (k, ((res, subs, states), &est)) in items.iter().zip(&item_ests).enumerate() { + let (dev, free, free_bytes) = (&self.dev, &mut self.free, &mut self.free_bytes); + let r = record_upload_mapped(dev, &list, res, subs, states, states, &mut |size| { + let fit = cur.as_ref().and_then(|c| next_staging_offset(c.used, size, c.cap)); + if fit.is_none() { + if let Some(c) = cur.take() { + Self::finish_chunk(c, &mut used, free, free_bytes, released); + } + cur = Some(Self::take_mapped(dev, free, free_bytes, size, remaining_est, released)?); + } + let c = cur.as_mut().unwrap(); + let (at, end) = next_staging_offset(c.used, size, c.cap).ok_or_else(|| format!("texture staging size overflow ({size} B)"))?; + let at_usize = usize::try_from(at).map_err(|_| format!("texture staging offset overflow ({at} B)"))?; + c.used = end; + Ok((windows::core::Interface::as_raw(&c.buf), at, c.ptr.add(at_usize))) + }); + remaining_est = remaining_est.saturating_sub(est); + match r { + Ok(()) => dests.push(res.clone()), + Err(e) => failed.push((k, e)), + } + } + if let Some(c) = cur.take() { + Self::finish_chunk(c, &mut used, &mut self.free, &mut self.free_bytes, released); + } + if dests.is_empty() { + // Nothing succeeded: close the empty list so it and the allocator can be reused without submitting. + if list.Close().is_ok() { + self.list = Some(list); + self.allocs.push_front((alloc, done)); + } else { + released.lists.push(list); + released.allocs.push(alloc); + } + for (b, bytes) in used { + return_free_buffer(&mut self.free, &mut self.free_bytes, b, bytes, &mut released.resources); + } + return Ok(failed); + } + if let Err(e) = list.Close() { + released.lists.push(list); + released.allocs.push(alloc); + for (b, bytes) in used { + return_free_buffer(&mut self.free, &mut self.free_bytes, b, bytes, &mut released.resources); + } + released.resources.extend(dests); + return Err(err(e)); + } + self.list = Some(list.clone()); + let cl: ID3D12CommandList = match windows::core::Interface::cast(&list) { + Ok(cl) => cl, + Err(e) => { + self.allocs.push_front((alloc, done)); + for (b, bytes) in used { + return_free_buffer(&mut self.free, &mut self.free_bytes, b, bytes, &mut released.resources); + } + released.resources.extend(dests); + return Err(err(e)); + } + }; + queue.ExecuteCommandLists(&[Some(cl)]); + let next = self.value + 1; + if let Err(e) = queue.Signal(&self.fence, next) { + // The list is already submitted: pin its allocator, staging buffers, and targets in + // dedicated vectors so they stay alive without head-of-line blocking the FIFO queues. + for (b, _) in used { + self.pinned_bufs.push(b); + } + for res in dests { + inc_inflight_dest(windows::core::Interface::as_raw(&res) as usize); + self.pinned_dests.push(res); + } + self.pinned_allocs.push(alloc); + return Err(err(e)); + } + self.value = next; + for (b, bytes) in used { + self.busy.push_back((next, b, bytes)); + } + for res in dests { + inc_inflight_dest(windows::core::Interface::as_raw(&res) as usize); + self.dests.push_back((next, res)); + } + self.allocs.push_back((alloc, next)); + Ok(failed) + } +} + +impl Drop for Uploader { + fn drop(&mut self) { + if self.value > 0 { + unsafe { + let _ = fence::wait(&self.fence, self.value, &self.dev, None, 10_000); + } + } + for (_, res) in self.dests.drain(..) { + dec_inflight_dest(windows::core::Interface::as_raw(&res) as usize); + drop(res); + } + for res in self.pinned_dests.drain(..) { + dec_inflight_dest(windows::core::Interface::as_raw(&res) as usize); + drop(res); + } + } +} + /// Record the copy of `subs` into `res` on `list` (barriers from `before` and back to `after`); /// the staging buffer returned must live until the list has run. pub unsafe fn record_upload(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, subs: &[Subresource], before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> Result { @@ -242,6 +650,44 @@ pub unsafe fn record_upload_states( before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], ) -> Result { + let mut mapped: Option<(ID3D12Resource, usize)> = None; + let r = record_upload_mapped(dev, list, res, subs, before, after, &mut |size| { + let len = usize::try_from(size).map_err(|_| format!("texture staging size overflow ({size} B)"))?; + let up = buffer(dev, size)?; + let no_read = D3D12_RANGE { Begin: 0, End: 0 }; + let mut p = std::ptr::null_mut(); + up.Map(0, Some(&no_read), Some(&mut p)).map_err(err)?; + let raw = windows::core::Interface::as_raw(&up); + mapped = Some((up, len)); + Ok((raw, 0, p as *mut u8)) + }); + match (r, mapped) { + (Ok(()), Some((up, len))) => { + let written = D3D12_RANGE { Begin: 0, End: len }; + up.Unmap(0, Some(&written)); + Ok(up) + } + (Err(e), Some((up, _))) => { + let none = D3D12_RANGE { Begin: 0, End: 0 }; + up.Unmap(0, Some(&none)); + Err(e) + } + (Err(e), None) => Err(e), + (Ok(()), None) => Err("texture upload staging buffer missing".into()), + } +} + +/// `record_upload_states` with caller-supplied mapped staging memory: `staging(size)` returns +/// `(raw_buffer, base_offset, mapped_dst_ptr)` with at least `size` writable bytes at `mapped_dst_ptr`. +unsafe fn record_upload_mapped( + dev: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + res: &ID3D12Resource, + subs: &[Subresource], + before: &[D3D12_RESOURCE_STATES], + after: &[D3D12_RESOURCE_STATES], + staging: &mut dyn FnMut(u64) -> Result<(*mut std::ffi::c_void, u64, *mut u8), String>, +) -> Result<(), String> { validate_subresources(subs)?; let rd = res.GetDesc(); let n = subs.len(); @@ -256,6 +702,10 @@ pub unsafe fn record_upload_states( let mut row_bytes = vec![0u64; n]; let mut total = 0u64; dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut total)); + if total == 0 || total == u64::MAX { + return Err(format!("invalid copyable footprint size ({total})")); + } + let total_usize = usize::try_from(total).map_err(|_| format!("texture staging size overflow ({total} B)"))?; for (i, ((s, fp), (&nrows, &nbytes))) in subs.iter().zip(&fps).zip(rows.iter().zip(&row_bytes)).enumerate() { if s.rows != nrows as usize || s.depth != fp.Footprint.Depth as usize || s.row_bytes != nbytes as usize { return Err(format!( @@ -263,23 +713,42 @@ pub unsafe fn record_upload_states( s.row_bytes, s.rows, s.depth, nbytes, nrows, fp.Footprint.Depth )); } + let rel = usize::try_from(fp.Offset).map_err(|_| "texture staging offset overflow")?; + let pitch = fp.Footprint.RowPitch as usize; + let row = s.row_bytes.min(pitch); + let depth = (fp.Footprint.Depth as usize).min(s.depth); + let nr = (nrows as usize).min(s.rows); + if depth > 0 && nr > 0 && row > 0 { + let slice_pitch = pitch.checked_mul(nrows as usize).ok_or("texture staging slice pitch overflow")?; + let end = (depth - 1) + .checked_mul(slice_pitch) + .and_then(|o| o.checked_add((nr - 1).checked_mul(pitch)?)) + .and_then(|o| o.checked_add(row)) + .and_then(|o| o.checked_add(rel)) + .ok_or("texture staging offset overflow")?; + if end > total_usize { + return Err(format!("texture staging write ({end} B) exceeds footprint ({total_usize} B)")); + } + } } - let up = buffer(dev, total)?; - let mut p = std::ptr::null_mut(); - up.Map(0, None, Some(&mut p)).map_err(err)?; - for ((s, fp), &nrows) in subs.iter().zip(&fps).zip(&rows) { + let (up_raw, base, dst_base) = staging(total)?; + base.checked_add(total).ok_or("texture staging offset overflow")?; + let up = windows::core::Interface::from_raw_borrowed(&up_raw) + .ok_or_else(|| "texture staging buffer is null".to_string())?; + for ((s, fp), &nrows) in subs.iter().zip(fps.iter_mut()).zip(&rows) { + let rel = fp.Offset as usize; + fp.Offset = fp.Offset.checked_add(base).ok_or("texture staging offset overflow")?; let pitch = fp.Footprint.RowPitch as usize; let row = s.row_bytes.min(pitch); // depth slices are NumRows rows apart (rows of 4×4 blocks for BCn) let slice_pitch = pitch * nrows as usize; for z in 0..(fp.Footprint.Depth as usize).min(s.depth) { for y in 0..(nrows as usize).min(s.rows) { - let at = fp.Offset as usize + z * slice_pitch + y * pitch; - std::ptr::copy_nonoverlapping(s.data[(z * s.rows + y) * s.row_bytes..].as_ptr(), (p as *mut u8).add(at), row); + let at = rel + z * slice_pitch + y * pitch; + std::ptr::copy_nonoverlapping(s.data[(z * s.rows + y) * s.row_bytes..].as_ptr(), dst_base.add(at), row); } } } - up.Unmap(0, None); let to_copy = transitions(res, before, &[D3D12_RESOURCE_STATE_COPY_DEST], n); if !to_copy.is_empty() { list.ResourceBarrier(&to_copy); @@ -290,14 +759,18 @@ pub unsafe fn record_upload_states( Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 }, }; - let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&up), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy::(up), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp }, + }; list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); } let back = transitions(res, &[D3D12_RESOURCE_STATE_COPY_DEST], after, n); if !back.is_empty() { list.ResourceBarrier(&back); } - Ok(up) + Ok(()) } /// The transitions of `r`'s `n` subresources from `from` to `to` (each one state for all, or one @@ -891,4 +1364,232 @@ mod tests { .clone() } } + + #[test] + fn uploader_staging_alignment_and_overflow() { + assert_eq!(next_staging_offset(0, 1024, UPLOADER_MIN_CHUNK), Some((0, 1024))); + assert_eq!(next_staging_offset(1, 512, UPLOADER_MIN_CHUNK), Some((512, 1024))); + assert_eq!(next_staging_offset(512, 512, 1024), Some((512, 1024))); + assert_eq!(next_staging_offset(513, 512, 1024), None); + assert_eq!(next_staging_offset(u64::MAX - 10, 64, u64::MAX), None); + assert_eq!(next_staging_offset(512, u64::MAX, u64::MAX), None); + + // Dynamic chunk sizing: small batches use 4 MiB, large batches cap at 64 MiB, and + // oversized one-off textures above UPLOADER_MAX_RETAIN round to 1 MiB instead of doubling. + assert_eq!(chunk_alloc_size(64 << 10, 64 << 10), UPLOADER_MIN_CHUNK); + assert_eq!(chunk_alloc_size(64 << 10, 12 << 20), 16 << 20); + assert_eq!(chunk_alloc_size(64 << 10, 200 << 20), UPLOADER_MAX_CHUNK); + assert_eq!(chunk_alloc_size(150 << 20, 150 << 20), 150 << 20); + assert_eq!(chunk_alloc_size((150 << 20) + 1, (150 << 20) + 1), 151 << 20); + } + + #[test] + fn uploader_free_pool_rejects_oversized_and_evicts_largest() { + let mut free: Vec<(u64, u32)> = Vec::new(); + let mut free_bytes = 0u64; + let mut evicted = Vec::new(); + + // Oversized one-off buffer (> UPLOADER_MAX_RETAIN and > UPLOADER_FREE_CAP) is never retained. + return_free_buffer(&mut free, &mut free_bytes, 1, 300 << 20, &mut evicted); + assert_eq!(evicted, vec![1]); + assert!(free.is_empty()); + assert_eq!(free_bytes, 0); + + // Even when two 128 MiB buffers completely fill UPLOADER_FREE_CAP (256 MiB), returning a + // normal 4 MiB buffer evicts the oldest 128 MiB buffer so normal reuse is never starved. + return_free_buffer(&mut free, &mut free_bytes, 10, 128 << 20, &mut evicted); + return_free_buffer(&mut free, &mut free_bytes, 11, 128 << 20, &mut evicted); + assert_eq!(free_bytes, UPLOADER_FREE_CAP); + assert_eq!(pick_free_buffer(&free, UPLOADER_MIN_CHUNK), None); + + return_free_buffer(&mut free, &mut free_bytes, 20, UPLOADER_MIN_CHUNK, &mut evicted); + assert_eq!(evicted, vec![1, 10], "oldest 128 MiB buffer should be evicted"); + assert_eq!(free_bytes, (128 << 20) + UPLOADER_MIN_CHUNK); + let picked = pick_free_buffer(&free, UPLOADER_MIN_CHUNK).expect("4 MiB buffer must be reusable"); + assert_eq!(free[picked], (UPLOADER_MIN_CHUNK, 20)); + } + + #[test] + fn inflight_dest_refs_tracks_multiple_holds() { + // Distinct sentinel addresses (never dereferenced). + let (a, b) = (0x7E57_DEAD_1000usize, 0x7E57_DEAD_2000usize); + assert_eq!(inflight_dest_refs(a), 0); + assert_eq!(inflight_dest_refs(b), 0); + inc_inflight_dest(a); + inc_inflight_dest(a); + inc_inflight_dest(b); + assert_eq!(inflight_dest_refs(a), 2); + assert_eq!(inflight_dest_refs(b), 1); + dec_inflight_dest(a); + assert_eq!(inflight_dest_refs(a), 1); + dec_inflight_dest(a); + assert_eq!(inflight_dest_refs(a), 0); + dec_inflight_dest(b); + assert_eq!(inflight_dest_refs(b), 0); + } + + /// Async `Uploader`: packs multiple textures into one shared staging buffer, syncs a + /// separate consuming queue through its fence without a CPU wait, keeps a caller-dropped + /// destination alive until GPU completion, reuses staging buffers and allocators after + /// completion, and recovers cleanly from partial or full validation failures. + #[test] + fn gpu_uploader_reuses_staging_syncs_via_fence_and_holds_dropped_targets() { + let Some((dev, upload_q)) = device() else { + println!("no D3D12 device – skipping"); + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + unsafe { + let title_q: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .unwrap(); + let mut up = Uploader::new(&dev).unwrap(); + assert_eq!(up.done_at().1, 0); + + let make_tex = |w: u64, h: u32, mips: u16, fill: u8| -> (ID3D12Resource, Vec) { + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: h, + DepthOrArraySize: 1, + MipLevels: mips, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &rd, + SHADER_READ, + None, + &mut r, + ) + .unwrap(); + let mut subs = Vec::new(); + for m in 0..mips as usize { + let mw = ((w as usize) >> m).max(1); + let mh = ((h as usize) >> m).max(1); + let mut data = vec![0u8; mw * mh * 4]; + for (idx, px) in data.chunks_exact_mut(4).enumerate() { + px[0] = fill.wrapping_add(m as u8); + px[1] = (idx & 0xFF) as u8; + px[2] = ((idx >> 8) & 0xFF) as u8; + px[3] = 0xFF; + } + subs.push(Subresource { depth: 1, rows: mh, row_bytes: mw * 4, data }); + } + (r.unwrap(), subs) + }; + + // Batch 1: two distinct textures + one caller-dropped texture share one 4 MiB staging buffer. + let (tex_a, subs_a) = make_tex(64, 64, 3, 0x10); + let (tex_b, subs_b) = make_tex(128, 32, 1, 0x80); + let (tex_ephemeral, subs_ephemeral) = make_tex(32, 32, 1, 0xCC); + let tex_a_raw = windows::core::Interface::as_raw(&tex_a) as usize; + let tex_eph_raw = windows::core::Interface::as_raw(&tex_ephemeral) as usize; + let failed = up + .upload( + &upload_q, + &[ + (tex_a.clone(), subs_a.clone(), vec![SHADER_READ]), + (tex_b.clone(), subs_b.clone(), vec![SHADER_READ]), + (tex_ephemeral, subs_ephemeral, vec![SHADER_READ]), + ], + ) + .unwrap(); + assert!(failed.is_empty()); + assert_eq!(up.done_at().1, 1); + assert_eq!(up.busy.len(), 1, "all 3 textures should pack into one shared staging chunk"); + assert_eq!(up.busy[0].2, UPLOADER_MIN_CHUNK, "small batch should allocate 4 MiB chunk, not 64 MiB"); + assert_eq!(up.dests.len(), 3, "all 3 destination textures must be retained until GPU completion"); + assert_eq!(inflight_dest_refs(tex_a_raw), 1); + assert_eq!(inflight_dest_refs(tex_eph_raw), 1); + assert_eq!(up.allocs.len(), 1); + + // Consuming queue waits on the uploader's fence (no CPU wait on upload_q before submit). + let (fence, val) = up.done_at(); + title_q.Wait(fence, val).unwrap(); + let got_a = read_back(&dev, &title_q, &tex_a, &subs_a); + let got_b = read_back(&dev, &title_q, &tex_b, &subs_b); + assert_eq!(got_a, subs_a); + assert_eq!(got_b, subs_b); + + // Batch 2 (after batch 1 completed on GPU): reuses both the staging buffer and the allocator. + let (tex_c, subs_c) = make_tex(64, 64, 1, 0x55); + let tex_c_raw = windows::core::Interface::as_raw(&tex_c) as usize; + let failed = up + .upload( + &upload_q, + &[ + // One invalid item (wrong subresource count) paired with one valid item. + (tex_a.clone(), vec![], vec![SHADER_READ]), + (tex_c.clone(), subs_c.clone(), vec![SHADER_READ]), + ], + ) + .unwrap(); + assert_eq!(failed.len(), 1); + assert_eq!(failed[0].0, 0); + assert_eq!(up.done_at().1, 2); + assert_eq!(up.busy.len(), 1, "completed staging buffer should be recycled and reused"); + assert_eq!(up.free.len(), 0, "recycled staging buffer should have been taken back for batch 2"); + assert_eq!(up.allocs.len(), 1, "completed allocator should be reused"); + assert_eq!(up.dests.len(), 1, "only valid uploaded targets are retained"); + assert_eq!(inflight_dest_refs(tex_a_raw), 0, "completed batch 1 dests must release tracking"); + assert_eq!(inflight_dest_refs(tex_eph_raw), 0); + assert_eq!(inflight_dest_refs(tex_c_raw), 1); + + let (fence, val) = up.done_at(); + title_q.Wait(fence, val).unwrap(); + assert_eq!(read_back(&dev, &title_q, &tex_c, &subs_c), subs_c); + + // Batch 3: all-invalid batch does not submit or advance fence, and leaves uploader reusable. + let failed = up.upload(&upload_q, &[(tex_c.clone(), vec![], vec![SHADER_READ])]).unwrap(); + assert_eq!(failed.len(), 1); + assert_eq!(up.done_at().1, 2); + assert_eq!(inflight_dest_refs(tex_c_raw), 0); + + // Batch 4 after all-invalid batch still works cleanly. + let (tex_d, subs_d) = make_tex(32, 32, 1, 0x99); + let tex_d_raw = windows::core::Interface::as_raw(&tex_d) as usize; + let failed = up.upload(&upload_q, &[(tex_d.clone(), subs_d.clone(), vec![SHADER_READ])]).unwrap(); + assert!(failed.is_empty()); + assert_eq!(up.done_at().1, 3); + assert_eq!(inflight_dest_refs(tex_d_raw), 1); + let (fence, val) = up.done_at(); + title_q.Wait(fence, val).unwrap(); + assert_eq!(read_back(&dev, &title_q, &tex_d, &subs_d), subs_d); + + // Verify idle allocator cap & oversized buffer non-starvation on the live Uploader: + let big_stub = buffer(&dev, 4096).unwrap(); + up.busy.push_back((0, big_stub, 300 << 20)); + for _ in 0..(UPLOADER_MAX_IDLE_ALLOCS + 3) { + let a: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + up.allocs.push_front((a, 0)); + } + let mut released = Released::default(); + up.recycle_deferred(&mut released).unwrap(); + assert!(up.free.iter().all(|(b, _)| *b <= UPLOADER_MAX_RETAIN), "oversized buffer must not enter free pool"); + assert_eq!(up.allocs.len(), UPLOADER_MAX_IDLE_ALLOCS, "idle allocators must be capped"); + assert!(released.allocs.len() >= 3); + drop(released); + + // Subsequent normal batch still reuses the pooled 4 MiB staging buffer cleanly. + let failed = up.upload(&upload_q, &[(tex_d.clone(), subs_d.clone(), vec![SHADER_READ])]).unwrap(); + assert!(failed.is_empty()); + assert_eq!(up.free.len(), 0, "pooled 4 MiB buffer must be reused after oversized buffer"); + assert_eq!(up.busy.len(), 1); + assert_eq!(inflight_dest_refs(tex_d_raw), 1); + + // Dropping Uploader without calling recycle() must drain both `dests` and `pinned_dests` tracking. + inc_inflight_dest(tex_a_raw); + up.pinned_dests.push(tex_a.clone()); + assert_eq!(inflight_dest_refs(tex_a_raw), 1); + drop(up); + assert_eq!(inflight_dest_refs(tex_d_raw), 0, "Drop must drain dests inflight tracking"); + assert_eq!(inflight_dest_refs(tex_a_raw), 0, "Drop must drain pinned_dests inflight tracking"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 26019155e..e07bba74b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1571,6 +1571,11 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { u.free(p); } } + } else if n == super::title_textures::inflight_dest_refs(this as usize) { + // Title dropped its last ref while XCL's async Uploader still holds `n` internal refs for + // in-flight copies: detach from `title_textures` now so shadowed textures uncover/remap + // immediately; `vram::forget` will run once `Uploader` drops its refs (`n -> 0`). + super::title_textures::forget(this as usize); } n } @@ -2639,6 +2644,9 @@ macro_rules! creator { } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { adopt(*ppv, $kind); + if matches!($kind, Kind::CommandQueue) { + super::title_textures::forget_queue(*ppv as usize); + } } hr } @@ -4550,6 +4558,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::title_textures::forget_queue(this as usize); } n } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 5686538e0..1edb9c58e 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -661,9 +661,15 @@ pub(super) unsafe fn refresh(queue: *mut c_void) { } let _refresh = REFRESH.lock().unwrap(); own_work(|| refresh_once(queue)); + if !sync_uploads() { + wait_for_uploads(queue); + } } unsafe fn refresh_once(queue: *mut c_void) { + if !sync_uploads() { + recycle_uploaders(); + } let Some(u) = crate::gpu::uma::get() else { return }; let sparse = u.has_sparse(); if !sparse && TEXTURES_LEN.load(Ordering::Relaxed) == 0 { @@ -855,10 +861,41 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { continue; } }; - match own_work(|| { - super::vram::before_execute(&queue); + // Wait for any tile mappings on this device BEFORE locking UPLOADERS or submitting copies. + super::vram::before_execute(&queue); + let r = if sync_uploads() { texture::upload_batch(dev, &queue, &batch) - }) { + } else { + let need_new = !UPLOADERS.lock().unwrap().contains_key(&device); + let created = if need_new { + match texture::Uploader::new(dev) { + Ok(u) => Some(u), + Err(e) => { + warn(&e); + continue; + } + } + } else { + None + }; + let mut released = texture::Released::default(); + let mut unused = None; + let res = { + let mut ups = UPLOADERS.lock().unwrap(); + if let Some(u) = created { + if ups.contains_key(&device) { + unused = Some(u); + } else { + ups.insert(device, u); + } + } + ups.get_mut(&device).unwrap().upload_deferred(&queue, &batch, &mut released) + }; + drop(unused); + drop(released); + res + }; + match r { Ok(failed) => { for (_, e) in failed { warn(&e); @@ -870,6 +907,71 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { } } +/// `XCL_SYNC_UPLOADS=1`: wait on the CPU after each upload batch (the pre-`Uploader` path). +fn sync_uploads() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SYNC_UPLOADS").is_ok_and(|v| v.trim() == "1")) +} + +/// Per-device async texture uploaders (`texture::Uploader`). +static UPLOADERS: Mutex> = Mutex::new(BTreeMap::new()); +/// Consuming title queue → last upload fence value it GPU-waited for. +static UPLOAD_WAITED: Mutex> = Mutex::new(BTreeMap::new()); + +/// Number of COM references currently held by async `Uploader`s for in-flight copies to `res`. +pub(super) fn inflight_dest_refs(res: usize) -> u32 { + texture::inflight_dest_refs(res) +} + +/// Fence and value of the latest async texture upload submitted on `device` (`None` if none yet). +/// Acquires only `UPLOADERS` (leaf lock) so callers like `vram::Pages` can read it before locking +/// `PAGES` without lock-order inversion. +pub(super) fn upload_fence_for(device: usize) -> Option<(ID3D12Fence, u64)> { + let ups = UPLOADERS.lock().unwrap(); + ups.get(&device).and_then(|up| { + let (fence, value) = up.done_at(); + (value > 0).then(|| (fence.clone(), value)) + }) +} + +/// Reclaim completed destination refs, staging buffers, and excess idle allocators across all +/// active uploaders, dropping retired COM objects outside the `UPLOADERS` lock. +unsafe fn recycle_uploaders() { + let mut released = texture::Released::default(); + { + let mut ups = UPLOADERS.lock().unwrap(); + for up in ups.values_mut() { + let _ = up.recycle_deferred(&mut released); + } + } + drop(released); +} + +/// Drop wait tracking for a released command queue so pointer reuse cannot skip a future wait. +pub(super) fn forget_queue(queue: usize) { + UPLOAD_WAITED.lock().unwrap().remove(&queue); +} + +/// Before the title submits work on `queue`, order it on the GPU after all texture uploads +/// submitted so far on `queue`'s own device (waiting on a fence from another device would stall +/// `queue` forever in multi-device test processes). +unsafe fn wait_for_uploads(queue: *mut c_void) { + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + if UPLOADERS.lock().unwrap().is_empty() { + return; + } + let mut dev: Option = None; + if q.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let Some((fence, value)) = upload_fence_for(dev.as_raw() as usize) else { return }; + let prev = UPLOAD_WAITED.lock().unwrap().get(&(queue as usize)).copied().unwrap_or(0); + if prev < value && q.Wait(&fence, value).is_ok() { + UPLOAD_WAITED.lock().unwrap().insert(queue as usize, value); + } +} + /// `XCL_TRACE_FRAME`: how much of a title texture's top level is not zero, each time it is /// uploaded (the first 48 uploads of textures of 64x64 and more). fn note_content(va: usize, r: &ID3D12Resource, subs: &[texture::Subresource]) { @@ -1713,4 +1815,150 @@ mod tests { uma.free(base); } } + + /// Regression test for async `Uploader`: dropping an overlapping placed texture while + /// `Uploader::dests` still holds an unrecycled internal COM ref must immediately detach it + /// from `TEXTURES`, uncover and remap the shadowed texture (ordering `pages.queue` after + /// `upload_q`), and allow subsequent rewrites to upload into the uncovered texture cleanly. + #[test] + fn async_drop_of_overlapping_placed_texture_uncovers_and_remaps_shadowed() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let Ok(adapter) = factory.EnumAdapters1(0) else { + println!("SKIPPED async_drop_of_overlapping_placed_texture_uncovers_and_remaps_shadowed: no adapter"); + return; + }; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { + println!("SKIPPED async_drop_of_overlapping_placed_texture_uncovers_and_remaps_shadowed: software adapter"); + return; + } + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev else { + println!("SKIPPED async_drop_of_overlapping_placed_texture_uncovers_and_remaps_shadowed: no D3D12 device"); + return; + }; + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_err() + || opts.ResourceHeapTier.0 < 2 + || opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 + { + println!("SKIPPED async_drop_of_overlapping_placed_texture_uncovers_and_remaps_shadowed: tiled tier < 2"); + return; + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let Some(uma) = crate::gpu::uma::get() else { + println!("SKIPPED async_drop_of_overlapping_placed_texture_uncovers_and_remaps_shadowed: no UMA"); + return; + }; + let Some(base) = uma.alloc(2 << 20, 0x1_0000).map(|p| p as usize) else { + println!("SKIPPED async_drop_of_overlapping_placed_texture_uncovers_and_remaps_shadowed: UMA alloc failed"); + return; + }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let place_tex = |va: usize, desc: &[u8; 0x38]| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = super::super::device_x::create_placed_resource_x(dev.as_raw(), va as u64, desc.as_ptr(), D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), riid, &mut p); + assert!(hr >= 0 && !p.is_null(), "CreatePlacedResourceX failed: {hr:#x}"); + assert!(super::super::vram::is_placed_texture(p as usize)); + ID3D12Resource::from_raw(p) + }; + let fill_tiled = |va: usize, desc: &[u8; 0x38], seed: u8| { + let tex = xg::Texture::new(desc).unwrap(); + let s = tex.texels().unwrap(); + let bytes = std::slice::from_raw_parts_mut(va as *mut u8, tex.size() as usize); + bytes.fill(0); + let l = &s.chain.levels[0]; + let pat: Vec = (0..l.width * l.height * s.bpe as usize).map(|k| seed.wrapping_add((k * 17) as u8)).collect(); + s.chain.tile_level(bytes, 0, 0, &pat); + }; + let read_sub0 = |r: &ID3D12Resource| -> Vec { + let rd = r.GetDesc(); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); + dev.GetCopyableFootprints(&rd, 0, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); + let mut rb: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .unwrap(); + let rb = rb.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + own_work(|| { + super::super::vram::before_execute(&queue); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + texture::wait(&dev, &queue).unwrap(); + }); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let mut out = Vec::with_capacity(rows as usize * row_bytes as usize); + for y in 0..rows as usize { + out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(y * fp.Footprint.RowPitch as usize), row_bytes as usize)); + } + rb.Unmap(0, None); + out + }; + + let old_desc = console_desc(3, 512, 512, 1, 1, 28, 0x109); // 1 MiB + let new_desc = console_desc(3, 256, 256, 1, 1, 28, 0x109); // 256 KiB + + // 1. Place and asynchronously upload old_res, then place & upload overlapping new_res + // (which shadows and unmaps old_res). + let old_res = place_tex(base, &old_desc); + let old_raw = old_res.as_raw() as usize; + fill_tiled(base, &old_desc, 0xAA); + refresh(queue.as_raw()); + + let new_res = place_tex(base + 0x4_0000, &new_desc); + let new_raw = new_res.as_raw() as usize; + fill_tiled(base + 0x4_0000, &new_desc, 0x55); + refresh(queue.as_raw()); + + // 2. Drop new_res IMMEDIATELY (no CPU wait or readback beforehand) while async + // Uploader::dests still holds an internal COM ref to new_res! + if !sync_uploads() { + assert!(inflight_dest_refs(new_raw) >= 1, "new_res must still be held by Uploader::dests before drop"); + } + drop(new_res); + + // new_res must be detached immediately and old_res reactivated & remapped. + { + let t = TEXTURES.lock().unwrap(); + assert!(!t.by_res.contains_key(&new_raw) && !t.shadowed.contains_key(&new_raw), "dropped texture remained in TEXTURES"); + let old_entry = t.by_res.get(&old_raw).expect("shadowed texture must be reactivated immediately"); + assert!(!old_entry.unmapped, "reactivated texture must be remapped"); + } + + // 3. Rewrite old_res and verify pixels match intact (ordering pages.queue after upload_q). + fill_tiled(base, &old_desc, 0xD4); + refresh(queue.as_raw()); + let want = subresources(base, &xg::Texture::new(&old_desc).unwrap()).swap_remove(0).data; + assert_eq!(read_sub0(&old_res), want, "uncovered texture must upload and preserve rewritten pixels"); + + // 4. Another refresh after GPU completion reclaims completed dests even when todo is empty. + drop(old_res); + refresh(queue.as_raw()); + assert_eq!(inflight_dest_refs(new_raw), 0, "completed dest ref must be reclaimed by recycle()"); + assert_eq!(inflight_dest_refs(old_raw), 0, "dropped old_res dest ref must be reclaimed by recycle()"); + + super::super::vram::sweep_idle_for_test(dev.as_raw() as usize); + uma.free(base); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 507c5b696..9dfc4f4f8 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -206,6 +206,8 @@ struct Pages { targets: std::collections::HashMap, /// queue → the fence value it last waited for waited: std::collections::HashMap, + /// last async texture upload `(fence_raw, value)` waited on by `self.queue` + uploads_waited: (usize, u64), } // D3D12 objects are free-threaded @@ -237,9 +239,21 @@ impl Pages { extra_pages: std::collections::HashMap::new(), targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), + uploads_waited: (0, 0), }) } + /// Order `self.queue` after the async texture uploader fence `(fence, value)` before mutating + /// tile mappings on an existing resource (`unmap_superseded` / `remap_if_unmapped`). + unsafe fn wait_uploads(&mut self, fence: &ID3D12Fence, value: u64) { + let key = fence.as_raw() as usize; + if value > 0 && (self.uploads_waited.0 != key || self.uploads_waited.1 < value) { + if self.queue.Wait(fence, value).is_ok() { + self.uploads_waited = (key, value); + } + } + } + fn sweep_map(map: &mut std::collections::HashMap, cooling: &mut std::collections::VecDeque<(Tile, std::time::Instant)>, now: std::time::Instant) { let old: Vec = map.iter().filter(|(_, p)| p.idle_since.is_some_and(|t| now.duration_since(t) >= IDLE)).map(|(&k, _)| k).collect(); for k in old { @@ -504,21 +518,34 @@ unsafe fn place_on_pages( /// unshared tiles (`extra_pages` and unshared tail pages) to the cooling pool immediately. pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { let key = res.as_raw() as usize; + let mut dev: Option = None; + let dev_key = res.GetDevice(&mut dev).ok().and_then(|()| dev).map(|d| d.as_raw() as usize); + let upload_wait = dev_key.and_then(super::title_textures::upload_fence_for); let mut g = PAGES.lock().unwrap(); let now = std::time::Instant::now(); - for pages in g.values_mut().flatten() { - let Some(t) = pages.targets.get_mut(&key) else { continue }; - if !t.mapped { - return; - } - let total = t.total; - let used = std::mem::take(&mut t.used); - let used_extra = std::mem::take(&mut t.used_extra); - t.mapped = false; - pages.unmap(res, total); - pages.release_tiles(used, used_extra, now, true); + let pages = match dev_key { + Some(dk) => match g.get_mut(&dk).and_then(Option::as_mut) { + Some(p) => p, + None => return, + }, + None => match g.values_mut().flatten().find(|p| p.targets.contains_key(&key)) { + Some(p) => p, + None => return, + }, + }; + let Some(t) = pages.targets.get_mut(&key) else { return }; + if !t.mapped { return; } + let total = t.total; + let used = std::mem::take(&mut t.used); + let used_extra = std::mem::take(&mut t.used_extra); + t.mapped = false; + if let Some((fence, val)) = upload_wait { + pages.wait_uploads(&fence, val); + } + pages.unmap(res, total); + pages.release_tiles(used, used_extra, now, true); } /// Re-map a previously unmapped placed texture when the newer placement shadowing it is released. @@ -528,15 +555,20 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { return false; } let Some(dev) = dev else { return false }; + let dev_key = dev.as_raw() as usize; + let upload_wait = super::title_textures::upload_fence_for(dev_key); let key = res.as_raw() as usize; let mut g = PAGES.lock().unwrap(); - let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return false }; + let Some(Some(pages)) = g.get_mut(&dev_key) else { return false }; let Some((va, console_bytes, total, mapped)) = pages.targets.get(&key).map(|t| (t.va, t.console_bytes, t.total, t.mapped)) else { return false; }; if mapped { return true; } + if let Some((fence, val)) = upload_wait { + pages.wait_uploads(&fence, val); + } let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total) else { return false; }; @@ -587,6 +619,14 @@ pub(super) fn page_bytes_for(device: usize) -> (usize, usize) { ((p.pages.len() + p.extra_pages.len()) * PAGE, p.pools.len() * POOL_PAGES as usize * PAGE) } +#[cfg(test)] +pub(super) fn sweep_idle_for_test(device: usize) { + let mut g = PAGES.lock().unwrap(); + if let Some(Some(p)) = g.get_mut(&device) { + p.sweep(std::time::Instant::now() + IDLE + std::time::Duration::from_secs(1)); + } +} + /// (bytes of pages in use by tiled textures, bytes of pool heaps) – `XCL_ACTIVITY` pub fn page_bytes() -> (usize, usize) { let g = PAGES.lock().unwrap(); From 7d1c466bff33329a5a6f0bc3f24e8559d2f3789a Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 20:56:01 -0300 Subject: [PATCH 02/16] xg: guard CopyFromSubresource destination span and log invalid arguments --- crates/xcl/src/hle/xg.rs | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/xg.rs b/crates/xcl/src/hle/xg.rs index 0eec7dc16..22aae68d0 100644 --- a/crates/xcl/src/hle/xg.rs +++ b/crates/xcl/src/hle/xg.rs @@ -695,14 +695,37 @@ unsafe extern "system" fn copy_into(p: *mut c_void, dst: *mut u8, plane: u32, su } /// the level's place in `src` (the whole resource) → rows of `dst` (`row_pitch` apart) -unsafe extern "system" fn copy_from(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, src: *const u8, row_pitch: u32, slice_pitch: u32) -> HRESULT { +unsafe extern "system" fn copy_from(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, src: *const u8, row_pitch_raw: usize, slice_pitch_raw: usize) -> HRESULT { let Some((t, at, i, k)) = subresource(tex(p), plane, sub).filter(|_| !dst.is_null() && !src.is_null()) else { return E_INVALIDARG }; let m = t.chain.levels[i]; let row = m.width * t.bpe as usize; + static SEEN: AtomicU32 = AtomicU32::new(0); + let pitch = row_pitch_raw as u32 as usize; + let slice_pitch = slice_pitch_raw as u32 as usize; + let last_off = m.height.saturating_sub(1).checked_mul(pitch).and_then(|o| o.checked_add(row)); + let dst_ok = pitch >= row + && last_off.is_some_and(|span| { + span <= (256 << 20) + && (dst as usize).checked_add(span).is_some() + && crate::gpu::shader::readable(dst as usize, 1) + && crate::gpu::shader::readable((dst as usize) + span.saturating_sub(1), 1) + }); + if !dst_ok { + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!( + "xg: CopyFromSubresource bad dst span: dst={dst:p} plane={plane} sub={sub} src={src:p} arg5={row_pitch_raw:#x} arg6={slice_pitch_raw:#x} (row={row:#x}, h={}, depth={}, bpe={}, mode={:#x})", + m.height, + t.depth, + t.bpe, + t.mode + ); + } + return E_INVALIDARG; + } if t.depth > 0 { let linear = t.chain.detile_volume(std::slice::from_raw_parts(src.add(at as usize), t.size() as usize), i); for (n, from) in linear.chunks_exact(row).enumerate() { - let to = n / m.height * slice_pitch as usize + n % m.height * row_pitch as usize; + let to = n / m.height * slice_pitch + n % m.height * pitch; std::ptr::copy_nonoverlapping(from.as_ptr(), dst.add(to), row); } return S_OK; @@ -710,7 +733,7 @@ unsafe extern "system" fn copy_from(p: *mut c_void, dst: *mut u8, plane: u32, su let slice = std::slice::from_raw_parts(src.add(at as usize + k * t.chain.slice_bytes), t.chain.slice_bytes); let linear = t.chain.detile_level(slice, i, k); for y in 0..m.height { - std::ptr::copy_nonoverlapping(linear[y * row..].as_ptr(), dst.add(y * row_pitch as usize), row); + std::ptr::copy_nonoverlapping(linear[y * row..].as_ptr(), dst.add(y * pitch), row); } S_OK } From ad67ee363c86593840c36f1e8a17155e8d39f4c2 Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 20:59:22 -0300 Subject: [PATCH 03/16] tiling: copy linear mip levels a row at a time --- crates/xcl/src/gpu/tiling.rs | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index 7d9f4be87..b39627b39 100644 --- a/crates/xcl/src/gpu/tiling.rs +++ b/crates/xcl/src/gpu/tiling.rs @@ -365,6 +365,23 @@ impl Chain { let l = self.levels[i]; let e = 1usize << self.layout.elem_log2; let mut out = vec![0u8; l.width * l.height * l.depth * e]; + if self.layout.mode == 0 && self.layout.base_xor == 0 && l.origin == (0, 0) { + let row_bytes = l.width * e; + let stride = l.pitch.div_ceil(self.layout.block_w) * self.layout.block_bytes; + for z in 0..l.depth { + let z_off = z * self.slice_bytes + l.offset; + for y in 0..l.height { + let o = z_off + y * stride; + if let Some(avail) = mem.len().checked_sub(o) { + let n = (avail.min(row_bytes) / e) * e; + if n > 0 { + out[(z * l.height + y) * row_bytes..][..n].copy_from_slice(&mem[o..o + n]); + } + } + } + } + return out; + } for z in 0..l.depth { for y in 0..l.height { for x in 0..l.width { @@ -398,6 +415,20 @@ impl Chain { let l = self.levels[i]; let e = 1usize << self.layout.elem_log2; let mut out = vec![0u8; l.width * l.height * e]; + if self.layout.mode == 0 && self.layout.base_xor == 0 && l.origin == (0, 0) { + let row_bytes = l.width * e; + let stride = l.pitch.div_ceil(self.layout.block_w) * self.layout.block_bytes; + for y in 0..l.height { + let o = l.offset + y * stride; + if let Some(avail) = src.len().checked_sub(o) { + let n = (avail.min(row_bytes) / e) * e; + if n > 0 { + out[y * row_bytes..][..n].copy_from_slice(&src[o..o + n]); + } + } + } + return out; + } for y in 0..l.height { for x in 0..l.width { let o = self.element_at(&l, x, y, slice); @@ -413,6 +444,15 @@ impl Chain { pub fn tile_level(&self, dst: &mut [u8], i: usize, slice: usize, linear: &[u8]) { let l = self.levels[i]; let e = 1usize << self.layout.elem_log2; + if self.layout.mode == 0 && self.layout.base_xor == 0 && l.origin == (0, 0) { + let row_bytes = l.width * e; + let stride = l.pitch.div_ceil(self.layout.block_w) * self.layout.block_bytes; + for y in 0..l.height { + let o = l.offset + y * stride; + dst[o..o + row_bytes].copy_from_slice(&linear[y * row_bytes..][..row_bytes]); + } + return; + } for y in 0..l.height { for x in 0..l.width { let o = self.element_at(&l, x, y, slice); From 9c4c3e62e987cf8d64b80b129cccc667ac2253ad Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 21:06:58 -0300 Subject: [PATCH 04/16] xg: fix CopyFromSubresource 7-argument ABI (extra u32 before src) --- crates/xcl/src/hle/xg.rs | 62 ++++++++++++++++++++++++++++++----- crates/xcl/tests/xg_oracle.rs | 5 +-- 2 files changed, 57 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/xg.rs b/crates/xcl/src/hle/xg.rs index 22aae68d0..0c26cf7b4 100644 --- a/crates/xcl/src/hle/xg.rs +++ b/crates/xcl/src/hle/xg.rs @@ -694,14 +694,23 @@ unsafe extern "system" fn copy_into(p: *mut c_void, dst: *mut u8, plane: u32, su S_OK } -/// the level's place in `src` (the whole resource) → rows of `dst` (`row_pitch` apart) -unsafe extern "system" fn copy_from(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, src: *const u8, row_pitch_raw: usize, slice_pitch_raw: usize) -> HRESULT { +/// #9 CopyFromSubresource(dst, plane, sub, _arg4, src, row_pitch, slice_pitch): +/// the level's place in `src` (the whole tiled resource) → linear rows at `dst` (`row_pitch` apart). +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn copy_from( + p: *mut c_void, + dst: *mut u8, + plane: u32, + sub: u32, + arg4: u32, + src: *const u8, + row_pitch: u32, + slice_pitch: u32, +) -> HRESULT { let Some((t, at, i, k)) = subresource(tex(p), plane, sub).filter(|_| !dst.is_null() && !src.is_null()) else { return E_INVALIDARG }; let m = t.chain.levels[i]; let row = m.width * t.bpe as usize; - static SEEN: AtomicU32 = AtomicU32::new(0); - let pitch = row_pitch_raw as u32 as usize; - let slice_pitch = slice_pitch_raw as u32 as usize; + let pitch = row_pitch as usize; let last_off = m.height.saturating_sub(1).checked_mul(pitch).and_then(|o| o.checked_add(row)); let dst_ok = pitch >= row && last_off.is_some_and(|span| { @@ -711,9 +720,10 @@ unsafe extern "system" fn copy_from(p: *mut c_void, dst: *mut u8, plane: u32, su && crate::gpu::shader::readable((dst as usize) + span.saturating_sub(1), 1) }); if !dst_ok { - if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + static BAD: AtomicU32 = AtomicU32::new(0); + if BAD.fetch_add(1, Ordering::Relaxed) < 8 { crate::xlog_warn!( - "xg: CopyFromSubresource bad dst span: dst={dst:p} plane={plane} sub={sub} src={src:p} arg5={row_pitch_raw:#x} arg6={slice_pitch_raw:#x} (row={row:#x}, h={}, depth={}, bpe={}, mode={:#x})", + "xg: CopyFromSubresource invalid span: dst={dst:p} plane={plane} sub={sub} arg4={arg4:#x} src={src:p} row_pitch={row_pitch:#x} slice_pitch={slice_pitch:#x} (row={row:#x}, h={}, depth={}, bpe={}, mode={:#x})", m.height, t.depth, t.bpe, @@ -722,10 +732,20 @@ unsafe extern "system" fn copy_from(p: *mut c_void, dst: *mut u8, plane: u32, su } return E_INVALIDARG; } + static OK_LOG: AtomicU32 = AtomicU32::new(0); + if OK_LOG.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "xg: CopyFromSubresource: dst={dst:p} plane={plane} sub={sub} arg4={arg4:#x} src={src:p} row_pitch={row_pitch:#x} slice_pitch={slice_pitch:#x} (row={row:#x}, h={}, depth={}, bpe={}, mode={:#x})", + m.height, + t.depth, + t.bpe, + t.mode + ); + } if t.depth > 0 { let linear = t.chain.detile_volume(std::slice::from_raw_parts(src.add(at as usize), t.size() as usize), i); for (n, from) in linear.chunks_exact(row).enumerate() { - let to = n / m.height * slice_pitch + n % m.height * pitch; + let to = n / m.height * slice_pitch as usize + n % m.height * pitch; std::ptr::copy_nonoverlapping(from.as_ptr(), dst.add(to), row); } return S_OK; @@ -806,4 +826,30 @@ mod tests { assert_eq!((t.size(), t.alignment()), (rgb10a2.size(), rgb10a2.alignment())); } } + + #[test] + fn copy_into_and_copy_from_round_trip() { + let d = desc(64, 32, 1, 1, 28, 0x105); + let mut comp = std::ptr::null_mut(); + unsafe { + assert_eq!(XGCreateTextureComputer(d.as_ptr(), &mut comp), S_OK); + let vt = *(comp as *const *const usize); + let get_size: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(*vt.add(3)); + let into: unsafe extern "system" fn(*mut c_void, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT = std::mem::transmute(*vt.add(8)); + let from: unsafe extern "system" fn(*mut c_void, *mut u8, u32, u32, u32, *const u8, u32, u32) -> HRESULT = std::mem::transmute(*vt.add(9)); + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*vt.add(1)); + + let size = get_size(comp) as usize; + let pitch = 64 * 4 + 16; + let src: Vec = (0..pitch * 32).map(|i: usize| (i.wrapping_mul(37) ^ (i >> 5)) as u8).collect(); + let mut tiled = vec![0u8; size]; + let mut dst = vec![0u8; pitch * 32]; + assert_eq!(into(comp, tiled.as_mut_ptr(), 0, 0, src.as_ptr(), pitch as u32, (pitch * 32) as u32), S_OK); + assert_eq!(from(comp, dst.as_mut_ptr(), 0, 0, 0, tiled.as_ptr(), pitch as u32, (pitch * 32) as u32), S_OK); + for y in 0..32 { + assert_eq!(dst[y * pitch..y * pitch + 64 * 4], src[y * pitch..y * pitch + 64 * 4], "row {y}"); + } + rel(comp); + } + } } diff --git a/crates/xcl/tests/xg_oracle.rs b/crates/xcl/tests/xg_oracle.rs index 49a7d6508..3d02993c7 100644 --- a/crates/xcl/tests/xg_oracle.rs +++ b/crates/xcl/tests/xg_oracle.rs @@ -400,9 +400,10 @@ fn subresource_copies_match_the_console_library() { assert_eq!(into(c)(c, a.as_mut_ptr(), 0, sub, lin.as_ptr(), pitch as u32, (pitch * l.height) as u32), 0); assert_eq!(into(o)(o, b.as_mut_ptr(), 0, sub, lin.as_ptr(), pitch as u32, (pitch * l.height) as u32), 0); // ours reads the console's bytes back - let from: Copy = std::mem::transmute(*(*(o as *const *const usize)).add(9)); + type CopyFrom = unsafe extern "system" fn(*mut std::ffi::c_void, *mut u8, u32, u32, u32, *const u8, u32, u32) -> i32; + let from: CopyFrom = std::mem::transmute(*(*(o as *const *const usize)).add(9)); let mut back = vec![0u8; pitch * l.height]; - assert_eq!(from(o, back.as_mut_ptr(), 0, sub, a.as_ptr(), pitch as u32, 0), 0); + assert_eq!(from(o, back.as_mut_ptr(), 0, sub, 0, a.as_ptr(), pitch as u32, 0), 0); for y in 0..l.height { assert_eq!(back[y * pitch..y * pitch + row], lin[y * pitch..y * pitch + row], "layout {layout:#x} format {f} mip {i} slice {s} row {y}"); } From dc74a88b327878a16a66e79c7abc32c8b8bfc563 Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 21:15:32 -0300 Subject: [PATCH 05/16] tiling/title_textures: hoisted tiled detiling and parallel batch detiling --- crates/xcl/src/gpu/tiling.rs | 86 +++++++++++++++++++-- crates/xcl/src/hle/d3d12x/title_textures.rs | 36 ++++++++- 2 files changed, 114 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index b39627b39..3eea4a17f 100644 --- a/crates/xcl/src/gpu/tiling.rs +++ b/crates/xcl/src/gpu/tiling.rs @@ -415,6 +415,9 @@ impl Chain { let l = self.levels[i]; let e = 1usize << self.layout.elem_log2; let mut out = vec![0u8; l.width * l.height * e]; + if l.width == 0 || l.height == 0 { + return out; + } if self.layout.mode == 0 && self.layout.base_xor == 0 && l.origin == (0, 0) { let row_bytes = l.width * e; let stride = l.pitch.div_ceil(self.layout.block_w) * self.layout.block_bytes; @@ -429,11 +432,84 @@ impl Chain { } return out; } - for y in 0..l.height { - for x in 0..l.width { - let o = self.element_at(&l, x, y, slice); - if let Some(s) = src.get(o..o + e) { - out[(y * l.width + x) * e..][..e].copy_from_slice(s); + let lay = &self.layout; + let bw_shift = lay.block_w.trailing_zeros(); + let bw_mask = lay.block_w - 1; + let bh_shift = lay.block_h.trailing_zeros(); + let bh_mask = lay.block_h - 1; + let bd_shift = lay.block_d.trailing_zeros(); + let bd_mask = lay.block_d - 1; + let blk_shift = lay.block_bytes.trailing_zeros(); + let hx_mask = lay.hx.len() - 1; + let hy_mask = lay.hy.len() - 1; + let hz_mask = lay.hz.len() - 1; + let pitch_bytes = l.pitch.div_ceil(lay.block_w) << blk_shift; + let z_xor = (lay.oz[slice & bd_mask] ^ lay.hz[(slice >> bd_shift) & hz_mask]) as usize ^ lay.base_xor; + let ox0 = l.origin.0; + let oy0 = l.origin.1; + + let mut x_blk = Vec::with_capacity(l.width); + let mut x_xor = Vec::with_capacity(l.width); + for x in 0..l.width { + let gx = x + ox0; + let bx = gx >> bw_shift; + x_blk.push(bx << blk_shift); + x_xor.push((lay.ox[gx & bw_mask] ^ lay.hx[bx & hx_mask]) as usize); + } + + let src_len = src.len(); + let max_gy = oy0 + l.height - 1; + let max_gx = ox0 + l.width - 1; + let max_end = l.offset + ((max_gy >> bh_shift) * pitch_bytes) + (((max_gx >> bw_shift) + 1) << blk_shift); + let all_in_bounds = max_end <= src_len && (lay.base_xor & (e - 1)) == 0; + + macro_rules! detile_elem { + ($n:literal) => {{ + let row_bytes = l.width * $n; + if all_in_bounds { + for y in 0..l.height { + let gy = y + oy0; + let by = gy >> bh_shift; + let row_base = l.offset + by * pitch_bytes; + let y_xor = (lay.oy[gy & bh_mask] ^ lay.hy[by & hy_mask]) as usize ^ z_xor; + let dst_row = &mut out[y * row_bytes..][..row_bytes]; + for x in 0..l.width { + let o = row_base + x_blk[x] + (x_xor[x] ^ y_xor); + dst_row[x * $n..x * $n + $n].copy_from_slice(&src[o..o + $n]); + } + } + } else { + for y in 0..l.height { + let gy = y + oy0; + let by = gy >> bh_shift; + let row_base = l.offset + by * pitch_bytes; + let y_xor = (lay.oy[gy & bh_mask] ^ lay.hy[by & hy_mask]) as usize ^ z_xor; + let dst_row = &mut out[y * row_bytes..][..row_bytes]; + for x in 0..l.width { + let o = row_base + x_blk[x] + (x_xor[x] ^ y_xor); + if let Some(s) = src.get(o..o + $n) { + dst_row[x * $n..x * $n + $n].copy_from_slice(s); + } + } + } + } + }}; + } + + match e { + 1 => detile_elem!(1), + 2 => detile_elem!(2), + 4 => detile_elem!(4), + 8 => detile_elem!(8), + 16 => detile_elem!(16), + _ => { + for y in 0..l.height { + for x in 0..l.width { + let o = self.element_at(&l, x, y, slice); + if let Some(s) = src.get(o..o + e) { + out[(y * l.width + x) * e..][..e].copy_from_slice(s); + } + } } } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 1edb9c58e..d65583e7a 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -822,11 +822,11 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { }; let mut todo = todo.into_iter().peekable(); while todo.peek().is_some() { - let mut batch = Vec::new(); + let mut raw = Vec::new(); let mut bytes = 0usize; let mut device = 0usize; while let Some((_, (dev, _, tex, _))) = todo.peek() { - if !batch.is_empty() && (bytes + tex.size() as usize > BATCH_BYTES || *dev != device) { + if !raw.is_empty() && (bytes + tex.size() as usize > BATCH_BYTES || *dev != device) { break; } let (r, (dev, va, tex, states)) = todo.next().unwrap(); @@ -846,7 +846,37 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { } device = dev; bytes += tex.size() as usize; - let subs = subresources(va, &tex); + raw.push((r, va, tex, states)); + } + let mut subs_all: Vec> = vec![Vec::new(); raw.len()]; + let workers = if raw.len() >= 2 && bytes >= (256 << 10) { + std::thread::available_parallelism().map_or(4, |n| n.get()).min(raw.len()).min(16) + } else { + 1 + }; + if workers <= 1 { + for (slot, (_, va, tex, _)) in subs_all.iter_mut().zip(raw.iter()) { + *slot = subresources(*va, tex); + } + } else { + use std::sync::atomic::AtomicUsize; + let next = AtomicUsize::new(0); + let tasks: Vec<(usize, Arc)> = raw.iter().map(|(_, va, tex, _)| (*va, Arc::clone(tex))).collect(); + let slots_ptr = subs_all.as_mut_ptr() as usize; + std::thread::scope(|s| { + for _ in 0..workers { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some((va, tex)) = tasks.get(i) else { break }; + let subs = subresources(*va, tex); + // SAFETY: each index `i < raw.len()` is claimed by at most one worker thread. + *(slots_ptr as *mut Vec).add(i) = subs; + }); + } + }); + } + let mut batch = Vec::with_capacity(raw.len()); + for ((r, va, _, states), subs) in raw.into_iter().zip(subs_all) { if super::present::trace_frame() { note_content(va, &r, &subs); } From 3a23ed4a1ff7732cf48a2069d7a80f083e00b55b Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 21:31:22 -0300 Subject: [PATCH 06/16] vram: coalesce page-queue fence signals and throttle idle-page sweeps --- crates/xcl/src/hle/d3d12x/vram.rs | 61 ++++++++++++++++++++++++++----- 1 file changed, 51 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 9dfc4f4f8..f7966d999 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -166,6 +166,9 @@ const IDLE: std::time::Duration = std::time::Duration::from_secs(2); /// a pool tile given back is not reused before this (the GPU may still be at work on what the /// title released) const COOL: std::time::Duration = std::time::Duration::from_secs(2); +/// minimum interval between full idle-page scans in `Pages::bind` (avoids O(N^2) rescans over +/// tens of thousands of live pages during texture-creation bursts while `IDLE` is 2 s) +const SWEEP_INTERVAL: std::time::Duration = std::time::Duration::from_millis(250); /// A pool tile: (pool heap, tile in it). type Tile = (u32, u32); @@ -190,9 +193,11 @@ struct Target { /// The title's pages of video memory for tiled textures (see the module's comment). struct Pages { queue: ID3D12CommandQueue, - /// signalled after each mapping; title queues wait for it before their next work + /// signalled lazily in `before_execute` when `dirty` is set; title queues wait for it fence: ID3D12Fence, value: u64, + /// `UpdateTileMappings` queued on `self.queue` since the last `Signal(&self.fence, ...)` + dirty: bool, pools: Vec, free: Vec, /// tiles given back, reusable after `COOL` @@ -202,6 +207,10 @@ struct Pages { /// extra / sub-64 KiB tiles keyed by `(va, tile_index)` so repeated placements at the same /// address share them without aliasing unrelated addresses extra_pages: std::collections::HashMap<(usize, usize), Page>, + /// true when any entry in `pages` or `extra_pages` may have `idle_since.is_some()` + has_idle: bool, + /// last wall-clock sweep triggered from `bind` + last_sweep: std::time::Instant, /// resource → its mapping metadata and currently held pages / extra keys targets: std::collections::HashMap, /// queue → the fence value it last waited for @@ -232,11 +241,14 @@ impl Pages { queue, fence, value: 0, + dirty: false, pools: Vec::new(), free: Vec::new(), cooling: std::collections::VecDeque::new(), pages: std::collections::HashMap::new(), extra_pages: std::collections::HashMap::new(), + has_idle: false, + last_sweep: std::time::Instant::now(), targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), uploads_waited: (0, 0), @@ -254,19 +266,41 @@ impl Pages { } } - fn sweep_map(map: &mut std::collections::HashMap, cooling: &mut std::collections::VecDeque<(Tile, std::time::Instant)>, now: std::time::Instant) { - let old: Vec = map.iter().filter(|(_, p)| p.idle_since.is_some_and(|t| now.duration_since(t) >= IDLE)).map(|(&k, _)| k).collect(); + fn sweep_map(map: &mut std::collections::HashMap, cooling: &mut std::collections::VecDeque<(Tile, std::time::Instant)>, now: std::time::Instant) -> bool { + let mut old = Vec::new(); + let mut any_idle = false; + for (&k, p) in map.iter() { + if let Some(t) = p.idle_since { + if now.saturating_duration_since(t) >= IDLE { + old.push(k); + } else { + any_idle = true; + } + } + } for k in old { if let Some(p) = map.remove(&k) { cooling.push_back((p.tile, now)); } } + any_idle } /// Pages no resource used for `IDLE` go back to the pools. fn sweep(&mut self, now: std::time::Instant) { - Self::sweep_map(&mut self.pages, &mut self.cooling, now); - Self::sweep_map(&mut self.extra_pages, &mut self.cooling, now); + if !self.has_idle { + return; + } + let rem_a = Self::sweep_map(&mut self.pages, &mut self.cooling, now); + let rem_b = Self::sweep_map(&mut self.extra_pages, &mut self.cooling, now); + self.has_idle = rem_a || rem_b; + } + + fn maybe_sweep(&mut self, now: std::time::Instant) { + if self.has_idle && now.saturating_duration_since(self.last_sweep) >= SWEEP_INTERVAL { + self.last_sweep = now; + self.sweep(now); + } } unsafe fn take_tile(&mut self, dev: &ID3D12Device) -> Option { @@ -319,8 +353,7 @@ impl Pages { D3D12_TILE_MAPPING_FLAG_NONE, ); } - self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + self.dirty = true; } /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return @@ -341,8 +374,7 @@ impl Pages { Some(&total), D3D12_TILE_MAPPING_FLAG_NONE, ); - self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + self.dirty = true; } fn release_tiles(&mut self, used: Vec, used_extra: Vec<(usize, usize)>, now: std::time::Instant, immediate_cool: bool) { @@ -356,6 +388,7 @@ impl Pages { } } else { p.idle_since = Some(now); + self.has_idle = true; } } } @@ -370,6 +403,7 @@ impl Pages { } } else { p.idle_since = Some(now); + self.has_idle = true; } } } @@ -380,7 +414,7 @@ impl Pages { unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); - self.sweep(now); + self.maybe_sweep(now); let mut tiles = Vec::with_capacity(total as usize); let mut used = Vec::with_capacity(own); let mut used_extra = Vec::new(); @@ -602,6 +636,13 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let Some(dev) = dev else { return }; let mut g = PAGES.lock().unwrap(); let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return }; + if pages.dirty { + let next = pages.value + 1; + if pages.queue.Signal(&pages.fence, next).is_ok() { + pages.value = next; + pages.dirty = false; + } + } let key = queue.as_raw() as usize; if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { let _ = queue.Wait(&pages.fence, pages.value); From a5c4937d6381876f412ff388ff60169565dcf2d1 Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 21:31:22 -0300 Subject: [PATCH 07/16] pso_async: pre-compile compute PSOs in the background while keeping graphics lazy --- crates/xcl/src/hle/d3d12x/pso_async.rs | 15 ++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 3 ++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index e4769de82..3a9c281f4 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -75,7 +75,11 @@ fn queue() -> &'static Mutex>> { // (None: a bind took it and builds it itself) let job = p.job.lock().unwrap().take(); if let Some(job) = job { - complete(&p, job()); + if p.orphan.load(Ordering::Acquire) { + complete(&p, 0); + } else { + complete(&p, job()); + } } }); } @@ -105,6 +109,15 @@ pub fn lazy() -> bool { *L.get_or_init(|| enabled() && std::env::var("XCL_LAZY_PSO").map_or(true, |v| v != "0")) } +/// Lazy creation for compute pipelines (`XCL_LAZY_COMPUTE_PSO=1` to defer them until first +/// bind like graphics pipelines). Graphics pipelines stay lazy because they never block on +/// bind; compute pipelines block in `resolve_wait` at first bind, so pre-compiling them in +/// the background avoids cold-compile stalls when a frame binds many compute shaders at once. +pub fn lazy_compute() -> bool { + static L: OnceLock = OnceLock::new(); + *L.get_or_init(|| lazy() && std::env::var("XCL_LAZY_COMPUTE_PSO").is_ok_and(|v| v == "1")) +} + /// `submit`, sent to the workers only on its first `resolve` (`lazy`). pub fn submit_lazy(standin: usize, compute: bool, job: Job) { submit_as(standin, compute, job, false); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e07bba74b..762544f2c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3702,7 +3702,8 @@ unsafe fn go_background( return None; } let dev = Dev(this as usize, f as usize); - let submit = if super::pso_async::lazy() { super::pso_async::submit_lazy } else { super::pso_async::submit }; + let use_lazy = if compute { super::pso_async::lazy_compute() } else { super::pso_async::lazy() }; + let submit = if use_lazy { super::pso_async::submit_lazy } else { super::pso_async::submit }; submit( *ppv as usize, compute, From 924670f504cedd8e386285b25d36446489b90695 Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 21:47:03 -0300 Subject: [PATCH 08/16] title_textures: cache VirtualQuery region spans in sorted recheck_gpu_view_sources --- crates/xcl/src/hle/d3d12x/title_textures.rs | 59 +++++++++++++++++---- 1 file changed, 49 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d65583e7a..3466fbb90 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -396,18 +396,41 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, Ok(()) } +/// Region cache `(base, end, committed)` from `VirtualQuery` for sorted address scans. +type RegionCache = Option<(usize, usize, bool)>; + +fn va_committed(va: usize, cache: &mut RegionCache) -> bool { + if let Some((base, end, committed)) = *cache { + if va >= base && va < end { + return committed; + } + } + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return false; + } + let base = m.BaseAddress as usize; + let end = base.saturating_add(m.RegionSize); + let committed = m.State == MEM_COMMIT; + *cache = Some((base, end, committed)); + committed +} + /// Where a texture at `va` is read from: the CPU view behind a GPU view (`kernelx::mirrors`) /// when nothing is mapped at `va` itself, else `va`. A physical page mapped at `va` counts /// before its first use too, while it is still reserved memory (`kernelx::physical_page_at`). -fn mirror_source(va: usize) -> usize { +fn mirror_source_cached(va: usize, cache: &mut RegionCache) -> usize { let Some(src) = crate::hle::kernelx::mirrors::source(va) else { return va }; if crate::hle::kernelx::physical_page_at(va) { return va; } - use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; - let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - let mapped = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0 && m.State == MEM_COMMIT; - if mapped { va } else { src } + if va_committed(va, cache) { va } else { src } +} + +fn mirror_source(va: usize) -> usize { + let mut cache = None; + mirror_source_cached(va, &mut cache) } /// Physical pages were mapped or unmapped in a GPU view since the last look: textures there @@ -420,11 +443,21 @@ fn recheck_gpu_view_sources() { return; } let mut changed = false; - // (the shadowed textures too: one comes back when the texture over it goes) + // Iterate in sorted `va` order (`by_va` / `shadowed_by_va`) so consecutive GPU-view textures + // inside the same reserved/committed region reuse a single `VirtualQuery` result instead of + // repeating 30k+ syscalls on the render thread. let mut g = TEXTURES.lock().unwrap(); let t = &mut *g; - for e in t.by_res.values_mut().chain(t.shadowed.values_mut()) { - changed |= recheck_source(e); + let mut cache: RegionCache = None; + for &(_, res) in t.by_va.keys() { + if let Some(e) = t.by_res.get_mut(&res) { + changed |= recheck_source_cached(e, &mut cache); + } + } + for &(_, res) in t.shadowed_by_va.keys() { + if let Some(e) = t.shadowed.get_mut(&res) { + changed |= recheck_source_cached(e, &mut cache); + } } drop(g); if changed { @@ -434,11 +467,11 @@ fn recheck_gpu_view_sources() { /// `e`'s source again (a texture in a GPU view): when it changed, `e` reads the new one and is /// uploaded at the next submit. Whether it changed. -fn recheck_source(e: &mut Entry) -> bool { +fn recheck_source_cached(e: &mut Entry, cache: &mut RegionCache) -> bool { if !e.in_gpu_view { return false; } - let src = mirror_source(e.va); + let src = mirror_source_cached(e.va, cache); if src == e.src { return false; } @@ -450,6 +483,12 @@ fn recheck_source(e: &mut Entry) -> bool { true } +#[cfg(test)] +fn recheck_source(e: &mut Entry) -> bool { + let mut cache = None; + recheck_source_cached(e, &mut cache) +} + /// The title's GPU work writes texture `res` (a copy into it): on the console the memory then /// holds what the GPU wrote; here the CPU's view of it is stale, so it is not uploaded again /// (a CPU write elsewhere on its pages – a neighbour, an allocator's header – would upload the From 0eca36e1961e1761a450859046ca206199686c82 Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 21:47:03 -0300 Subject: [PATCH 09/16] pso_async: route big compute driver compiles to dedicated pool without starving small PSOs --- crates/xcl/src/hle/d3d12x/pso_async.rs | 82 +++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 74 +++++++++++------------ 2 files changed, 116 insertions(+), 40 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 3a9c281f4..0d203c0ca 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -23,6 +23,8 @@ struct Pending { compute: bool, /// the stand-in was released before the real pipeline was built orphan: std::sync::atomic::AtomicBool, + /// title threads currently blocked in `resolve_wait` for this pipeline + waiters: AtomicUsize, } /// stand-in handed to the title → its real pipeline @@ -60,13 +62,56 @@ pub fn enabled() -> bool { /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box usize + Send>; +thread_local! { + /// True while a regular `xcl-pso-*` worker executes a job. + static IN_NORMAL_WORKER: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Remaining driver-compile closure deferred from a regular worker to `big_queue()`. + static DEFER_BIG: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// True when running on a regular `xcl-pso-*` worker (not a title thread or `xcl-pso-big`). +pub fn in_normal_worker() -> bool { + IN_NORMAL_WORKER.with(|c| c.get()) +} + +/// Park a slow driver compile for the dedicated `xcl-pso-big-*` pool so regular `xcl-pso-*` +/// workers stay free for smaller pipelines. Only effective when `in_normal_worker()` is true. +pub fn defer_big(rest: Job) { + DEFER_BIG.with(|slot| *slot.borrow_mut() = Some(rest)); +} + +fn big_queue() -> &'static Mutex>> { + static BIG_Q: OnceLock>>> = OnceLock::new(); + BIG_Q.get_or_init(|| { + let (tx, rx) = mpsc::channel::>(); + let rx = Arc::new(Mutex::new(rx)); + let n = std::env::var("XCL_BIG_PSO_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(2usize).clamp(1, 4); + for k in 0..n { + let rx = rx.clone(); + let _ = std::thread::Builder::new().name(format!("xcl-pso-big-{k}")).stack_size(64 << 20).spawn(move || loop { + let Ok(p) = rx.lock().unwrap().recv() else { return }; + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + if p.orphan.load(Ordering::Acquire) { + complete(&p, 0); + } else { + complete(&p, job()); + } + } + }); + } + Mutex::new(tx) + }) +} + fn queue() -> &'static Mutex>> { static Q: OnceLock>>> = OnceLock::new(); Q.get_or_init(|| { let (tx, rx) = mpsc::channel::>(); let rx = Arc::new(Mutex::new(rx)); - // translation recurses deeply on big programs; DXC itself runs on its own pool - let n = crate::gpu::recomp::dxc::compile_threads(); + // translation recurses deeply on big programs; DXC itself runs on its own pool. + // Cap normal background PSO workers at 16 so high-core CPUs keep cores free for title/DirectStorage threads. + let n = crate::gpu::recomp::dxc::compile_threads().min(16); for k in 0..n { let rx = rx.clone(); let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { @@ -78,7 +123,29 @@ fn queue() -> &'static Mutex>> { if p.orphan.load(Ordering::Acquire) { complete(&p, 0); } else { - complete(&p, job()); + IN_NORMAL_WORKER.with(|c| c.set(true)); + DEFER_BIG.with(|s| *s.borrow_mut() = None); + let real = job(); + IN_NORMAL_WORKER.with(|c| c.set(false)); + let deferred = DEFER_BIG.with(|s| s.borrow_mut().take()); + if let Some(big_job) = deferred { + if p.orphan.load(Ordering::Acquire) { + complete(&p, 0); + } else if p.waiters.load(Ordering::SeqCst) > 0 { + complete(&p, big_job()); + } else { + *p.job.lock().unwrap() = Some(big_job); + if p.waiters.load(Ordering::SeqCst) > 0 { + if let Some(j) = p.job.lock().unwrap().take() { + complete(&p, j()); + } + } else { + let _ = big_queue().lock().unwrap().send(p); + } + } + } else { + complete(&p, real); + } } } }); @@ -132,6 +199,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool) { cv: Condvar::new(), compute, orphan: Default::default(), + waiters: AtomicUsize::new(0), }); PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); static ONCE: std::sync::Once = std::sync::Once::new(); @@ -166,6 +234,14 @@ pub fn resolve(pso: usize) -> usize { /// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now). pub fn resolve_wait(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; + struct WaiterGuard<'a>(&'a Pending); + impl Drop for WaiterGuard<'_> { + fn drop(&mut self) { + self.0.waiters.fetch_sub(1, Ordering::SeqCst); + } + } + p.waiters.fetch_add(1, Ordering::SeqCst); + let _waiter = WaiterGuard(&p); let job = p.job.lock().unwrap().take(); if let Some(job) = job { complete(&p, job()); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 762544f2c..35c7ce54f 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3297,35 +3297,6 @@ unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { /// DXIL size from which a compute pipeline's driver compile goes to the background const BIG_DRIVER_COMPILE: usize = 256 << 10; -/// A counting semaphore: background driver compiles of big programs at once. -struct Slots { - n: Mutex, - cv: std::sync::Condvar, - most: usize, -} - -struct SlotGuard(&'static Slots); - -impl Slots { - fn acquire(&'static self) -> SlotGuard { - let mut n = self.n.lock().unwrap(); - while *n >= self.most { - n = self.cv.wait(n).unwrap(); - } - *n += 1; - SlotGuard(self) - } -} - -impl Drop for SlotGuard { - fn drop(&mut self) { - *self.0.n.lock().unwrap() -= 1; - self.0.cv.notify_one(); - } -} - -static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1 }; - /// Before a big driver compile in the background: until 3 GB of commit are free (each takes /// ~1.5 GB; the title loading next to it must not run out – no minute's grace as for DXC). fn wait_for_commit() { @@ -3371,16 +3342,45 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi } let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) }; LAST_COMPUTE_RS.with(|c| c.set(rs as usize)); + let user_sgprs = crate::gpu::recomp::pso::compute_user_sgprs(cs); let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); - copy.CS = bytecode(&dxil); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); - // in the background, one at a time and within the commit left (each ~1.5 GB in the driver) - let _slot = (big && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso"))).then(|| { - let slot = BIG_COMPILES.acquire(); - wait_for_commit(); - slot - }); + // On a regular `xcl-pso-*` worker, hand off big driver compiles to the dedicated `xcl-pso-big-*` + // pool so smaller compute pipelines are never starved behind giant ones. + if big && super::pso_async::in_normal_worker() { + let dev = Dev(this as usize, f as usize); + let rs_raw = rs as usize; + let node_mask = copy.NodeMask; + let flags = copy.Flags; + super::pso_async::defer_big(Box::new(move || { + wait_for_commit(); + let mut out: *mut c_void = std::ptr::null_mut(); + let iid = pc_iid(Kind::PipelineState); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs_raw as *mut c_void), + CS: bytecode(&dxil), + NodeMask: node_mask, + CachedPSO: D3D12_CACHED_PIPELINE_STATE::default(), + Flags: flags, + }; + let hr = finish_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), &desc as *const _ as *const c_void, &iid, &mut out); + if hr < 0 || out.is_null() { + note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); + return 0; + } + TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + note_pso_rs(out, rs_raw as *mut c_void); + if let Some(n) = user_sgprs { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(out as usize, n); + } + note_translated_compute(hr, &mut out); + crate::xlog_info!("D3D12.X: compute PSO with the translated console CS ({} B DXIL)", dxil.len()); + out as usize + })); + return Some(Err(())); + } + copy.CS = bytecode(&dxil); let hr = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); if hr < 0 { note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); @@ -3388,7 +3388,7 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi } TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { + if let Some(n) = user_sgprs { PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } note_translated_compute(hr, ppv); From d37cf8014dfc39d3cae3d7a8fadff10c5c2aaac5 Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 21:56:04 -0300 Subject: [PATCH 10/16] tiling: cache Layout offset tables with Arc slices and trim unused high-bit tables --- crates/xcl/src/gpu/tiling.rs | 67 +++++++++++++++++++++++++++--------- 1 file changed, 51 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index 3eea4a17f..f69704aa3 100644 --- a/crates/xcl/src/gpu/tiling.rs +++ b/crates/xcl/src/gpu/tiling.rs @@ -6,10 +6,13 @@ //! offset is linear over GF(2): `offset(x, y, z) = ox[x] ^ oy[y] ^ oz[z]`, small tables per //! layout. Blocks (256 B / 4 KB / 64 KB) are laid out row-major; `Chain` lays out the mips. +use std::collections::HashMap; +use std::sync::{Arc, OnceLock, RwLock}; + use super::tiling_tables::{NIBBLE01, NIBBLE2, NIBBLE3, NIBBLE4, PATTERNS, PATTERNS_3D}; /// The part of GB_ADDR_CONFIG the XOR modes depend on (number of pipes and packers, log2). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct PipeConfig { pub pipes_log2: u32, pub pkrs_log2: u32, @@ -63,14 +66,21 @@ pub struct Layout { /// XORed into every in-block byte offset: the pipe / bank swizzle a T# base address carries /// in its low bits (`base & (block_bytes - 1)`), 0 otherwise pub base_xor: usize, - ox: Vec, - oy: Vec, - oz: Vec, + ox: Arc<[u32]>, + oy: Arc<[u32]>, + oz: Arc<[u32]>, /// the in-block bits the coordinates above the block give (XOR modes with many pipes take /// pipe bits from neighbouring blocks' coordinates), by `x >> log2(block_w)` etc. - hx: Vec, - hy: Vec, - hz: Vec, + hx: Arc<[u32]>, + hy: Arc<[u32]>, + hz: Arc<[u32]>, +} + +type LayoutKey = (bool, u32, u32, PipeConfig); + +fn layout_cache() -> &'static RwLock>> { + static CACHE: OnceLock>>> = OnceLock::new(); + CACHE.get_or_init(|| RwLock::new(HashMap::new())) } impl Layout { @@ -78,13 +88,24 @@ impl Layout { /// elements over 16 B. Linear (0): rows padded to 256 bytes (addrlib /// Gfx10Lib::HwlComputeSurfaceInfoLinear), a "block" of 256 B, one row high. pub fn new(mode: u32, elem_log2: u32, cfg: PipeConfig) -> Option { + let key = (false, mode, elem_log2, cfg); + if let Some(hit) = layout_cache().read().unwrap().get(&key) { + return hit.clone(); + } + let built = Self::build_2d(mode, elem_log2, cfg); + layout_cache().write().unwrap().insert(key, built.clone()); + built + } + + fn build_2d(mode: u32, elem_log2: u32, cfg: PipeConfig) -> Option { if elem_log2 > 4 { return None; } if mode == 0 { let bw = 256 >> elem_log2; - let ox = (0..bw as u32).map(|x| x << elem_log2).collect(); - return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, ox, oy: vec![0], oz: vec![0], hx: vec![0], hy: vec![0], hz: vec![0] }); + let ox: Arc<[u32]> = (0..bw as u32).map(|x| x << elem_log2).collect::>().into(); + let z: Arc<[u32]> = Arc::from([0u32]); + return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, ox, oy: Arc::clone(&z), oz: Arc::clone(&z), hx: Arc::clone(&z), hy: Arc::clone(&z), hz: z }); } let blk = block_log2(mode)?; let bits = pattern_bits(PATTERNS, mode, elem_log2, cfg)?; @@ -99,7 +120,11 @@ impl Layout { /// each depth slice as a 2D surface. `None`: a mode 3D textures cannot have (addrlib /// Gfx10Rsrc3dSwModeMask) or no pattern. pub fn new_3d(mode: u32, elem_log2: u32, cfg: PipeConfig) -> Option { - match mode { + let key = (true, mode, elem_log2, cfg); + if let Some(hit) = layout_cache().read().unwrap().get(&key) { + return hit.clone(); + } + let built = match mode { 0 | 24 | 27 => Self::new(mode, elem_log2, cfg), 5 | 9 | 17 | 21 | 25 | 26 if elem_log2 <= 4 => { let blk = block_log2(mode)?; @@ -111,14 +136,16 @@ impl Layout { Some(Self::from_bits(mode, elem_log2, blk, &bits, (w1k + avg, h1k + avg + rest / 2, d1k + avg + u32::from(rest != 0)))) } _ => None, - } + }; + layout_cache().write().unwrap().insert(key, built.clone()); + built } /// The offset tables of a block `1 << wl` × `1 << hl` × `1 << dl` elements. fn from_bits(mode: u32, elem_log2: u32, blk: u32, bits: &[u64; 20], (wl, hl, dl): (u32, u32, u32)) -> Layout { // the in-block offset bits coordinate `c << lo` gives - let table = |n: usize, shift: u32, lo: u32| -> Vec { - (0..n as u32) + let table = |n: usize, shift: u32, lo: u32| -> Arc<[u32]> { + let v: Vec = (0..n as u32) .map(|c| { let mut off = 0u32; for (i, &b) in bits[..blk as usize].iter().enumerate() { @@ -127,11 +154,19 @@ impl Layout { } off }) - .collect() + .collect(); + v.into() }; let (bw, bh, bd) = (1usize << wl, 1usize << hl, 1usize << dl); - // the pattern masks are 16 bits: coordinates above them do not matter - let high = |l: u32, shift: u32| table(1 << (16 - l.min(16)), shift, l); + // the pattern masks are 16 bits: only allocate up to the highest actually used bit above `l` + let high = |l: u32, shift: u32| -> Arc<[u32]> { + let used_hi = bits[..blk as usize].iter().fold(0u32, |acc, &b| acc | ((((b >> shift) & 0xFFFF) as u32) >> l.min(16))); + if used_hi == 0 { + return Arc::from([0u32]); + } + let hi_bits = 32 - used_hi.leading_zeros(); + table(1usize << hi_bits, shift, l) + }; Layout { mode, elem_log2, From e61f3f7a77b385e7e704738e69396a5caad7e01c Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 21:56:04 -0300 Subject: [PATCH 11/16] pso_async: run background PSO worker threads at BELOW_NORMAL priority --- crates/xcl/src/hle/d3d12x/pso_async.rs | 85 +++++++++++++++----------- 1 file changed, 49 insertions(+), 36 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 0d203c0ca..0510307d1 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -80,6 +80,13 @@ pub fn defer_big(rest: Job) { DEFER_BIG.with(|slot| *slot.borrow_mut() = Some(rest)); } +fn lower_worker_priority() { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL}; + unsafe { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + } +} + fn big_queue() -> &'static Mutex>> { static BIG_Q: OnceLock>>> = OnceLock::new(); BIG_Q.get_or_init(|| { @@ -88,14 +95,17 @@ fn big_queue() -> &'static Mutex>> { let n = std::env::var("XCL_BIG_PSO_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(2usize).clamp(1, 4); for k in 0..n { let rx = rx.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-pso-big-{k}")).stack_size(64 << 20).spawn(move || loop { - let Ok(p) = rx.lock().unwrap().recv() else { return }; - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - if p.orphan.load(Ordering::Acquire) { - complete(&p, 0); - } else { - complete(&p, job()); + let _ = std::thread::Builder::new().name(format!("xcl-pso-big-{k}")).stack_size(64 << 20).spawn(move || { + lower_worker_priority(); + loop { + let Ok(p) = rx.lock().unwrap().recv() else { return }; + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + if p.orphan.load(Ordering::Acquire) { + complete(&p, 0); + } else { + complete(&p, job()); + } } } }); @@ -114,37 +124,40 @@ fn queue() -> &'static Mutex>> { let n = crate::gpu::recomp::dxc::compile_threads().min(16); for k in 0..n { let rx = rx.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { - let next = rx.lock().unwrap().recv(); - let Ok(p) = next else { return }; - // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - if p.orphan.load(Ordering::Acquire) { - complete(&p, 0); - } else { - IN_NORMAL_WORKER.with(|c| c.set(true)); - DEFER_BIG.with(|s| *s.borrow_mut() = None); - let real = job(); - IN_NORMAL_WORKER.with(|c| c.set(false)); - let deferred = DEFER_BIG.with(|s| s.borrow_mut().take()); - if let Some(big_job) = deferred { - if p.orphan.load(Ordering::Acquire) { - complete(&p, 0); - } else if p.waiters.load(Ordering::SeqCst) > 0 { - complete(&p, big_job()); - } else { - *p.job.lock().unwrap() = Some(big_job); - if p.waiters.load(Ordering::SeqCst) > 0 { - if let Some(j) = p.job.lock().unwrap().take() { - complete(&p, j()); - } + let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || { + lower_worker_priority(); + loop { + let next = rx.lock().unwrap().recv(); + let Ok(p) = next else { return }; + // (None: a bind took it and builds it itself) + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + if p.orphan.load(Ordering::Acquire) { + complete(&p, 0); + } else { + IN_NORMAL_WORKER.with(|c| c.set(true)); + DEFER_BIG.with(|s| *s.borrow_mut() = None); + let real = job(); + IN_NORMAL_WORKER.with(|c| c.set(false)); + let deferred = DEFER_BIG.with(|s| s.borrow_mut().take()); + if let Some(big_job) = deferred { + if p.orphan.load(Ordering::Acquire) { + complete(&p, 0); + } else if p.waiters.load(Ordering::SeqCst) > 0 { + complete(&p, big_job()); } else { - let _ = big_queue().lock().unwrap().send(p); + *p.job.lock().unwrap() = Some(big_job); + if p.waiters.load(Ordering::SeqCst) > 0 { + if let Some(j) = p.job.lock().unwrap().take() { + complete(&p, j()); + } + } else { + let _ = big_queue().lock().unwrap().send(p); + } } + } else { + complete(&p, real); } - } else { - complete(&p, real); } } } From 63de0741b4ec5f742e68831f74b4f3376a367f52 Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 22:03:18 -0300 Subject: [PATCH 12/16] bind/pso_async: skip draws on pending graphics PSOs instead of blocking the render thread --- crates/xcl/src/hle/d3d12x/bind.rs | 21 +++++++++++------ crates/xcl/src/hle/d3d12x/pso_async.rs | 32 ++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index d8df8e34a..c58d9c3fa 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -214,7 +214,10 @@ pub(super) fn note_root_changing_signature(sig: usize) { pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); + let Some(pso) = super::pso_async::resolve_indirect(with(this, |s| s.pso)) else { + count(DRAWS_SKIPPED); + return; + }; let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if !gfx && !compute { @@ -367,8 +370,13 @@ pub(super) unsafe fn emit_prepared_indexed_draw( unsafe fn graphics_bound(this: *mut c_void) -> Option { let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); let pso = with(this, |s| s.pso); - // a pipeline still being built in the background is waited for (its stand-in draws nothing) - if !super::real::is_translated_graphics(super::pso_async::resolve_wait(pso)) { + // Graphics pipelines compile asynchronously (`pso_async`): skip draws while still building + // instead of stalling the render thread (compute pipelines still wait in `dispatch`). + let Some(resolved) = super::pso_async::resolve_nonblocking(pso) else { + count(DRAWS_SKIPPED); + return None; + }; + if !super::real::is_translated_graphics(resolved) { count(DRAWS_PC); if super::present::trace_frame() { // which pipelines draw without a translation (first 12 distinct) @@ -376,11 +384,10 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option let mut g = SEEN.lock().unwrap(); if !g.contains(&pso) && g.len() < 12 { g.push(pso); - let real = super::pso_async::resolve_wait(pso); crate::xlog_info!( - "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})", + "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {resolved:#x}; pending {}, two-pass {}, RT0 {:?})", super::pso_async::is_pending(pso), - super::real::two_pass_of(real).is_some(), + super::real::two_pass_of(resolved).is_some(), super::present::rt0_resource(this as usize).map(|r| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0) })) ); } @@ -397,7 +404,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option if super::present::trace_frame() { trace_ui_draw(this, pso); } - match bind_abi(this, &list, pso, true) { + match bind_abi(this, &list, resolved, true) { Ok(()) => { count(DRAWS); Some(list) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 0510307d1..6fb0d4830 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -278,6 +278,38 @@ pub fn resolve_for_bind(pso: usize) -> usize { } } +/// Non-blocking resolve for graphics draws: returns `None` while the real pipeline is still +/// being built (triggering lazy submission if needed), or `Some(real)` once built (`Some(pso)` +/// when not managed by `pso_async` or when the build failed). +pub fn resolve_nonblocking(pso: usize) -> Option { + let Some(p) = entry(pso) else { return Some(pso) }; + let r = p.real.load(Ordering::Acquire); + if r != 0 { + return Some(r); + } + if !p.sent.swap(true, Ordering::AcqRel) { + let _ = queue().lock().unwrap().send(p.clone()); + } + if *p.done.lock().unwrap() { + Some(match p.real.load(Ordering::Acquire) { + 0 => pso, + r => r, + }) + } else { + None + } +} + +/// Resolve for `ExecuteIndirect`: waits for compute pipelines (never skips dispatches), and +/// returns `None` while a graphics pipeline is still compiling in the background. +pub fn resolve_indirect(pso: usize) -> Option { + match entry(pso) { + Some(p) if p.compute => Some(resolve_wait(pso)), + Some(_) => resolve_nonblocking(pso), + None => Some(pso), + } +} + /// The title released stand-in `pso` for good: forget it (its address may come back for /// another object) and return its real pipeline to release (0: none, or still being built – /// the worker's result is then released when it arrives). From 07dba959ed247bae935c6de85fc5a0e6f615e4e9 Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 22:08:03 -0300 Subject: [PATCH 13/16] pso_async: give bound lazy graphics PSOs a dedicated urgent worker pool --- crates/xcl/src/hle/d3d12x/pso_async.rs | 38 ++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 6fb0d4830..c1fd716e0 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -114,14 +114,40 @@ fn big_queue() -> &'static Mutex>> { }) } +/// Dedicated fast-lane workers for actually-bound lazy graphics pipelines so UI / video / +/// visible draws never queue behind speculative background compute pre-compilation. +fn urgent_queue() -> &'static Mutex>> { + static URGENT_Q: OnceLock>>> = OnceLock::new(); + URGENT_Q.get_or_init(|| { + let (tx, rx) = mpsc::channel::>(); + let rx = Arc::new(Mutex::new(rx)); + let n = crate::gpu::recomp::dxc::compile_threads().clamp(1, 2); + for k in 0..n { + let rx = rx.clone(); + let _ = std::thread::Builder::new().name(format!("xcl-pso-gfx-{k}")).stack_size(64 << 20).spawn(move || loop { + let Ok(p) = rx.lock().unwrap().recv() else { return }; + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + if p.orphan.load(Ordering::Acquire) { + complete(&p, 0); + } else { + complete(&p, job()); + } + } + }); + } + Mutex::new(tx) + }) +} + fn queue() -> &'static Mutex>> { static Q: OnceLock>>> = OnceLock::new(); Q.get_or_init(|| { let (tx, rx) = mpsc::channel::>(); let rx = Arc::new(Mutex::new(rx)); - // translation recurses deeply on big programs; DXC itself runs on its own pool. - // Cap normal background PSO workers at 16 so high-core CPUs keep cores free for title/DirectStorage threads. - let n = crate::gpu::recomp::dxc::compile_threads().min(16); + // Reserve up to 2 DXC pool slots for urgent bound graphics PSOs and title `resolve_wait` + // so speculative compute pre-compilation never starves visible draws or DXC. + let n = crate::gpu::recomp::dxc::compile_threads().saturating_sub(2).clamp(1, 8); for k in 0..n { let rx = rx.clone(); let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || { @@ -233,9 +259,9 @@ pub fn resolve(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; match p.real.load(Ordering::Acquire) { 0 => { - // a lazy one is wanted now: to the workers + // a lazy one is wanted now: straight to the urgent graphics workers if !p.sent.swap(true, Ordering::AcqRel) { - let _ = queue().lock().unwrap().send(p); + let _ = urgent_queue().lock().unwrap().send(p); } pso } @@ -288,7 +314,7 @@ pub fn resolve_nonblocking(pso: usize) -> Option { return Some(r); } if !p.sent.swap(true, Ordering::AcqRel) { - let _ = queue().lock().unwrap().send(p.clone()); + let _ = urgent_queue().lock().unwrap().send(p.clone()); } if *p.done.lock().unwrap() { Some(match p.real.load(Ordering::Acquire) { From ab843226556a93bfe41b752c6f894d811f669c44 Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 22:24:39 -0300 Subject: [PATCH 14/16] pso_async/bind: add opt-in XCL_ASYNC_COMPUTE=1 non-blocking compute PSO mode --- crates/xcl/src/hle/d3d12x/bind.rs | 5 ++- crates/xcl/src/hle/d3d12x/pso_async.rs | 58 ++++++++++++++++++-------- 2 files changed, 45 insertions(+), 18 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index c58d9c3fa..4619e97c1 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -680,7 +680,10 @@ pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: /// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); + let Some(pso) = super::pso_async::resolve_compute(with(this, |s| s.pso)) else { + count(DISPATCHES_SKIPPED); + return; + }; let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; if !super::real::is_translated_compute(pso) { // a console pipeline without a translation (including a background build that diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index c1fd716e0..8353a6e16 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -16,6 +16,8 @@ struct Pending { job: Mutex>, /// the build went to the workers (a lazy one goes on its first `resolve`) sent: std::sync::atomic::AtomicBool, + /// already promoted to `urgent_queue()` after being bound/used on a title thread + urgent: std::sync::atomic::AtomicBool, /// the real pipeline state (raw pointer), 0 while building or when building failed real: AtomicUsize, done: Mutex, @@ -169,11 +171,11 @@ fn queue() -> &'static Mutex>> { if let Some(big_job) = deferred { if p.orphan.load(Ordering::Acquire) { complete(&p, 0); - } else if p.waiters.load(Ordering::SeqCst) > 0 { + } else if p.waiters.load(Ordering::SeqCst) > 0 || p.urgent.load(Ordering::SeqCst) { complete(&p, big_job()); } else { *p.job.lock().unwrap() = Some(big_job); - if p.waiters.load(Ordering::SeqCst) > 0 { + if p.waiters.load(Ordering::SeqCst) > 0 || p.urgent.load(Ordering::SeqCst) { if let Some(j) = p.job.lock().unwrap().take() { complete(&p, j()); } @@ -224,6 +226,15 @@ pub fn lazy_compute() -> bool { *L.get_or_init(|| lazy() && std::env::var("XCL_LAZY_COMPUTE_PSO").is_ok_and(|v| v == "1")) } +/// Opt-in non-blocking compute pipelines (`XCL_ASYNC_COMPUTE=1`): when set, compute pipelines +/// still compiling in the background are promoted to the urgent pool and skipped until ready +/// instead of blocking bind / dispatch (useful to warm all shader caches without tripping a +/// title's frame watchdog). +pub fn async_compute() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| enabled() && std::env::var("XCL_ASYNC_COMPUTE").is_ok_and(|v| v == "1")) +} + /// `submit`, sent to the workers only on its first `resolve` (`lazy`). pub fn submit_lazy(standin: usize, compute: bool, job: Job) { submit_as(standin, compute, job, false); @@ -233,6 +244,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool) { let p = Arc::new(Pending { job: Mutex::new(Some(job)), sent: std::sync::atomic::AtomicBool::new(send), + urgent: std::sync::atomic::AtomicBool::new(false), real: AtomicUsize::new(0), done: Mutex::new(false), cv: Condvar::new(), @@ -254,15 +266,20 @@ fn entry(pso: usize) -> Option> { PENDING.lock().unwrap().as_ref()?.get(&pso).cloned() } +fn promote_urgent(p: &Arc) { + p.sent.store(true, Ordering::Release); + if !p.urgent.swap(true, Ordering::AcqRel) { + let _ = urgent_queue().lock().unwrap().send(p.clone()); + } +} + /// The pipeline to use for `pso` now: the real one once built, else `pso` itself. pub fn resolve(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; match p.real.load(Ordering::Acquire) { 0 => { - // a lazy one is wanted now: straight to the urgent graphics workers - if !p.sent.swap(true, Ordering::AcqRel) { - let _ = urgent_queue().lock().unwrap().send(p); - } + // an actually-bound pipeline: promote straight to the urgent workers + promote_urgent(&p); pso } r => r, @@ -295,27 +312,25 @@ pub fn resolve_wait(pso: usize) -> usize { } } -/// For binding: compute pipelines are waited for, graphics ones are not. +/// For binding: compute pipelines are waited for (unless `XCL_ASYNC_COMPUTE=1`), graphics ones are not. pub fn resolve_for_bind(pso: usize) -> usize { match entry(pso) { - Some(p) if p.compute => resolve_wait(pso), + Some(p) if p.compute && !async_compute() => resolve_wait(pso), Some(_) => resolve(pso), None => pso, } } -/// Non-blocking resolve for graphics draws: returns `None` while the real pipeline is still -/// being built (triggering lazy submission if needed), or `Some(real)` once built (`Some(pso)` -/// when not managed by `pso_async` or when the build failed). +/// Non-blocking resolve for draws (and compute dispatches under `XCL_ASYNC_COMPUTE=1`): returns +/// `None` while the real pipeline is still being built (promoting it to the urgent pool), or +/// `Some(real)` once built (`Some(pso)` when not managed by `pso_async` or when the build failed). pub fn resolve_nonblocking(pso: usize) -> Option { let Some(p) = entry(pso) else { return Some(pso) }; let r = p.real.load(Ordering::Acquire); if r != 0 { return Some(r); } - if !p.sent.swap(true, Ordering::AcqRel) { - let _ = urgent_queue().lock().unwrap().send(p.clone()); - } + promote_urgent(&p); if *p.done.lock().unwrap() { Some(match p.real.load(Ordering::Acquire) { 0 => pso, @@ -326,11 +341,20 @@ pub fn resolve_nonblocking(pso: usize) -> Option { } } -/// Resolve for `ExecuteIndirect`: waits for compute pipelines (never skips dispatches), and -/// returns `None` while a graphics pipeline is still compiling in the background. +/// Resolve for `Dispatch`: waits by default; skips while compiling when `XCL_ASYNC_COMPUTE=1`. +pub fn resolve_compute(pso: usize) -> Option { + if async_compute() { + resolve_nonblocking(pso) + } else { + Some(resolve_wait(pso)) + } +} + +/// Resolve for `ExecuteIndirect`: waits for compute pipelines (unless `XCL_ASYNC_COMPUTE=1`), +/// and returns `None` while a graphics (or async compute) pipeline is still compiling. pub fn resolve_indirect(pso: usize) -> Option { match entry(pso) { - Some(p) if p.compute => Some(resolve_wait(pso)), + Some(p) if p.compute && !async_compute() => Some(resolve_wait(pso)), Some(_) => resolve_nonblocking(pso), None => Some(pso), } From d419af8d11bcbb685319317448adb1c2f982445d Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 22:49:56 -0300 Subject: [PATCH 15/16] D3D12.X: bridge monotonic Wait64BitValueX to GPU queue.Wait/Signal fences --- crates/xcl/src/hle/d3d12x/list_x.rs | 741 +++++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 3 +- 2 files changed, 728 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 208010030..ebd9007cc 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -21,7 +21,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::mem::{transmute_copy, ManuallyDrop}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; -use std::sync::Mutex; +use std::sync::{Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; use windows::core::Interface; @@ -55,10 +55,25 @@ const TOP_TIMESTAMPS: u32 = 0xC; /// fills larger than this are not done (one pattern buffer per value, up to this size) const MAX_FILL: u64 = 256 << 20; /// Bounded wait timeout for Wait32BitValueX / Wait64BitValueX so an unsatisfied wait never hangs. +/// Overridable via `XCL_WAIT_TIMEOUT_MS` for diagnostics. const WAIT_TIMEOUT: Duration = Duration::from_secs(2); +/// Watchdog timeout for GPU wait-before-signal when a recorded producer list is never submitted. +const GPU_WAIT_WATCHDOG_TIMEOUT: Duration = Duration::from_millis(1000); /// Cap on tracked per-list written UMA ranges (for same-list write-then-wait detection). const MAX_WRITTEN_RANGES: usize = 256; +fn wait_timeout() -> Duration { + static T: OnceLock = OnceLock::new(); + *T.get_or_init(|| { + std::env::var("XCL_WAIT_TIMEOUT_MS") + .ok() + .and_then(|v| v.parse::().ok()) + .filter(|&ms| ms > 0) + .map(Duration::from_millis) + .unwrap_or(WAIT_TIMEOUT) + }) +} + fn once(counter: &AtomicU64, n: u64) -> bool { counter.fetch_add(1, Ordering::Relaxed) < n } @@ -165,6 +180,9 @@ struct PendingWait { comparison: u32, value: u64, mask: u64, + /// True if this list already recorded a `Write64BitValue*` before this wait (potential + /// intra-list fork-join where hoisting a GPU wait before list submission could deadlock). + after_write64: bool, } fn compare_u64(op: u32, lhs: u64, rhs: u64) -> Option { @@ -544,6 +562,10 @@ struct ListState { /// Sparse-window `(va, bytes)` ranges written by memory ops (`Write32/64`, `Fill*`, /// `CopyMemoryToMemoryX`, timestamps) to copy back to the CPU view after execution. sparse_writes: Vec<(usize, usize)>, + /// Non-timestamp 64-bit `(va, value)` writes recorded by `Write64BitValue{Bottom,Top}OfPipeX` + /// so `ExecuteCommandLists` / `KickoffX` can signal per-address GPU fences for cross-queue + /// `Wait64BitValueX` without blocking the submitter thread on the CPU. + write64_signals: Vec<(u64, u64)>, /// External memory waits recorded on this list pending_waits: Vec, /// bottom-of-pipe writes into memory the GPU does not see (`cpu_writes`) @@ -586,6 +608,21 @@ impl ListState { std::mem::take(&mut self.sparse_writes) } + fn push_write64_signal(&mut self, va: u64, value: u64) { + if self.write64_signals.is_empty() { + WRITE64_SIGNAL_LISTS.fetch_add(1, Ordering::AcqRel); + } + self.write64_signals.push((va, value)); + } + + fn clear_write64_signals(&mut self) -> Vec<(u64, u64)> { + if self.write64_signals.is_empty() { + return Vec::new(); + } + WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); + std::mem::take(&mut self.write64_signals) + } + fn has_prior_write(&self, va: u64, size: u64) -> bool { let end = va.saturating_add(size); self.written_ranges.iter().any(|&(s, e)| va < e && s < end) @@ -619,6 +656,8 @@ static LIVE_QUEUES: Mutex> = Mutex::new(Vec::new()); static PENDING_WAIT_LISTS: AtomicUsize = AtomicUsize::new(0); /// Number of lists with recorded sparse-window memory writes (fast-path guard for post-execute readback). static SPARSE_WRITE_LISTS: AtomicUsize = AtomicUsize::new(0); +/// Number of lists with recorded non-timestamp `Write64BitValue*` signals (fast-path guard). +static WRITE64_SIGNAL_LISTS: AtomicUsize = AtomicUsize::new(0); /// Set once any list uses `RSSetDepthBiasX` (fast-path guard for Draw* hooks). static DEPTH_BIAS_USED: AtomicBool = AtomicBool::new(false); /// Set once any list uses `SetPredicationBufferX` (fast-path guard for Close/Reset hooks). @@ -694,6 +733,9 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C if !old.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } + if !old.write64_signals.is_empty() { + WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); + } } m.insert(key, ListState { allocator: alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); old @@ -724,6 +766,9 @@ pub(super) fn on_release(list: usize) { if !old.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } + if !old.write64_signals.is_empty() { + WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); + } } } @@ -875,20 +920,411 @@ fn note_write(list: usize, va: u64, size: u64) { LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size); } -unsafe fn wait_all(waits: &[PendingWait]) { +// --------------------------------------------------------------------------------------- +// per-address GPU fence bridge for monotonic 64-bit Write64BitValue* -> Wait64BitValueX +// --------------------------------------------------------------------------------------- + +/// Recent `Write32/64BitValue*` call for timeout diagnostics. +#[derive(Clone, Copy)] +struct WriteTraceEntry { + va: u64, + value: u64, + flags: u32, + list_type: i32, + what: &'static str, +} + +struct WriteTraceRing { + entries: [Option; 32], + next: usize, + total: u64, +} + +impl WriteTraceRing { + const fn new() -> Self { + Self { entries: [None; 32], next: 0, total: 0 } + } + + fn push(&mut self, e: WriteTraceEntry) { + self.entries[self.next] = Some(e); + self.next = (self.next + 1) % self.entries.len(); + self.total += 1; + } + + fn snapshot(&self) -> (u64, Vec) { + let mut out = Vec::with_capacity(self.entries.len()); + for i in 0..self.entries.len() { + let idx = (self.next + i) % self.entries.len(); + if let Some(e) = self.entries[idx] { + out.push(e); + } + } + (self.total, out) + } +} + +static WRITE_TRACE: Mutex = Mutex::new(WriteTraceRing::new()); + +fn record_write_trace(list: *mut c_void, va: u64, value: u64, flags: u32, what: &'static str) { + let ty = LISTS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(list as usize))) + .and_then(|s| s.list_type) + .map_or(-1, |t| t.0); + WRITE_TRACE.lock().unwrap().push(WriteTraceEntry { va, value, flags, list_type: ty, what }); +} + +/// Per-address GPU fence state bridging `Write64BitValue{Bottom,Top}OfPipeX` to cross-queue +/// `Wait64BitValueX` (`GREATER_EQUAL`, full 64-bit mask). +#[derive(Default)] +struct SyncCell { + fence: Option, + /// Raw `ID3D12Device` pointer owning `fence`. + device: usize, + /// Highest non-zero value recorded in a `Write64BitValue*` targeting this VA. + recorded_max: u64, + /// Command list type of the most recent recording advancing `recorded_max`. + recorded_list_type: Option, + /// Last queue the recording list was executed on (if known), used to prevent same-queue + /// wait-before-signal self-deadlocks. + recorded_last_queue: Option, + /// Highest value submitted via `queue.Signal(&fence, v)`. + submitted_max: u64, + /// Queue that issued the latest `Signal`. + submitted_queue: Option, + /// Set once a non-monotonic write (`value <= submitted_max`) is observed at this VA, disabling + /// GPU-fence bridging and falling back to CPU polling. + non_monotonic: bool, + /// Pending GPU `queue.Wait(&fence, v)` values whose producer had not been submitted yet. + unsubmitted_waits: Vec<(u64, Instant)>, +} + +// SAFETY: `ID3D12Fence` is a free-threaded COM object in D3D12. +unsafe impl Send for SyncCell {} + +static SYNC_CELLS: Mutex>> = Mutex::new(None); +static UNSUBMITTED_GPU_WAITS: AtomicUsize = AtomicUsize::new(0); +static SYNC_WATCHDOG_WAKE: OnceLock<(Mutex<()>, Condvar)> = OnceLock::new(); + +fn wake_sync_watchdog() { + let pair = SYNC_WATCHDOG_WAKE.get_or_init(|| { + let pair = (Mutex::new(()), Condvar::new()); + let _ = std::thread::Builder::new().name("xcl-sync-watchdog".into()).spawn(|| loop { + let (lock, cv) = SYNC_WATCHDOG_WAKE.get().unwrap(); + let guard = lock.lock().unwrap(); + if UNSUBMITTED_GPU_WAITS.load(Ordering::Acquire) == 0 { + let _g = cv.wait(guard).unwrap(); + continue; + } + let _ = cv.wait_timeout(guard, Duration::from_millis(50)).unwrap(); + let expired = { + let mut g = SYNC_CELLS.lock().unwrap(); + let mut out: Vec<(u64, u64, ID3D12Fence, u64, u64)> = Vec::new(); + if let Some(m) = g.as_mut() { + for (&va, cell) in m.iter_mut() { + if cell.unsubmitted_waits.is_empty() { + continue; + } + let mut max_exp = 0u64; + let before = cell.unsubmitted_waits.len(); + cell.unsubmitted_waits.retain(|&(val, armed_at)| { + if cell.submitted_max >= val { + return false; + } + if armed_at.elapsed() >= GPU_WAIT_WATCHDOG_TIMEOUT { + max_exp = max_exp.max(val); + return false; + } + true + }); + let removed = before - cell.unsubmitted_waits.len(); + if removed > 0 { + UNSUBMITTED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); + } + if max_exp > 0 { + if let Some(ref f) = cell.fence { + out.push((va, max_exp, f.clone(), cell.recorded_max, cell.submitted_max)); + } + } + } + } + out + }; + for (va, val, fence, rec, sub) in expired { + unsafe { + let _ = fence.Signal(val); + } + crate::xlog_warn!( + "D3D12.X: GPU wait-before-signal at {va:#x} >= {val:#x} was not submitted within {} ms (recorded_max={rec:#x}, submitted_max={sub:#x}) – released on CPU to prevent GPU hang", + GPU_WAIT_WATCHDOG_TIMEOUT.as_millis() + ); + } + }); + pair + }); + pair.1.notify_one(); +} + +unsafe fn queue_device_and_type(queue: *mut c_void) -> Option<(ID3D12Device, usize, D3D12_COMMAND_LIST_TYPE)> { + if queue.is_null() { + return None; + } + let q = ID3D12CommandQueue::from_raw_borrowed(&queue)?; + let ty = q.GetDesc().Type; + let mut dev: Option = None; + q.GetDevice(&mut dev).ok()?; + let dev = dev?; + let raw = dev.as_raw() as usize; + Some((dev, raw, ty)) +} + +unsafe fn ensure_cell_fence(va: u64, dev: &ID3D12Device, dev_raw: usize) -> Option { + { + let g = SYNC_CELLS.lock().unwrap(); + if let Some(cell) = g.as_ref().and_then(|m| m.get(&va)) { + if cell.non_monotonic { + return None; + } + if let Some(ref f) = cell.fence { + return (cell.device == dev_raw).then(|| f.clone()); + } + } + } + let created: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let mut g = SYNC_CELLS.lock().unwrap(); + let cell = g.get_or_insert_with(HashMap::new).entry(va).or_default(); + if cell.non_monotonic { + return None; + } + if let Some(ref existing) = cell.fence { + return (cell.device == dev_raw).then(|| existing.clone()); + } + cell.fence = Some(created.clone()); + cell.device = dev_raw; + Some(created) +} + +fn note_write64_recorded(list: *mut c_void, va: u64, value: u64) { + if value == 0 || !va.is_multiple_of(8) { + return; + } + let (lty, last_q) = { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + s.push_write64_signal(va, value); + (s.list_type, s.last_queue) + }; + let mut g = SYNC_CELLS.lock().unwrap(); + let cell = g.get_or_insert_with(HashMap::new).entry(va).or_default(); + if cell.non_monotonic { + return; + } + if value <= cell.submitted_max { + cell.non_monotonic = true; + cell.fence = None; + return; + } + if value > cell.recorded_max { + cell.recorded_max = value; + cell.recorded_list_type = lty; + cell.recorded_last_queue = last_q; + } +} + +unsafe fn signal_write64_pairs(queue: *mut c_void, pairs: &[(u64, u64)]) { + if queue.is_null() || pairs.is_empty() { + return; + } + let Some((dev, dev_raw, _ty)) = queue_device_and_type(queue) else { return }; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + // Coalesce per-VA max value within this batch. + let mut max_by_va: Vec<(u64, u64)> = Vec::with_capacity(pairs.len()); + for &(va, val) in pairs { + if val == 0 { + continue; + } + if let Some(entry) = max_by_va.iter_mut().find(|e| e.0 == va) { + entry.1 = entry.1.max(val); + } else { + max_by_va.push((va, val)); + } + } + for (va, val) in max_by_va { + let skip = { + let g = SYNC_CELLS.lock().unwrap(); + g.as_ref().and_then(|m| m.get(&va)).is_some_and(|c| c.non_monotonic || c.submitted_max >= val) + }; + if skip { + continue; + } + let Some(fence) = ensure_cell_fence(va, &dev, dev_raw) else { continue }; + let should_signal = { + let mut g = SYNC_CELLS.lock().unwrap(); + let cell = g.get_or_insert_with(HashMap::new).entry(va).or_default(); + if cell.non_monotonic || cell.device != dev_raw || val <= cell.submitted_max { + false + } else { + cell.submitted_max = val; + cell.submitted_queue = Some(queue as usize); + if val > cell.recorded_max { + cell.recorded_max = val; + } + let before = cell.unsubmitted_waits.len(); + cell.unsubmitted_waits.retain(|&(w_val, _)| w_val > val); + let removed = before - cell.unsubmitted_waits.len(); + if removed > 0 { + UNSUBMITTED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); + } + true + } + }; + if should_signal { + if let Err(e) = q.Signal(&fence, val) { + crate::xlog_warn!("D3D12.X: Write64 fence Signal({va:#x}, {val:#x}) failed ({e}) – signalling on CPU"); + let _ = fence.Signal(val); + } + } + } +} + +/// After `queue.ExecuteCommandLists(lists)`: signal per-address GPU fences for any +/// `Write64BitValue{Bottom,Top}OfPipeX` commands recorded on `lists`. +pub(super) unsafe fn signal_write64_fences(queue: *mut c_void, lists: &[*mut c_void]) { + if WRITE64_SIGNAL_LISTS.load(Ordering::Acquire) == 0 || queue.is_null() || lists.is_empty() { + return; + } + let pairs: Vec<(u64, u64)> = { + let g = LISTS.lock().unwrap(); + let Some(m) = g.as_ref() else { return }; + let mut out = Vec::new(); + for &l in lists { + if let Some(s) = m.get(&(l as usize)) { + out.extend_from_slice(&s.write64_signals); + } + } + out + }; + signal_write64_pairs(queue, &pairs); +} + +/// Attempt to satisfy a `Wait64BitValueX(GREATER_EQUAL, u64::MAX)` on the GPU via +/// `queue.Wait(&fence, w.value)` instead of blocking the submission thread on the CPU. +/// Returns `true` if the wait was handled on the GPU (or already satisfied). +unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait) -> bool { + if queue.is_null() + || w.width != 8 + || w.comparison != D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32 + || w.mask != u64::MAX + || w.value == 0 + || w.after_write64 + { + return false; + } + let Some((dev, dev_raw, q_ty)) = queue_device_and_type(queue) else { return false }; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return false }; + + let eligible = { + let g = SYNC_CELLS.lock().unwrap(); + g.as_ref().and_then(|m| m.get(&w.va)).is_some_and(|c| { + !c.non_monotonic + && c.recorded_max >= w.value + && !(c.submitted_max < w.value && c.recorded_last_queue == Some(queue as usize)) + }) + }; + if !eligible { + return false; + } + let Some(fence) = ensure_cell_fence(w.va, &dev, dev_raw) else { return false }; + + let (unsubmitted, rec_ty) = { + let mut g = SYNC_CELLS.lock().unwrap(); + let Some(cell) = g.as_mut().and_then(|m| m.get_mut(&w.va)) else { return false }; + if cell.non_monotonic || cell.device != dev_raw || cell.recorded_max < w.value { + return false; + } + if fence.GetCompletedValue() >= w.value { + // Fence already reached `w.value`: only trust it if CPU memory agrees (not reset/reused). + return w.is_satisfied(); + } + let unsubmitted = cell.submitted_max < w.value; + if unsubmitted { + if cell.recorded_last_queue == Some(queue as usize) { + return false; + } + cell.unsubmitted_waits.push((w.value, Instant::now())); + UNSUBMITTED_GPU_WAITS.fetch_add(1, Ordering::AcqRel); + } + (unsubmitted, cell.recorded_list_type) + }; + + if let Err(e) = q.Wait(&fence, w.value) { + if unsubmitted { + let mut g = SYNC_CELLS.lock().unwrap(); + if let Some(cell) = g.as_mut().and_then(|m| m.get_mut(&w.va)) { + if let Some(pos) = cell.unsubmitted_waits.iter().rposition(|&(v, _)| v == w.value) { + cell.unsubmitted_waits.remove(pos); + UNSUBMITTED_GPU_WAITS.fetch_sub(1, Ordering::AcqRel); + } + } + } + crate::xlog_warn!("D3D12.X: Wait64 GPU queue.Wait({:#x}, {:#x}) failed ({e}) – falling back to CPU wait", w.va, w.value); + return false; + } + + if unsubmitted { + wake_sync_watchdog(); + static LOGGED: AtomicU64 = AtomicU64::new(0); + if once(&LOGGED, 8) { + crate::xlog_info!( + "D3D12.X: Wait64BitValueX at {:#x} >= {:#x} bridged to GPU queue.Wait (queue type {}, producer type {:?}; wait-before-signal)", + w.va, + w.value, + q_ty.0, + rec_ty.map(|t| t.0) + ); + } + } + true +} + +unsafe fn wait_all_on(queue: *mut c_void, waits: &[PendingWait]) { static TIMEOUTS: AtomicU64 = AtomicU64::new(0); + static RING_DUMPED: AtomicU64 = AtomicU64::new(0); + let timeout = wait_timeout(); + let q_ty = queue_device_and_type(queue).map_or(-1, |(_, _, t)| t.0); for w in waits { - if !w.wait_until_satisfied(WAIT_TIMEOUT) && once(&TIMEOUTS, 40) { + if w.is_satisfied() || try_gpu_wait(queue, w) { + continue; + } + if !w.wait_until_satisfied(timeout) && once(&TIMEOUTS, 40) { + let cell_diag = { + let g = SYNC_CELLS.lock().unwrap(); + g.as_ref().and_then(|m| m.get(&w.va)).map(|c| (c.recorded_max, c.submitted_max, c.non_monotonic, c.recorded_list_type.map(|t| t.0))) + }; crate::xlog_warn!( - "D3D12.X: Wait{}BitValueX timed out after {} ms at {:#x} (op {}, want {:#x}, mask {:#x}; memory holds {:x?})", + "D3D12.X: Wait{}BitValueX timed out after {} ms at {:#x} (op {}, want {:#x}, mask {:#x}; memory holds {:x?}; queue_type={}, after_write64={}, sync={cell_diag:x?})", w.width * 8, - WAIT_TIMEOUT.as_millis(), + timeout.as_millis(), w.va, w.comparison, w.value, w.mask, - w.read_value() + w.read_value(), + q_ty, + w.after_write64 ); + if once(&RING_DUMPED, 2) { + let (total, entries) = WRITE_TRACE.lock().unwrap().snapshot(); + let summary: Vec = entries + .iter() + .rev() + .take(16) + .map(|e| format!("{}({:#x}={:#x},f={:#x},ty={})", e.what, e.va, e.value, e.flags, e.list_type)) + .collect(); + crate::xlog_warn!("D3D12.X: recent Write32/64 calls ({total} total): [{}]", summary.join(", ")); + } } } } @@ -930,7 +1366,9 @@ pub(super) unsafe fn cpu_writes_after(queue: *mut c_void, lists: &[*mut c_void]) /// 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])) { +/// When `queue` is non-null, monotonic 64-bit waits backed by a recorded `Write64BitValue*` are +/// bridged to GPU-side `queue.Wait` without blocking the submitter thread on the CPU. +pub(super) unsafe fn execute_with_waits_on(queue: *mut c_void, lists: &[*mut c_void], mut submit: impl FnMut(&[*mut c_void])) { if lists.is_empty() || PENDING_WAIT_LISTS.load(Ordering::Acquire) == 0 { submit(lists); return; @@ -955,7 +1393,7 @@ pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], mut submit: impl if i > start { submit(&lists[start..i]); } - wait_all(waits); + wait_all_on(queue, waits); start = i; } if start < lists.len() { @@ -963,6 +1401,11 @@ pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], mut submit: impl } } +#[cfg(test)] +pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], submit: impl FnMut(&[*mut c_void])) { + execute_with_waits_on(std::ptr::null_mut(), lists, submit); +} + // --------------------------------------------------------------------------------------- // memory copy / fill / immediate write / timestamp // --------------------------------------------------------------------------------------- @@ -1219,16 +1662,19 @@ unsafe fn timestamp(list: *mut c_void, va: u64, what: &str) { /// /// # Safety /// `this` must be a valid adopted `ID3D12GraphicsCommandList` pointer. -pub unsafe extern "system" fn write32_bottom_x(this: *mut c_void, va: u64, value: u32, _flush: u32, _flags: u32) { +pub unsafe extern "system" fn write32_bottom_x(this: *mut c_void, va: u64, value: u32, _flush: u32, flags: u32) { + record_write_trace(this, va, value as u64, flags, "W32B"); write(this, va, &[value], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, "Write32BitValueBottomOfPipeX"); } /// command list #70 Write64BitValueBottomOfPipeX(address, value, flush, flags) pub(super) unsafe extern "system" fn write64_bottom_x(this: *mut c_void, va: u64, value: u64, _flush: u32, flags: u32) { const W: &str = "Write64BitValueBottomOfPipeX"; + record_write_trace(this, va, value, flags, "W64B"); if flags & BOTTOM_TIMESTAMPS != 0 { return timestamp(this, va, W); } + note_write64_recorded(this, va, value); write(this, va, &[value as u32, (value >> 32) as u32], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, W); } @@ -1263,7 +1709,8 @@ unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, va if s.has_prior_write(va, n) { return; } - s.push_wait(PendingWait { va, width, comparison, value, mask }); + let after_write64 = !s.write64_signals.is_empty(); + s.push_wait(PendingWait { va, width, comparison, value, mask, after_write64 }); } /// command list #71 Wait32BitValueX(address, comparison, value, mask, flags) @@ -1281,21 +1728,25 @@ pub(super) unsafe extern "system" fn wait64_x(this: *mut c_void, va: u64, compar } /// command list #88 Write32BitValueTopOfPipeX(address, value, flags) -pub(super) unsafe extern "system" fn write32_top_x(this: *mut c_void, va: u64, value: u32, _flags: u32) { +pub(super) unsafe extern "system" fn write32_top_x(this: *mut c_void, va: u64, value: u32, flags: u32) { + record_write_trace(this, va, value as u64, flags, "W32T"); write(this, va, &[value], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN, "Write32BitValueTopOfPipeX"); } /// command list #89 Write64BitValueTopOfPipeX(address, value, flags) pub(super) unsafe extern "system" fn write64_top_x(this: *mut c_void, va: u64, value: u64, flags: u32) { const W: &str = "Write64BitValueTopOfPipeX"; + record_write_trace(this, va, value, flags, "W64T"); if flags & TOP_TIMESTAMPS != 0 { return timestamp(this, va, W); } + note_write64_recorded(this, va, value); write(this, va, &[value as u32, (value >> 32) as u32], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN, W); } /// command list #90 Write32BitValueBottomOfShaderX(address, value, stage) -pub(super) unsafe extern "system" fn write32_bottom_of_shader_x(this: *mut c_void, va: u64, value: u32, _stage: u32) { +pub(super) unsafe extern "system" fn write32_bottom_of_shader_x(this: *mut c_void, va: u64, value: u32, stage: u32) { + record_write_trace(this, va, value as u64, stage, "W32S"); write(this, va, &[value], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, "Write32BitValueBottomOfShaderX"); } @@ -1532,13 +1983,14 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { std::mem::take(&mut s.pending_waits) }; let sparse_writes = s.clear_sparse_writes(); + let write64_signals = s.clear_write64_signals(); 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, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, waits, (sparse_writes, write64_signals, cpu_writes)) }; - let (sparse_writes, cpu_writes) = sparse_writes; + let (sparse_writes, write64_signals, 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 { @@ -1560,13 +2012,14 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let q_raw = queue as *mut c_void; super::title_textures::refresh(q_raw); if !waits.is_empty() { - wait_all(&waits); + wait_all_on(q_raw, &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()); + signal_write64_pairs(q_raw, &write64_signals); // what ran is in the textures' states; the list records anew after its Reset below super::title_textures::submitted(&one); super::title_textures::list_reset(this as usize); @@ -2135,6 +2588,7 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz s.occlusion = Occlusion::default(); s.written_ranges.clear(); s.clear_sparse_writes(); + s.clear_write64_signals(); s.clear_waits(); s.cpu_writes.clear(); s.predication = None; @@ -2712,6 +3166,7 @@ mod tests { comparison: D3D12_COMPARISON_FUNC_EQUAL.0 as u32, value: 0x0000_005A, mask: 0x0000_00FF, + after_write64: false, }; unsafe { assert!(!w32.is_satisfied()); @@ -2731,6 +3186,7 @@ mod tests { comparison: D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, value: 0x0000_0002_0000_0000, mask: u64::MAX, + after_write64: false, }; unsafe { assert!(!w64.is_satisfied()); @@ -2775,6 +3231,7 @@ mod tests { comparison: D3D12_COMPARISON_FUNC_EQUAL.0 as u32, value: 42, mask: u32::MAX as u64, + after_write64: false, }); } @@ -3714,4 +4171,258 @@ mod tests { on_release(list_ptr as usize); } } + + #[test] + fn write_buffer_immediate_on_open_existing_heap_visible_to_cpu() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + 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 dev3: ID3D12Device3 = dev.cast().unwrap(); + + let mem = VirtualAlloc(std::ptr::null(), 0x1_0000, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE); + assert!(!mem.is_null()); + let base = mem as usize; + + let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(mem).expect("OpenExistingHeapFromAddress"); + let buf_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 0x1_0000, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, + ..Default::default() + }; + let mut buf: Option = None; + dev.CreatePlacedResource(&heap, 0, &buf_desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).unwrap(); + let buf = buf.unwrap(); + let gpu_va = buf.GetGPUVirtualAddress(); + + // Upload buffer holding known u64 for CopyBufferRegion comparison + let up_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut up: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &up_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut up, + ) + .unwrap(); + let up = up.unwrap(); + let mut up_ptr = std::ptr::null_mut(); + up.Map(0, None, Some(&mut up_ptr)).unwrap(); + *(up_ptr as *mut u64) = 0xCAFE_BABE_DEAD_BEEFu64; + up.Unmap(0, None); + + // Readback buffer to inspect what the GPU itself sees at +0x100, +0x180, +0x200 + let mut rb: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &up_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .unwrap(); + let rb = rb.unwrap(); + + // 1. DIRECT queue: WriteBufferImmediate at +0x100 and CopyBufferRegion at +0x200 + let dq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let da: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let dl: ID3D12GraphicsCommandList2 = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &da, None).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + let make_barrier = |before, after| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: ManuallyDrop::new(Some(buf.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }; + + dl.ResourceBarrier(&[make_barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + let p_direct = [ + D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: gpu_va + 0x100, Value: 0x0000_0677 }, + D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: gpu_va + 0x104, Value: 0x0000_0000 }, + ]; + let m_direct = [D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT; 2]; + dl.WriteBufferImmediate(2, p_direct.as_ptr(), Some(m_direct.as_ptr())); + dl.CopyBufferRegion(&buf, 0x200, &up, 0, 8); + dl.ResourceBarrier(&[make_barrier(D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); + dl.Close().unwrap(); + let dcl: ID3D12CommandList = dl.cast().unwrap(); + dq.ExecuteCommandLists(&[Some(dcl)]); + dq.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 2000).unwrap(); + + // 2. COMPUTE queue: WriteBufferImmediate at +0x180 + let cq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let ca: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let cl2: ID3D12GraphicsCommandList2 = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &ca, None).unwrap(); + cl2.ResourceBarrier(&[make_barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + let p_comp = [ + D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: gpu_va + 0x180, Value: 0x0000_0677 }, + D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: gpu_va + 0x184, Value: 0x1122_3344 }, + ]; + let m_comp = [D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT; 2]; + cl2.WriteBufferImmediate(2, p_comp.as_ptr(), Some(m_comp.as_ptr())); + cl2.ResourceBarrier(&[make_barrier(D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); + cl2.Close().unwrap(); + let ccl: ID3D12CommandList = cl2.cast().unwrap(); + cq.ExecuteCommandLists(&[Some(ccl)]); + cq.Signal(&fence, 2).unwrap(); + crate::gpu::fence::wait(&fence, 2, &dev, None, 2000).unwrap(); + + // 3. GPU readback of +0x100, +0x180, +0x200 + let da2: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let dl2: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &da2, None).unwrap(); + dl2.CopyBufferRegion(&rb, 0, &buf, 0x100, 8); + dl2.CopyBufferRegion(&rb, 8, &buf, 0x180, 8); + dl2.CopyBufferRegion(&rb, 16, &buf, 0x200, 8); + dl2.Close().unwrap(); + let dcl2: ID3D12CommandList = dl2.cast().unwrap(); + dq.ExecuteCommandLists(&[Some(dcl2)]); + dq.Signal(&fence, 3).unwrap(); + crate::gpu::fence::wait(&fence, 3, &dev, None, 2000).unwrap(); + + let cpu_direct = *((base + 0x100) as *const u64); + let cpu_comp = *((base + 0x180) as *const u64); + let cpu_copy = *((base + 0x200) as *const u64); + let mut rb_ptr = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut rb_ptr)).unwrap(); + let gpu_direct = *(rb_ptr as *const u64); + let gpu_comp = *((rb_ptr as *const u64).add(1)); + let gpu_copy = *((rb_ptr as *const u64).add(2)); + rb.Unmap(0, None); + + drop(dl); + drop(dl2); + drop(cl2); + drop(buf); + drop(heap); + VirtualFree(mem, 0, MEM_RELEASE); + + assert_eq!(cpu_direct, 0x677, "DIRECT WriteBufferImmediate must be visible to CPU (gpu={gpu_direct:#x})"); + assert_eq!(cpu_comp, 0x1122_3344_0000_0677, "COMPUTE WriteBufferImmediate must be visible to CPU (gpu={gpu_comp:#x})"); + assert_eq!(cpu_copy, 0xCAFE_BABE_DEAD_BEEF, "DIRECT CopyBufferRegion must be visible to CPU (gpu={gpu_copy:#x})"); + } + } + + /// Submitting a DIRECT list with `Wait64BitValueX(va, >=, 0x677)` BEFORE submitting the + /// COMPUTE list that recorded `Write64BitValueBottomOfPipeX(va, 0x677)` must bridge via + /// GPU `queue.Wait`/`queue.Signal` without blocking the submitter thread for `WAIT_TIMEOUT`. + #[test] + fn cross_queue_wait64_before_signal_does_not_deadlock_submit_thread() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let 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 dq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let cq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let da: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let ca: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let dl: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &da, None).unwrap(); + let cl: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &ca, None).unwrap(); + let done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + let cell = Box::new(AtomicU64::new(0)); + let va = &*cell as *const AtomicU64 as u64; + + let dl_ptr = dl.as_raw(); + let cl_ptr = cl.as_raw(); + on_create(dl_ptr, da.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + on_create(cl_ptr, ca.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + // Worker threads record both lists: COMPUTE writes `va = 0x677`, DIRECT waits `va >= 0x677`. + note_write64_recorded(cl_ptr, va, 0x677); + wait64_x(dl_ptr, va, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, 0x677, 1, 0); + dl.Close().unwrap(); + cl.Close().unwrap(); + + // Single submitter thread submits DIRECT (consumer) FIRST — before COMPUTE (producer)! + let t0 = Instant::now(); + let dcl: ID3D12CommandList = dl.cast().unwrap(); + execute_with_waits_on(dq.as_raw(), &[dl_ptr], |chunk| { + assert_eq!(chunk, &[dl_ptr]); + dq.ExecuteCommandLists(&[Some(dcl.clone())]); + signal_write64_fences(dq.as_raw(), chunk); + }); + let direct_submit_ms = t0.elapsed().as_millis(); + assert!( + direct_submit_ms < 500, + "wait-before-signal must bridge to GPU queue.Wait without blocking CPU (took {direct_submit_ms} ms)" + ); + dq.Signal(&done_fence, 1).unwrap(); + + // Now submit COMPUTE (producer) which signals the per-VA GPU fence. + let ccl: ID3D12CommandList = cl.cast().unwrap(); + execute_with_waits_on(cq.as_raw(), &[cl_ptr], |chunk| { + assert_eq!(chunk, &[cl_ptr]); + cq.ExecuteCommandLists(&[Some(ccl.clone())]); + signal_write64_fences(cq.as_raw(), chunk); + }); + + // DIRECT queue must now unblock and finish promptly on the GPU. + crate::gpu::fence::wait(&done_fence, 1, &dev, None, 2000).expect("DIRECT queue must complete after COMPUTE signals per-VA fence"); + + on_release(dl_ptr as usize); + on_release(cl_ptr as usize); + SYNC_CELLS.lock().unwrap().as_mut().map(|m| m.remove(&va)); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 35c7ce54f..e96ab3834 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4779,8 +4779,9 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis .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| { + super::list_x::execute_with_waits_on(this, &mapped, |chunk| { f(this, chunk.len() as u32, chunk.as_ptr()); + super::list_x::signal_write64_fences(this, chunk); super::list_x::readback_sparse_writes(this, chunk); super::list_x::cpu_writes_after(this, chunk); }); From 4ff33f02789f6f6b9748567e45366568f60f13c9 Mon Sep 17 00:00:00 2001 From: gsucristo Date: Mon, 23 Nov 2026 23:00:22 -0300 Subject: [PATCH 16/16] D3D12.X: detect cross-queue Wait64 cycles, bypass same-queue FIFO, and watch GPU completion --- crates/xcl/src/hle/d3d12x/list_x.rs | 403 +++++++++++++++++++++++----- 1 file changed, 329 insertions(+), 74 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ebd9007cc..31545c1c0 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -976,6 +976,15 @@ fn record_write_trace(list: *mut c_void, va: u64, value: u64, flags: u32, what: WRITE_TRACE.lock().unwrap().push(WriteTraceEntry { va, value, flags, list_type: ty, what }); } +/// Active GPU `queue.Wait(&fence, val)` tracked for cycle detection and deadlock watchdog. +#[derive(Clone, Copy)] +struct ArmedGpuWait { + val: u64, + waiting_queue: usize, + waiting_queue_ty: i32, + armed_at: Instant, +} + /// Per-address GPU fence state bridging `Write64BitValue{Bottom,Top}OfPipeX` to cross-queue /// `Wait64BitValueX` (`GREATER_EQUAL`, full 64-bit mask). #[derive(Default)] @@ -997,67 +1006,102 @@ struct SyncCell { /// Set once a non-monotonic write (`value <= submitted_max`) is observed at this VA, disabling /// GPU-fence bridging and falling back to CPU polling. non_monotonic: bool, - /// Pending GPU `queue.Wait(&fence, v)` values whose producer had not been submitted yet. - unsubmitted_waits: Vec<(u64, Instant)>, + /// All active GPU `queue.Wait(&fence, v)` calls on this cell not yet confirmed completed on GPU. + armed_waits: Vec, } // SAFETY: `ID3D12Fence` is a free-threaded COM object in D3D12. unsafe impl Send for SyncCell {} static SYNC_CELLS: Mutex>> = Mutex::new(None); -static UNSUBMITTED_GPU_WAITS: AtomicUsize = AtomicUsize::new(0); +static ARMED_GPU_WAITS: AtomicUsize = AtomicUsize::new(0); static SYNC_WATCHDOG_WAKE: OnceLock<(Mutex<()>, Condvar)> = OnceLock::new(); +/// Remove any `armed_waits` already satisfied on the GPU (or if the device was removed). +/// Returns the fence's current completed value (or `0` if no fence exists yet). +unsafe fn prune_completed_waits(cell: &mut SyncCell) -> u64 { + let Some(ref fence) = cell.fence else { return 0 }; + let completed = fence.GetCompletedValue(); + if cell.armed_waits.is_empty() { + return completed; + } + let before = cell.armed_waits.len(); + if completed == u64::MAX { + cell.armed_waits.clear(); + } else { + cell.armed_waits.retain(|aw| aw.val > completed); + } + let removed = before - cell.armed_waits.len(); + if removed > 0 { + ARMED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); + } + completed +} + fn wake_sync_watchdog() { let pair = SYNC_WATCHDOG_WAKE.get_or_init(|| { let pair = (Mutex::new(()), Condvar::new()); let _ = std::thread::Builder::new().name("xcl-sync-watchdog".into()).spawn(|| loop { let (lock, cv) = SYNC_WATCHDOG_WAKE.get().unwrap(); let guard = lock.lock().unwrap(); - if UNSUBMITTED_GPU_WAITS.load(Ordering::Acquire) == 0 { + if ARMED_GPU_WAITS.load(Ordering::Acquire) == 0 { let _g = cv.wait(guard).unwrap(); continue; } let _ = cv.wait_timeout(guard, Duration::from_millis(50)).unwrap(); let expired = { let mut g = SYNC_CELLS.lock().unwrap(); - let mut out: Vec<(u64, u64, ID3D12Fence, u64, u64)> = Vec::new(); + let mut out: Vec<(u64, u64, ID3D12Fence, i32, Option, u64, u64, u64)> = Vec::new(); if let Some(m) = g.as_mut() { for (&va, cell) in m.iter_mut() { - if cell.unsubmitted_waits.is_empty() { + if cell.armed_waits.is_empty() { + continue; + } + let completed = unsafe { prune_completed_waits(cell) }; + if cell.armed_waits.is_empty() || completed == u64::MAX { continue; } let mut max_exp = 0u64; - let before = cell.unsubmitted_waits.len(); - cell.unsubmitted_waits.retain(|&(val, armed_at)| { - if cell.submitted_max >= val { - return false; - } - if armed_at.elapsed() >= GPU_WAIT_WATCHDOG_TIMEOUT { - max_exp = max_exp.max(val); + let mut waiter_ty = -1i32; + let before = cell.armed_waits.len(); + cell.armed_waits.retain(|aw| { + if aw.armed_at.elapsed() >= GPU_WAIT_WATCHDOG_TIMEOUT { + if aw.val >= max_exp { + max_exp = aw.val; + waiter_ty = aw.waiting_queue_ty; + } return false; } true }); - let removed = before - cell.unsubmitted_waits.len(); + let removed = before - cell.armed_waits.len(); if removed > 0 { - UNSUBMITTED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); + ARMED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); } if max_exp > 0 { if let Some(ref f) = cell.fence { - out.push((va, max_exp, f.clone(), cell.recorded_max, cell.submitted_max)); + out.push(( + va, + max_exp, + f.clone(), + waiter_ty, + cell.recorded_list_type.map(|t| t.0), + cell.recorded_max, + cell.submitted_max, + completed, + )); } } } } out }; - for (va, val, fence, rec, sub) in expired { + for (va, val, fence, waiter_ty, prod_ty, rec, sub, done) in expired { unsafe { let _ = fence.Signal(val); } crate::xlog_warn!( - "D3D12.X: GPU wait-before-signal at {va:#x} >= {val:#x} was not submitted within {} ms (recorded_max={rec:#x}, submitted_max={sub:#x}) – released on CPU to prevent GPU hang", + "D3D12.X: GPU queue.Wait at {va:#x} >= {val:#x} did not complete within {} ms (waiter_ty={waiter_ty}, prod_ty={prod_ty:?}, recorded={rec:#x}, submitted={sub:#x}, completed={done:#x}) – released on CPU to prevent GPU hang", GPU_WAIT_WATCHDOG_TIMEOUT.as_millis() ); } @@ -1067,6 +1111,10 @@ fn wake_sync_watchdog() { pair.1.notify_one(); } +fn live_queues_of_type(ty: D3D12_COMMAND_LIST_TYPE) -> usize { + LIVE_QUEUES.lock().unwrap().iter().filter(|q| q.ty == ty).count() +} + unsafe fn queue_device_and_type(queue: *mut c_void) -> Option<(ID3D12Device, usize, D3D12_COMMAND_LIST_TYPE)> { if queue.is_null() { return None; @@ -1163,6 +1211,7 @@ unsafe fn signal_write64_pairs(queue: *mut c_void, pairs: &[(u64, u64)]) { let should_signal = { let mut g = SYNC_CELLS.lock().unwrap(); let cell = g.get_or_insert_with(HashMap::new).entry(va).or_default(); + prune_completed_waits(cell); if cell.non_monotonic || cell.device != dev_raw || val <= cell.submitted_max { false } else { @@ -1171,12 +1220,6 @@ unsafe fn signal_write64_pairs(queue: *mut c_void, pairs: &[(u64, u64)]) { if val > cell.recorded_max { cell.recorded_max = val; } - let before = cell.unsubmitted_waits.len(); - cell.unsubmitted_waits.retain(|&(w_val, _)| w_val > val); - let removed = before - cell.unsubmitted_waits.len(); - if removed > 0 { - UNSUBMITTED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); - } true } }; @@ -1209,95 +1252,213 @@ pub(super) unsafe fn signal_write64_fences(queue: *mut c_void, lists: &[*mut c_v signal_write64_pairs(queue, &pairs); } +#[derive(Clone, Copy, PartialEq, Eq)] +enum GpuWaitOutcome { + /// Satisfied on GPU (via `queue.Wait` or same-queue FIFO order) — no CPU wait needed. + Handled, + /// Skipping this wait avoids a guaranteed GPU/CPU cycle (logged once). + CycleSkip, + /// Not eligible for GPU fence bridging — fall back to bounded CPU poll. + FallbackCpu, +} + +/// Detect whether emitting `q_raw.Wait` on `prod_queue` / `prod_ty` would close a 2-queue cycle +/// (the producer queue is already waiting on an unsubmitted write from `q_raw` or `list_writes`). +unsafe fn would_create_gpu_cycle( + map: &mut HashMap, + q_raw: usize, + q_ty: i32, + prod_queue: Option, + prod_ty: Option, + list_writes: &[(u64, u64)], +) -> bool { + for (&other_va, other_cell) in map.iter_mut() { + if other_cell.armed_waits.is_empty() { + continue; + } + let completed = prune_completed_waits(other_cell); + if other_cell.armed_waits.is_empty() || completed == u64::MAX { + continue; + } + let other_prod_q = other_cell.submitted_queue.or(other_cell.recorded_last_queue); + let other_prod_ty = other_cell.recorded_list_type.map(|t| t.0); + for aw in &other_cell.armed_waits { + let waiter_is_our_producer = match (prod_queue, prod_ty) { + (Some(pq), _) => aw.waiting_queue == pq, + (None, Some(pt)) => aw.waiting_queue_ty == pt, + (None, None) => false, + }; + if !waiter_is_our_producer { + continue; + } + let written_by_this_list = list_writes.iter().any(|&(wva, wv)| wva == other_va && wv >= aw.val); + let unsubmitted_from_us = other_cell.submitted_max < aw.val + && (other_prod_q == Some(q_raw) || (other_prod_q.is_none() && other_prod_ty == Some(q_ty))); + if written_by_this_list || unsubmitted_from_us { + return true; + } + } + } + false +} + /// Attempt to satisfy a `Wait64BitValueX(GREATER_EQUAL, u64::MAX)` on the GPU via -/// `queue.Wait(&fence, w.value)` instead of blocking the submission thread on the CPU. -/// Returns `true` if the wait was handled on the GPU (or already satisfied). -unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait) -> bool { +/// `queue.Wait(&fence, w.value)` (or same-queue FIFO ordering) instead of blocking the +/// submission thread on the CPU. +unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, u64)]) -> GpuWaitOutcome { if queue.is_null() || w.width != 8 || w.comparison != D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32 || w.mask != u64::MAX || w.value == 0 - || w.after_write64 { - return false; + return GpuWaitOutcome::FallbackCpu; } - let Some((dev, dev_raw, q_ty)) = queue_device_and_type(queue) else { return false }; - let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return false }; + let Some((dev, dev_raw, q_ty)) = queue_device_and_type(queue) else { return GpuWaitOutcome::FallbackCpu }; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return GpuWaitOutcome::FallbackCpu }; + let q_raw = queue as usize; + let same_ty_queues = live_queues_of_type(q_ty); - let eligible = { + // Fast path: check eligibility and same-queue FIFO bypass before allocating a fence. + let pre = { let g = SYNC_CELLS.lock().unwrap(); - g.as_ref().and_then(|m| m.get(&w.va)).is_some_and(|c| { - !c.non_monotonic - && c.recorded_max >= w.value - && !(c.submitted_max < w.value && c.recorded_last_queue == Some(queue as usize)) + g.as_ref().and_then(|m| m.get(&w.va)).map(|c| { + ( + c.non_monotonic, + c.recorded_max, + c.submitted_max, + c.submitted_queue, + c.recorded_last_queue, + c.recorded_list_type, + ) }) }; - if !eligible { - return false; + let Some((non_mono, rec_max, sub_max, sub_q, rec_q, rec_ty)) = pre else { + return GpuWaitOutcome::FallbackCpu; + }; + if non_mono || rec_max < w.value { + return GpuWaitOutcome::FallbackCpu; + } + // Producer already submitted earlier on THIS EXACT queue: D3D12 FIFO executes it strictly + // before this list without needing a CPU wait or redundant queue.Wait. + if sub_max >= w.value && sub_q == Some(q_raw) { + return GpuWaitOutcome::Handled; + } + // Same-queue wait-before-signal guard: never block a queue waiting on an unsubmitted write + // destined for that same queue. + if sub_max < w.value && (rec_q == Some(q_raw) || (rec_q.is_none() && rec_ty == Some(q_ty) && same_ty_queues <= 1)) { + static SAME_Q_WARN: AtomicU64 = AtomicU64::new(0); + if once(&SAME_Q_WARN, 8) { + crate::xlog_warn!( + "D3D12.X: Wait64BitValueX at {:#x} >= {:#x} skipped to avoid same-queue wait-before-signal deadlock (queue_type={}, recorded={rec_max:#x}, submitted={sub_max:#x})", + w.va, + w.value, + q_ty.0 + ); + } + return GpuWaitOutcome::CycleSkip; } - let Some(fence) = ensure_cell_fence(w.va, &dev, dev_raw) else { return false }; - let (unsubmitted, rec_ty) = { + let Some(fence) = ensure_cell_fence(w.va, &dev, dev_raw) else { return GpuWaitOutcome::FallbackCpu }; + + let (unsubmitted, final_rec_ty) = { let mut g = SYNC_CELLS.lock().unwrap(); - let Some(cell) = g.as_mut().and_then(|m| m.get_mut(&w.va)) else { return false }; - if cell.non_monotonic || cell.device != dev_raw || cell.recorded_max < w.value { - return false; - } - if fence.GetCompletedValue() >= w.value { - // Fence already reached `w.value`: only trust it if CPU memory agrees (not reset/reused). - return w.is_satisfied(); - } - let unsubmitted = cell.submitted_max < w.value; - if unsubmitted { - if cell.recorded_last_queue == Some(queue as usize) { - return false; + let Some(map) = g.as_mut() else { return GpuWaitOutcome::FallbackCpu }; + let (cell_ok, cell_sub_max, cell_sub_q, cell_rec_q, cell_rec_ty) = match map.get_mut(&w.va) { + Some(cell) => { + if cell.non_monotonic || cell.device != dev_raw || cell.recorded_max < w.value { + (false, 0, None, None, None) + } else { + let completed = prune_completed_waits(cell); + if completed >= w.value { + // Fence already reached `w.value`: trust it if CPU memory agrees (not reset). + return if w.is_satisfied() { GpuWaitOutcome::Handled } else { GpuWaitOutcome::FallbackCpu }; + } + if cell.submitted_max >= w.value && cell.submitted_queue == Some(q_raw) { + return GpuWaitOutcome::Handled; + } + (true, cell.submitted_max, cell.submitted_queue, cell.recorded_last_queue, cell.recorded_list_type) + } } - cell.unsubmitted_waits.push((w.value, Instant::now())); - UNSUBMITTED_GPU_WAITS.fetch_add(1, Ordering::AcqRel); + None => (false, 0, None, None, None), + }; + if !cell_ok { + return GpuWaitOutcome::FallbackCpu; + } + let unsubmitted = cell_sub_max < w.value; + if unsubmitted && (cell_rec_q == Some(q_raw) || (cell_rec_q.is_none() && cell_rec_ty == Some(q_ty) && same_ty_queues <= 1)) { + return GpuWaitOutcome::CycleSkip; + } + let prod_q = cell_sub_q.or(cell_rec_q); + let prod_ty = cell_rec_ty.map(|t| t.0); + if would_create_gpu_cycle(map, q_raw, q_ty.0, prod_q, prod_ty, list_writes) { + static CYCLE_WARN: AtomicU64 = AtomicU64::new(0); + if once(&CYCLE_WARN, 16) { + crate::xlog_warn!( + "D3D12.X: Wait64BitValueX at {:#x} >= {:#x} skipped to break cross-queue cycle (queue_type={}, prod_ty={prod_ty:?}, after_write64={}, list_writes={})", + w.va, + w.value, + q_ty.0, + w.after_write64, + list_writes.len() + ); + } + return GpuWaitOutcome::CycleSkip; + } + if let Some(cell) = map.get_mut(&w.va) { + cell.armed_waits.push(ArmedGpuWait { + val: w.value, + waiting_queue: q_raw, + waiting_queue_ty: q_ty.0, + armed_at: Instant::now(), + }); + ARMED_GPU_WAITS.fetch_add(1, Ordering::AcqRel); } - (unsubmitted, cell.recorded_list_type) + (unsubmitted, cell_rec_ty) }; if let Err(e) = q.Wait(&fence, w.value) { - if unsubmitted { - let mut g = SYNC_CELLS.lock().unwrap(); - if let Some(cell) = g.as_mut().and_then(|m| m.get_mut(&w.va)) { - if let Some(pos) = cell.unsubmitted_waits.iter().rposition(|&(v, _)| v == w.value) { - cell.unsubmitted_waits.remove(pos); - UNSUBMITTED_GPU_WAITS.fetch_sub(1, Ordering::AcqRel); - } + let mut g = SYNC_CELLS.lock().unwrap(); + if let Some(cell) = g.as_mut().and_then(|m| m.get_mut(&w.va)) { + if let Some(pos) = cell.armed_waits.iter().rposition(|aw| aw.val == w.value && aw.waiting_queue == q_raw) { + cell.armed_waits.remove(pos); + ARMED_GPU_WAITS.fetch_sub(1, Ordering::AcqRel); } } crate::xlog_warn!("D3D12.X: Wait64 GPU queue.Wait({:#x}, {:#x}) failed ({e}) – falling back to CPU wait", w.va, w.value); - return false; + return GpuWaitOutcome::FallbackCpu; } + wake_sync_watchdog(); if unsubmitted { - wake_sync_watchdog(); static LOGGED: AtomicU64 = AtomicU64::new(0); if once(&LOGGED, 8) { crate::xlog_info!( - "D3D12.X: Wait64BitValueX at {:#x} >= {:#x} bridged to GPU queue.Wait (queue type {}, producer type {:?}; wait-before-signal)", + "D3D12.X: Wait64BitValueX at {:#x} >= {:#x} bridged to GPU queue.Wait (queue type {}, producer type {:?}; wait-before-signal, after_write64={})", w.va, w.value, q_ty.0, - rec_ty.map(|t| t.0) + final_rec_ty.map(|t| t.0), + w.after_write64 ); } } - true + GpuWaitOutcome::Handled } -unsafe fn wait_all_on(queue: *mut c_void, waits: &[PendingWait]) { +unsafe fn wait_all_on(queue: *mut c_void, waits: &[PendingWait], list_writes: &[(u64, u64)]) { static TIMEOUTS: AtomicU64 = AtomicU64::new(0); static RING_DUMPED: AtomicU64 = AtomicU64::new(0); let timeout = wait_timeout(); let q_ty = queue_device_and_type(queue).map_or(-1, |(_, _, t)| t.0); for w in waits { - if w.is_satisfied() || try_gpu_wait(queue, w) { + if w.is_satisfied() { continue; } + match try_gpu_wait(queue, w, list_writes) { + GpuWaitOutcome::Handled | GpuWaitOutcome::CycleSkip => continue, + GpuWaitOutcome::FallbackCpu => {} + } if !w.wait_until_satisfied(timeout) && once(&TIMEOUTS, 40) { let cell_diag = { let g = SYNC_CELLS.lock().unwrap(); @@ -1373,27 +1534,27 @@ pub(super) unsafe fn execute_with_waits_on(queue: *mut c_void, lists: &[*mut c_v submit(lists); return; } - let per_list: Vec> = { + let per_list: Vec<(Vec, Vec<(u64, u64)>)> = { 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()) + .map(|s| (s.pending_waits.clone(), s.write64_signals.clone())) .unwrap_or_default() }) .collect() }; let mut start = 0usize; - for (i, waits) in per_list.iter().enumerate() { + for (i, (waits, list_writes)) in per_list.iter().enumerate() { if waits.is_empty() || waits.iter().all(|w| w.is_satisfied()) { continue; } if i > start { submit(&lists[start..i]); } - wait_all_on(queue, waits); + wait_all_on(queue, waits, list_writes); start = i; } if start < lists.len() { @@ -2012,7 +2173,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let q_raw = queue as *mut c_void; super::title_textures::refresh(q_raw); if !waits.is_empty() { - wait_all_on(q_raw, &waits); + wait_all_on(q_raw, &waits, &write64_signals); } type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); @@ -4425,4 +4586,98 @@ mod tests { SYNC_CELLS.lock().unwrap().as_mut().map(|m| m.remove(&va)); } } + + /// Cross-queue cycle detection (`DIRECT` waits on `COMPUTE` while `COMPUTE` is already + /// blocked on an unsubmitted write from `DIRECT`) and same-queue FIFO bypass must both + /// complete immediately without stalling CPU or hanging GPU. + #[test] + fn cross_queue_cycle_and_same_queue_fifo_do_not_deadlock() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let 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 dq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let cq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let da: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let ca1: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let ca2: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let dl: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &da, None).unwrap(); + let cl1: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &ca1, None).unwrap(); + let cl2: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &ca2, None).unwrap(); + let done_d: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done_c: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + let cell_a = Box::new(AtomicU64::new(0)); + let cell_b = Box::new(AtomicU64::new(0)); + let va_a = &*cell_a as *const AtomicU64 as u64; + let va_b = &*cell_b as *const AtomicU64 as u64; + + let (dl_ptr, cl1_ptr, cl2_ptr) = (dl.as_raw(), cl1.as_raw(), cl2.as_raw()); + on_create(dl_ptr, da.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + on_create(cl1_ptr, ca1.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + on_create(cl2_ptr, ca2.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + // Fork-join cycle: DIRECT writes A then waits on B; COMPUTE1 waits on A then writes B; + // COMPUTE2 waits on B (same-queue FIFO after COMPUTE1) after writing something else. + note_write64_recorded(dl_ptr, va_a, 0x702); + wait64_x(dl_ptr, va_b, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, 0x702, 1, 0); + wait64_x(cl1_ptr, va_a, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, 0x702, 1, 0); + note_write64_recorded(cl1_ptr, va_b, 0x702); + wait64_x(cl2_ptr, va_b, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, 0x702, 1, 0); + dl.Close().unwrap(); + cl1.Close().unwrap(); + cl2.Close().unwrap(); + + let t0 = Instant::now(); + let ccl1: ID3D12CommandList = cl1.cast().unwrap(); + execute_with_waits_on(cq.as_raw(), &[cl1_ptr], |chunk| { + cq.ExecuteCommandLists(&[Some(ccl1.clone())]); + signal_write64_fences(cq.as_raw(), chunk); + }); + // Same-queue FIFO bypass: cl2 waits on va_b already submitted on cq. + let ccl2: ID3D12CommandList = cl2.cast().unwrap(); + execute_with_waits_on(cq.as_raw(), &[cl2_ptr], |chunk| { + cq.ExecuteCommandLists(&[Some(ccl2.clone())]); + signal_write64_fences(cq.as_raw(), chunk); + }); + cq.Signal(&done_c, 1).unwrap(); + + // Cycle breaking: dl writes va_a (which cq is blocked on) and waits on va_b (from cq). + // Must detect the cycle, skip hoisting va_b ahead of dl, submit dl immediately, and unblock BOTH queues! + let dcl: ID3D12CommandList = dl.cast().unwrap(); + execute_with_waits_on(dq.as_raw(), &[dl_ptr], |chunk| { + dq.ExecuteCommandLists(&[Some(dcl.clone())]); + signal_write64_fences(dq.as_raw(), chunk); + }); + dq.Signal(&done_d, 1).unwrap(); + + assert!(t0.elapsed().as_millis() < 500, "submits must not stall CPU (took {} ms)", t0.elapsed().as_millis()); + crate::gpu::fence::wait(&done_d, 1, &dev, None, 2000).expect("DIRECT must finish without GPU deadlock"); + crate::gpu::fence::wait(&done_c, 1, &dev, None, 2000).expect("COMPUTE must finish once DIRECT signals A"); + + on_release(dl_ptr as usize); + on_release(cl1_ptr as usize); + on_release(cl2_ptr as usize); + if let Some(m) = SYNC_CELLS.lock().unwrap().as_mut() { + m.remove(&va_a); + m.remove(&va_b); + } + } + } }