diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..ba07c73958 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -10,6 +10,7 @@ //! signalled on every queue with work on it; the batch goes once all of them have passed it. use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Mutex; use std::time::{Duration, Instant}; @@ -92,6 +93,175 @@ pub fn enabled() -> bool { *ON.get_or_init(|| !std::env::var("XCL_LATE_RELEASE").is_ok_and(|v| v.trim() == "0")) } +/// Force the one-time read of `XCL_LATE_RELEASE` on the calling (Wine) thread. +/// +/// D3DMetal calls `Release` on adopted resources from a native thread of its own, which has +/// no Wine TEB. Reading the environment there for the first time never returns. Calling +/// this from `real::adopt` -- on the Wine thread that creates the object -- makes sure the +/// `OnceLock` inside `enabled()` is already set before the host's thread can reach it. +pub fn init() { + let _ = enabled(); + // Record whether this is Wine on macOS so is_foreign_thread can check without a Win32 call. + if !MACOS_HOST.load(Ordering::Relaxed) { + MACOS_HOST.store(crate::util::mac_host(), Ordering::Relaxed); + } +} + +// --- Foreign-thread detection and deferred release queue --- +// +// A host driver (D3DMetal on macOS) may call Release on adopted resources from a thread +// of its own that has no Wine TEB. Mutex, env-var reads, and most Win32 calls hang or +// crash there. When `is_foreign_thread()` is true, the release work is deferred to a +// Wine thread through an atomic ring buffer. + +/// Set by `init()` on a Wine thread: Wine on a macOS host, where D3DMetal has threads of its +/// own. On Windows and on Wine on Linux it stays false, so the foreign-thread path is off and +/// `is_foreign_thread()` returns false unconditionally. +static MACOS_HOST: AtomicBool = AtomicBool::new(false); + +/// Boundary between Wine/Rosetta 2 stacks and macOS native stacks. +/// +/// Measured on an M5 Pro (CrossOver 26.3, Rosetta 2): +/// Wine threads (test thread, 5 spawned std::threads): 0x0180ea9f .. 0x0220fb37 +/// D3DMetal threads (spy callbacks during ExecuteCommandLists): 0x7ff2063df667 .. 0x7ff2066c3677 +/// +/// Wine under Rosetta 2 runs in the emulated address space; thread stacks are in the low +/// hundreds of megabytes. macOS native stacks are near the top of the 47-bit user range. +/// The gap is over 100 TB. A threshold at 0x7000_0000_0000 (112 TB) is well above any +/// Wine thread and well below any observed D3DMetal thread, with tens of TB of margin on +/// each side. The check only runs on a macOS host (`MACOS_HOST`): on Linux a Wine thread's +/// stack may sit in that range, and every Release from it would take the deferred path. +/// +/// The TEB pointer (`gs:[0x30]`) is not used to tell the threads apart: reading it on a +/// D3DMetal thread hangs (measured), and the stack pointer needs no memory access at all. +const NATIVE_STACK_BOUNDARY: usize = 0x7000_0000_0000; + +#[cfg(not(test))] +pub(super) fn is_foreign_thread() -> bool { + if !MACOS_HOST.load(Ordering::Relaxed) { + return false; + } + let local = 0u8; + let sp = &local as *const u8 as usize; + sp >= NATIVE_STACK_BOUNDARY +} + +/// Test version: a thread-local flag overrides the detection so unit tests can exercise +/// the foreign path on a normal Wine thread. +#[cfg(test)] +pub(super) fn is_foreign_thread() -> bool { + if FORCE_FOREIGN.load(Ordering::Relaxed) != 0 { + return true; + } + if !MACOS_HOST.load(Ordering::Relaxed) { + return false; + } + let local = 0u8; + let sp = &local as *const u8 as usize; + sp >= NATIVE_STACK_BOUNDARY +} + +#[cfg(test)] +static FORCE_FOREIGN: AtomicUsize = AtomicUsize::new(0); + +/// Ring buffer for releases deferred from a foreign thread. +/// +/// Each slot holds a resource pointer whose Release is kept for a Wine thread. 0 means the +/// slot is empty. Every Release on a foreign thread goes through here, and a full ring leaks +/// the reference, so it is sized for a title's loading screens rather than the 2 Release +/// calls per ExecuteCommandLists the probes show: 16,384 slots, 128 KiB. +const DEFERRED_CAP: usize = 16_384; + +struct Ring { + slots: [AtomicUsize; DEFERRED_CAP], + /// next slot a producer (foreign thread) claims + head: AtomicUsize, + /// next slot the consumer (a Wine thread) takes + tail: AtomicUsize, + /// set while one thread takes entries off the ring: there is one consumer at a time + draining: AtomicBool, +} + +impl Ring { + const fn new() -> Self { + Ring { + slots: [const { AtomicUsize::new(0) }; DEFERRED_CAP], + head: AtomicUsize::new(0), + tail: AtomicUsize::new(0), + draining: AtomicBool::new(false), + } + } + + /// Push a deferred Release. Returns false if the ring is full (the caller keeps the + /// reference). Only atomics: no locks, no allocation. + fn push(&self, res: usize) -> bool { + loop { + let head = self.head.load(Ordering::Relaxed); + let next = (head + 1) % DEFERRED_CAP; + if next == self.tail.load(Ordering::Acquire) { + return false; + } + // Claim this slot. D3DMetal serialises its submit callbacks (one foreign producer), + // but CAS is correct if that ever changes. + if self.head.compare_exchange_weak(head, next, Ordering::AcqRel, Ordering::Relaxed).is_ok() { + self.slots[head].store(res, Ordering::Release); + return true; + } + } + } + + /// Move every written entry off the ring into `out`, oldest first. Returns false without + /// taking anything when another thread is taking entries already (it takes these too, or + /// the next drain does). + /// + /// The slot is emptied before the tail moves past it. A producer can claim a slot only + /// once the tail is past it, so it always finds the slot empty and its entry is never + /// erased. With one consumer, a slot that is still 0 at the tail is one a producer has + /// claimed and not written yet: the drain stops there and the next one carries on. + fn take(&self, out: &mut Vec) -> bool { + if self.draining.swap(true, Ordering::Acquire) { + return false; + } + loop { + let tail = self.tail.load(Ordering::Relaxed); + if tail == self.head.load(Ordering::Acquire) { + break; // empty + } + let value = self.slots[tail].swap(0, Ordering::Acquire); + if value == 0 { + break; // claimed, not written yet + } + self.tail.store((tail + 1) % DEFERRED_CAP, Ordering::Release); + out.push(value); + } + self.draining.store(false, Ordering::Release); + true + } +} + +static DEFERRED: Ring = Ring::new(); + +/// Releases that could not fit in the ring. The reference is kept: the object and XCL's +/// bookkeeping entry for it stay until the process ends. +pub(super) static DEFERRED_OVERFLOW: AtomicUsize = AtomicUsize::new(0); + +/// Defer a Release from a foreign thread to a Wine thread. False when the ring is full (the +/// caller keeps the reference and increments `DEFERRED_OVERFLOW`). +pub(super) fn defer_release(res: usize) -> bool { + DEFERRED.push(res) +} + +/// Drain the deferred ring buffer. Each entry is a Release a foreign thread kept for a Wine +/// thread; it runs here through the full `res_release` path (cleanup, late-release hold). +pub unsafe fn drain_deferred() { + let mut work = Vec::new(); + DEFERRED.take(&mut work); + // Released outside the ring: res_release drains again, and these are already off it. + for res in work { + super::real::res_release(res as *mut c_void); + } +} + /// how long a last `Release` itself waits for queues with nothing to do to say so const IDLE_WAIT: Duration = Duration::from_micros(300); @@ -117,7 +287,12 @@ pub unsafe fn hold(res: usize) { THREAD.call_once(|| { let _ = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop { std::thread::sleep(TICK); + unsafe { drain_deferred() }; unsafe { drain_known(false) }; + let overflow = DEFERRED_OVERFLOW.swap(0, Ordering::Relaxed); + if overflow > 0 { + crate::xlog_warn!("D3D12.X: {overflow} deferred release(s) dropped (ring full, references leaked)"); + } }); }); } @@ -208,4 +383,135 @@ mod tests { assert_eq!(unsafe { held.drain(&[], false) }, vec![0x1000]); assert!(held.is_empty()); } + + /// A Wine thread (the test thread) is not foreign: `under_wine` is false on Windows CI + /// and the SP is below the boundary on macOS Wine. + #[test] + fn wine_thread_is_not_foreign() { + assert!(!is_foreign_thread(), "the test thread must not be classified as foreign"); + } + + /// Spawned std::threads are not foreign either (their stacks may be at different + /// addresses, but they are Wine threads with valid TEBs). + #[test] + fn spawned_threads_are_not_foreign() { + let handles: Vec<_> = (0..8).map(|_| { + std::thread::spawn(|| is_foreign_thread()) + }).collect(); + for (i, h) in handles.into_iter().enumerate() { + assert!(!h.join().unwrap(), "spawned thread {i} classified as foreign"); + } + } + + /// With FORCE_FOREIGN set, the detection reports the thread as foreign even though + /// it has a TEB. This exercises the test hook. + #[test] + fn force_foreign_flag_overrides_detection() { + FORCE_FOREIGN.store(1, Ordering::Relaxed); + assert!(is_foreign_thread(), "FORCE_FOREIGN should make it report foreign"); + FORCE_FOREIGN.store(0, Ordering::Relaxed); + assert!(!is_foreign_thread(), "back to normal"); + } + + /// A ring of the test's own: the process-wide one is drained by every `res_release`, which + /// would release the made-up pointers these tests push. + fn empty_ring() -> std::sync::Arc { + std::sync::Arc::new(Ring::new()) + } + + /// Entries come off the ring once each and in order, across the wrap-around: a slot + /// written again after a drain keeps its new entry. + #[test] + fn deferred_ring_round_trips_across_the_wrap() { + let ring = empty_ring(); + for round in 0..3usize { + let want: Vec = (1..DEFERRED_CAP).map(|i| round * DEFERRED_CAP + i).collect(); + for &v in &want { + assert!(ring.push(v), "round {round}: defer_release failed at {v}"); + } + let mut got = Vec::new(); + assert!(ring.take(&mut got)); + assert_eq!(got, want, "round {round}"); + } + } + + /// One producer filling the ring while several threads drain it: every entry comes off + /// exactly once. Producers keep reusing slots right behind the consumer (the ring is + /// small next to the count), which is where an entry written into a slot the consumer + /// had not finished with would be lost. + #[test] + fn deferred_ring_concurrent_producer_and_drains() { + let ring = empty_ring(); + const N: usize = 200_000; + let done = std::sync::Arc::new(AtomicBool::new(false)); + let drains: Vec<_> = (0..4).map(|_| { + let (done, ring) = (done.clone(), ring.clone()); + std::thread::spawn(move || { + let mut got = Vec::new(); + loop { + let finished = done.load(Ordering::Acquire); + ring.take(&mut got); + if finished && ring.tail.load(Ordering::Acquire) == ring.head.load(Ordering::Acquire) { + return got; + } + } + }) + }).collect(); + for v in 1..=N { + while !ring.push(v) { + std::hint::spin_loop(); + } + } + done.store(true, Ordering::Release); + let mut got: Vec = drains.into_iter().flat_map(|h| h.join().unwrap()).collect(); + let taken = got.len(); + got.sort_unstable(); + got.dedup(); + assert_eq!(taken, N, "entries taken more than once or lost"); + assert_eq!(got, (1..=N).collect::>(), "each entry must come off exactly once"); + } + + /// While one thread takes entries, another drain returns at once and takes none. + #[test] + fn deferred_ring_has_one_consumer_at_a_time() { + let ring = empty_ring(); + assert!(ring.push(0x1234)); + ring.draining.store(true, Ordering::Relaxed); + let mut got = Vec::new(); + assert!(!ring.take(&mut got)); + assert!(got.is_empty()); + ring.draining.store(false, Ordering::Relaxed); + assert!(ring.take(&mut got)); + assert_eq!(got, vec![0x1234]); + } + + /// A claimed slot that is not written yet stops the drain there, and the next drain + /// takes it once it is written. + #[test] + fn deferred_ring_stops_at_an_unwritten_slot() { + let ring = empty_ring(); + let head = ring.head.load(Ordering::Relaxed); + ring.head.store((head + 1) % DEFERRED_CAP, Ordering::Release); // claimed, slot still 0 + assert!(ring.push(0x2222)); + let mut got = Vec::new(); + assert!(ring.take(&mut got)); + assert!(got.is_empty(), "nothing past the unwritten slot"); + ring.slots[head].store(0x1111, Ordering::Release); + assert!(ring.take(&mut got)); + assert_eq!(got, vec![0x1111, 0x2222]); + } + + /// When the ring is full, `defer_release` returns false instead of spinning. + #[test] + fn deferred_ring_overflow_returns_false() { + let ring = empty_ring(); + // capacity is DEFERRED_CAP - 1 usable slots + for i in 0..(DEFERRED_CAP - 1) { + assert!(ring.push(0x1000 + i), "should succeed at {i}"); + } + assert!(!ring.push(0xdead), "should return false when full"); + let mut got = Vec::new(); + assert!(ring.take(&mut got)); + assert_eq!(got.len(), DEFERRED_CAP - 1); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 574f582d86..c90ca133db 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -721,6 +721,10 @@ pub unsafe fn adopt(obj: *mut c_void, kind: Kind) { if is_ext(v) { return; } + // Read the setting `res_release` needs here, on the thread adopting the object: D3DMetal + // releases the resources of an executed list on a thread of its own, which has no Wine TEB, + // and reading the environment there for the first time never returns. + super::late_release::init(); let ext = class_for(obj, v, kind); *(obj as *mut usize) = ext; } @@ -1652,8 +1656,20 @@ unsafe extern "system" fn res_unmap(this: *mut c_void, sub: u32, range: *const c f(this, sub, range) } -unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { +/// The Release override for adopted resources. Public so `late_release::drain_deferred` +/// can run the final Release of a deferred resource through the normal path. +pub(super) unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + + // A thread the host driver created (D3DMetal on macOS) must not take locks or call + // Win32 here. Its Release is deferred to a Wine thread. + if super::late_release::is_foreign_thread() { + return foreign_release(this, f); + } + + // On a normal (Wine) thread, drain any releases a foreign thread deferred. + super::late_release::drain_deferred(); + // The last reference: kept until the queues are past the work in flight (`late_release`). // (Two last-but-one releases at once can miss each other here; the object then goes at // once, as before.) @@ -1672,32 +1688,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { f(this) }; if n == 0 { - if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() { - s.remove(&(this as usize)); - } - if let Some(s) = SPARSE_READBACK.lock().unwrap().as_mut() { - s.remove(&(this as usize)); - } - if let Some(s) = RESERVED.lock().unwrap().as_mut() { - s.remove(&(this as usize)); - } - if let Some(m) = BUFFER_DELTA.lock().unwrap().as_mut() { - m.remove(&(this as usize)); - } - if let Some(m) = TITLE_ADDRESS.lock().unwrap().as_mut() { - m.remove(&(this as usize)); - } - super::sparse::forget_buffer(this as usize); - super::vram::forget(this as usize); - super::title_textures::forget(this as usize); - let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); - if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { - if u.is_sparse(p) { - super::sparse::free(p); - } else { - u.free(p); - } - } + release_cleanup(this as usize); } if held { super::late_release::hold(this as usize); @@ -1711,6 +1702,56 @@ pub(super) fn standin_released(pso: usize) { super::pso_async::release(super::pso_async::released(pso)); } +/// Release on a thread XCL did not create. The caller's Release never runs here: it goes to +/// a Wine thread through the ring buffer, which runs it through `res_release`. Deciding here +/// whether it is the last one (AddRef returning 2) would not be safe: a Release on another +/// thread between that check and ours can still take the count to 0 on this thread. +/// +/// The returned count is what the caller's Release would leave if nothing else changed. The +/// AddRef and its Release cannot take the count to 0: the caller's reference is still held. +unsafe fn foreign_release(this: *mut c_void, f: unsafe extern "system" fn(*mut c_void) -> u32) -> u32 { + let add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); + let after_add = add(this); + f(this); + if !super::late_release::defer_release(this as usize) { + // Ring full: keep the reference (the object leaks, but no hang or corruption). + use std::sync::atomic::Ordering; + super::late_release::DEFERRED_OVERFLOW.fetch_add(1, Ordering::Relaxed); + } + after_add.saturating_sub(2) +} + +/// Remove a released resource from XCL's tracking maps. Runs on a Wine thread only +/// (from `res_release` or from `late_release::drain_deferred`). +pub(super) unsafe fn release_cleanup(res: usize) { + if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() { + s.remove(&res); + } + if let Some(s) = SPARSE_READBACK.lock().unwrap().as_mut() { + s.remove(&res); + } + if let Some(s) = RESERVED.lock().unwrap().as_mut() { + s.remove(&res); + } + if let Some(m) = BUFFER_DELTA.lock().unwrap().as_mut() { + m.remove(&res); + } + if let Some(m) = TITLE_ADDRESS.lock().unwrap().as_mut() { + m.remove(&res); + } + super::sparse::forget_buffer(res); + super::vram::forget(res); + super::title_textures::forget(res); + let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&res)); + if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { + if u.is_sparse(p) { + super::sparse::free(p); + } else { + u.free(p); + } + } +} + /// A stand-in pipeline released for good takes its background-built real pipeline with it. unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); diff --git a/crates/xcl/src/util.rs b/crates/xcl/src/util.rs index a7609fe3ff..37b05d9354 100644 --- a/crates/xcl/src/util.rs +++ b/crates/xcl/src/util.rs @@ -132,6 +132,36 @@ pub fn under_wine() -> bool { }) } +/// The process runs under Wine on a Mac (ntdll's `wine_get_host_version` says Darwin): CrossOver +/// or the Game Porting Toolkit, where D3D12 is Apple's D3DMetal and, on Apple Silicon, the +/// title's code runs through Rosetta 2. Known from the start of the run, before there is a +/// device. `XCL_MAC_HOST=1` / `0` overrides the detection. +pub fn mac_host() -> bool { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + static MAC: std::sync::OnceLock = std::sync::OnceLock::new(); + *MAC.get_or_init(|| { + let forced = std::env::var("XCL_MAC_HOST").ok(); + // SAFETY: ntdll is always loaded; Wine's export fills two pointers to static strings. + let sysname = unsafe { + GetProcAddress(GetModuleHandleA(c"ntdll.dll".as_ptr() as *const u8), c"wine_get_host_version".as_ptr() as *const u8).and_then(|f| { + let f: unsafe extern "C" fn(*mut *const u8, *mut *const u8) = std::mem::transmute(f); + let (mut sysname, mut release) = (std::ptr::null(), std::ptr::null()); + f(&mut sysname, &mut release); + from_cstr_ptr(sysname) + }) + }; + mac_host_from(forced.as_deref(), sysname.as_deref()) + }) +} + +/// `mac_host`'s answer from `XCL_MAC_HOST` (`forced`) and the host's system name, if Wine gave one. +fn mac_host_from(forced: Option<&str>, sysname: Option<&str>) -> bool { + match forced { + Some(v) => v.trim() != "0", + None => sysname.is_some_and(|s| s.eq_ignore_ascii_case("Darwin")), + } +} + /// Normalised DLL key: lower-case file name, ".dll" appended when no extension. pub fn dll_key(name: &str) -> String { let base = name.rsplit(['\\', '/']).next().unwrap_or(name); @@ -321,6 +351,20 @@ unsafe impl Sync for SendPtr {} mod tests { use super::*; + /// Darwin from Wine's host version is a Mac (in any case); Linux, Windows and no answer are + /// not; `XCL_MAC_HOST` decides when it is set, "0" for no and anything else for yes. + #[test] + fn a_mac_host_is_darwin_under_wine_unless_forced() { + assert!(mac_host_from(None, Some("Darwin"))); + assert!(mac_host_from(None, Some("darwin"))); + assert!(!mac_host_from(None, Some("Linux"))); + assert!(!mac_host_from(None, None)); + assert!(!mac_host_from(Some("0"), Some("Darwin"))); + assert!(!mac_host_from(Some(" 0 "), Some("Darwin"))); + assert!(mac_host_from(Some("1"), None)); + assert!(mac_host_from(Some("1"), Some("Linux"))); + } + #[test] fn dll_keys() { assert_eq!(dll_key("KERNELX"), "kernelx.dll");