Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
306 changes: 306 additions & 0 deletions crates/xcl/src/hle/d3d12x/late_release.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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<usize>) -> 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);

Expand All @@ -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)");
}
});
});
}
Expand Down Expand Up @@ -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<Ring> {
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<usize> = (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<usize> = 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::<Vec<_>>(), "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);
}
}
Loading
Loading