From 9ac7d6366e2a0af2449638620942b44a92d46771 Mon Sep 17 00:00:00 2001 From: vakaobr <15154330+vakaobr@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:44:37 -0300 Subject: [PATCH 1/4] D3D12.X: read the late-release setting at adoption, not at first release D3DMetal calls Release on adopted resources from a native thread of its own at submit time. That thread has no Wine TEB, so the first-time std::env::var read inside the OnceLock in late_release::enabled() enters Wine's ntdll and never returns. Reading the setting once in adopt(), on the Wine thread that creates the object, makes sure the OnceLock is already set before the host's thread can reach it. Part of #258. Assisted-by: Claude Code (Claude Opus 4.6 (1M context)) --- crates/xcl/src/hle/d3d12x/late_release.rs | 10 ++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..b9b96b4d04 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -92,6 +92,16 @@ 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(); +} + /// how long a last `Release` itself waits for queues with nothing to do to say so const IDLE_WAIT: Duration = Duration::from_micros(300); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 01e3e1015e..2bf6f01af9 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; } From 4b5a933d09126f7058fcda6dc65317da0c3ab6f8 Mon Sep 17 00:00:00 2001 From: Ahmet Dedeler <105894172+Ahmet-Dedeler@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:48:55 +0300 Subject: [PATCH 2/4] D3D12.X: a resource's last Release forgets its address in one function The steps that drop what XCL keeps by a released resource's address (the maps, sparse pins, title textures, tiled textures, its unified-memory block) move from res_release into real::forget_released, unchanged and in the same order. The next commit calls it from the late-release thread as well. No change in behaviour. Co-Authored-By: Claude Mythos 5.2 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 57 +++++++++++++++++-------------- 1 file changed, 31 insertions(+), 26 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 2bf6f01af9..70a0928e77 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1678,32 +1678,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); - } - } + forget_released(this as usize); } if held { super::late_release::hold(this as usize); @@ -1711,6 +1686,36 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { n } +/// A resource the title released for good: what XCL keeps by its address goes. +pub(super) unsafe fn forget_released(this: usize) { + if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() { + s.remove(&this); + } + if let Some(s) = SPARSE_READBACK.lock().unwrap().as_mut() { + s.remove(&this); + } + if let Some(s) = RESERVED.lock().unwrap().as_mut() { + s.remove(&this); + } + if let Some(m) = BUFFER_DELTA.lock().unwrap().as_mut() { + m.remove(&this); + } + if let Some(m) = TITLE_ADDRESS.lock().unwrap().as_mut() { + m.remove(&this); + } + super::sparse::forget_buffer(this); + super::vram::forget(this); + super::title_textures::forget(this); + let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&this)); + 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 that is no driver object (`standin`) was released for good. pub(super) fn standin_released(pso: usize) { forget_pso(pso); From 6979e9fe663f1311abb4772a71ffa1e3015cabf0 Mon Sep 17 00:00:00 2001 From: Ahmet Dedeler <105894172+Ahmet-Dedeler@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:48:55 +0300 Subject: [PATCH 3/4] D3D12.X: a native host's last Release only queues the resource Apple's D3DMetal (CrossOver, the Game Porting Toolkit) calls Release on threads of its own (its queue thread at submit, for a barrier's resource) and from inside calls XCL makes while XCL holds a lock of its own. When that Release is the title's last one and late release keeps the object, res_release took the maps' locks, the sparse state's and the texture table's, and late_release::hold signalled the queues and waited. Whatever the host's thread waits for there, its queue waits for too. (The one such wait seen in a retail run on the Mac port, sparse's forget_buffer, no longer waits since #1981; the others are the same shape and are not waited for here either.) On a host whose D3D12 is in no PE module (class_for: module_of of the table's first method is 0, noted once when the first such table is adopted) a kept last Release now writes the resource into a ring of atomics (late_release::hand_over) and returns: no lock, no fence, no allocation, no thread start, no environment read (#1789 reads XCL_LATE_RELEASE at adoption). The next drain_known, on the late-release thread (started at adoption on such a host) or a submit, forgets what XCL keeps by the address (real::forget_released, the old body of res_release) and holds the object like any other; the address cannot come again before that, the object is still there. With the ring full (16,384 slots) the reference is kept for good and counted. D3D12 on Windows and vkd3d-proton are PE modules: there the flag is never set, the ring stays empty (drain_known reads two atomics) and a Release does what it did. Co-Authored-By: Claude Mythos 5.2 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/late_release.rs | 196 ++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 149 ++++++++++++++++ 2 files changed, 345 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index b9b96b4d04..42a505ae61 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::{AtomicUsize, Ordering}; use std::sync::Mutex; use std::time::{Duration, Instant}; @@ -123,18 +124,119 @@ pub unsafe fn hold(res: usize) { // A thread of its own lets the held ones go: the title may release a resource and then // wait for its memory without another submit (an imported heap pins the pages under its // resources – unmapping them stood still while one was held "until the next submit"). + start_thread(); +} + +/// The thread that lets held resources go. Started by the first `hold`, or on a native host +/// when the device is adopted (`real::class_for`): a Release there starts no thread. +pub(super) fn start_thread() { static THREAD: std::sync::Once = std::sync::Once::new(); THREAD.call_once(|| { let _ = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop { std::thread::sleep(TICK); unsafe { drain_known(false) }; + let kept = RING.kept.swap(0, Ordering::Relaxed); + if kept > 0 { + crate::xlog_warn!("D3D12.X: {kept} released resource(s) kept for good: the late-release ring was full"); + } }); }); } +/// Resources handed over by a last `Release` that may neither lock nor wait (`hand_over`): a +/// ring of slots written with atomics alone. The indices only grow (a slot is `index % N`); +/// a writer claims an index, then writes its slot; one reader at a time empties a slot before +/// it moves the tail past it. +struct Ring { + slots: [AtomicUsize; N], + /// the next index to write + head: AtomicUsize, + /// the next index to read + tail: AtomicUsize, + /// one reader at a time (readers are XCL's threads; writers never take it) + reading: Mutex<()>, + /// resources kept for good because the ring was full (`hand_over`; logged by the thread here) + kept: AtomicUsize, +} + +/// Room kept free for writers that pass the check in `Ring::push` at the same moment: with +/// fewer than this many at once, a claimed index is never a slot the reader has not emptied. +const RING_WRITERS: usize = 256; + +impl Ring { + const fn new() -> Self { + Self { slots: [const { AtomicUsize::new(0) }; N], head: AtomicUsize::new(0), tail: AtomicUsize::new(0), reading: Mutex::new(()), kept: AtomicUsize::new(0) } + } + + /// Nothing but atomics: no lock, no allocation. False: no room. + fn push(&self, res: usize) -> bool { + debug_assert!(res != 0); + if self.head.load(Ordering::Acquire).wrapping_sub(self.tail.load(Ordering::Acquire)) >= N - RING_WRITERS { + return false; + } + let i = self.head.fetch_add(1, Ordering::AcqRel); + self.slots[i % N].store(res, Ordering::Release); + true + } + + /// What was pushed so far, in order. An index claimed but not written yet ends the look: + /// it and those after it are taken the next time. + fn take(&self) -> Vec { + // (an empty ring – always, on a host that hands nothing over – is two loads) + if self.head.load(Ordering::Acquire) == self.tail.load(Ordering::Acquire) { + return Vec::new(); + } + let _one = self.reading.lock().unwrap(); + let mut out = Vec::new(); + let mut i = self.tail.load(Ordering::Acquire); + while i != self.head.load(Ordering::Acquire) { + let res = self.slots[i % N].swap(0, Ordering::AcqRel); + if res == 0 { + break; + } + out.push(res); + i = i.wrapping_add(1); + self.tail.store(i, Ordering::Release); + } + out + } +} + +/// The process's ring (16,384 slots, 128 KiB): a title releases thousands of resources a +/// frame while it loads. +static RING: Ring<{ 1 << 14 }> = Ring::new(); + +/// `res`, an adopted resource the title released for good with one reference kept +/// (`real::res_release` on a native host), is left to the thread here: what XCL keeps by its +/// address is forgotten there (`real::forget_released`) and the object goes once the queues +/// are past the work in flight. Nothing but atomics on the calling thread. With the ring full +/// the reference is kept for good: the object is never let go, so its address never comes +/// again and nothing XCL keeps by it can be wrong. +pub(super) fn hand_over(res: usize) { + hand_over_to(&RING, res); +} + +fn hand_over_to(ring: &Ring, res: usize) -> bool { + if ring.push(res) { + return true; + } + ring.kept.fetch_add(1, Ordering::Relaxed); + false +} + /// Release what every queue XCL knows of is past: the title's, the tile-mapping one, the /// upload ones. pub unsafe fn drain_known(seal_now: bool) { + // what was handed over by Releases that must not wait: forgotten here, on a thread of + // XCL's or the title's, then held like any other (the object is still there, so its + // address cannot come again before it is forgotten) + let handed = RING.take(); + if !handed.is_empty() { + for &res in &handed { + super::real::forget_released(res); + } + HELD.lock().unwrap().get_or_insert_with(Held::default).open.extend(handed); + } if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { return; } @@ -158,6 +260,12 @@ pub unsafe fn drain_known(seal_now: bool) { } } +/// The lock of the held resources, for a test that shows a Release does not wait for it. +#[cfg(test)] +pub(super) fn lock_held_for_test() -> impl Sized { + HELD.lock().unwrap() +} + #[cfg(test)] mod tests { use super::*; @@ -218,4 +326,92 @@ mod tests { assert_eq!(unsafe { held.drain(&[], false) }, vec![0x1000]); assert!(held.is_empty()); } + + /// The ring gives back what was handed over, in order, once, and is empty after. + #[test] + fn the_ring_gives_back_what_was_handed_over_in_order() { + let ring: Ring<1024> = Ring::new(); + assert!(ring.take().is_empty()); + for r in 1..=100 { + assert!(hand_over_to(&ring, r * 0x1000)); + } + assert_eq!(ring.take(), (1..=100).map(|r| r * 0x1000).collect::>()); + assert!(ring.take().is_empty()); + // the indices go on past the end of the slots + for round in 0..20 { + for r in 1..=100 { + assert!(hand_over_to(&ring, round * 0x10_0000 + r)); + } + assert_eq!(ring.take().len(), 100); + } + assert_eq!(ring.kept.load(Ordering::Relaxed), 0); + } + + /// A full ring refuses at once: the resource is counted as kept (its reference is never + /// given back, so nothing waits and its address never comes again), and the ring takes + /// resources again once it has been read. + #[test] + fn a_full_ring_keeps_the_resource_and_does_not_wait() { + let ring: Ring<512> = Ring::new(); + let room = 512 - RING_WRITERS; + for r in 1..=room { + assert!(hand_over_to(&ring, r), "room for {room}, refused at {r}"); + } + let start = Instant::now(); + assert!(!hand_over_to(&ring, 0xdead), "a full ring refuses"); + assert!(start.elapsed() < Duration::from_millis(100)); + assert_eq!(ring.kept.load(Ordering::Relaxed), 1); + let got = ring.take(); + assert_eq!(got.len(), room); + assert!(!got.contains(&0xdead), "the kept one is not handed over"); + assert!(hand_over_to(&ring, 0xbeef)); + assert_eq!(ring.take(), vec![0xbeef]); + } + + /// Writers on several threads against readers on others: every resource comes out once. + #[test] + fn writers_and_readers_at_once_lose_nothing_and_take_nothing_twice() { + const WRITERS: usize = 4; + const EACH: usize = 50_000; + let ring: &'static Ring<1024> = Box::leak(Box::new(Ring::new())); + let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let writers: Vec<_> = (0..WRITERS) + .map(|w| { + std::thread::spawn(move || { + for k in 0..EACH { + let res = (w + 1) << 32 | (k + 1); + while !ring.push(res) { + std::thread::yield_now(); + } + } + }) + }) + .collect(); + let readers: Vec<_> = (0..2) + .map(|_| { + let done = done.clone(); + std::thread::spawn(move || { + let mut got = Vec::new(); + loop { + let last = done.load(Ordering::Acquire); + got.extend(ring.take()); + if last { + break got; + } + std::thread::yield_now(); + } + }) + }) + .collect(); + for w in writers { + w.join().unwrap(); + } + done.store(true, Ordering::Release); + let mut all: Vec = readers.into_iter().flat_map(|r| r.join().unwrap()).collect(); + all.extend(ring.take()); + assert_eq!(all.len(), WRITERS * EACH, "every resource once"); + all.sort_unstable(); + all.dedup(); + assert_eq!(all.len(), WRITERS * EACH, "none twice"); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 70a0928e77..697e73daec 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -634,6 +634,29 @@ pub unsafe fn orig_fn(this: *mut c_void, slot: usize) -> usize { *orig.add(slot) } +/// The host's D3D12 is in no PE module (Apple's D3DMetal under CrossOver or the Game Porting +/// Toolkit): set when the first such table is adopted (`class_for`), never cleared. +static NATIVE_HOST: AtomicBool = AtomicBool::new(false); + +/// Whether the host's D3D12 is a native host's (`NATIVE_HOST`): an atomic read, for a Release. +pub(super) fn native_host() -> bool { + let on = NATIVE_HOST.load(Ordering::Relaxed); + // (a test's own switch, read after the flag: on a native host the flag is set before any + // Release, so a thread of the host's never reads this thread-local) + #[cfg(test)] + let on = on || native_host_tests::FORCED.with(|f| f.get()); + on +} + +/// `class_for` met a native host's table: noted once, and the thread that lets held resources +/// go is started now, on the adopting thread, not in a Release on a thread of the host's. +fn note_native_host() { + if !NATIVE_HOST.swap(true, Ordering::Relaxed) { + super::late_release::start_thread(); + crate::xlog_info!("D3D12.X: the host's D3D12 is in no PE module (a native host: D3DMetal) – a resource's last Release only hands it to the late-release thread"); + } +} + fn module_of(addr: usize) -> usize { use windows_sys::Win32::System::LibraryLoader::{ GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, @@ -750,6 +773,10 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { } let public = iface.methods.len(); let m0 = module_of(*ot); + // (D3D12 on Windows and vkd3d-proton under Wine are PE modules) + if m0 == 0 { + note_native_host(); + } let mut scanned = 0; while scanned < public + MAX_SCAN && module_of(*ot.add(scanned)) == m0 { scanned += 1; @@ -1677,6 +1704,15 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } else { f(this) }; + // On a native host (D3DMetal) a Release can come on a thread of the host's own (its queue + // thread, at submit) or from inside a call XCL makes with a lock of its own held: a kept + // last Release only goes into a ring of atomics there – no lock of XCL's, no fence, no + // allocation. `late_release`'s thread forgets what XCL keeps by the address and lets the + // object go. Elsewhere this is never taken. + if held && native_host() { + super::late_release::hand_over(this as usize); + return 0; + } if n == 0 { forget_released(this as usize); } @@ -8888,3 +8924,116 @@ void main() { } } + +#[cfg(test)] +mod native_host_tests { + use super::*; + use std::time::{Duration, Instant}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + + thread_local! { + /// `native_host` answers true on this thread (a test of the native host's Release on + /// any host) + pub(super) static FORCED: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + unsafe fn adopted_buffer(dev: &ID3D12Device) -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 4096, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut res: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut res).unwrap(); + let res = res.unwrap(); + adopt(res.as_raw(), Kind::Resource); + res + } + + /// The host is a native one only when its tables are in no PE module: D3D12 on Windows (and + /// vkd3d-proton under Wine) keeps the Release it had. + #[test] + fn only_a_table_in_no_pe_module_makes_a_native_host() { + // this test's own code is in a PE module, memory from the heap is in none + assert_ne!(module_of(native_host as usize), 0); + let heap = Box::new(0usize); + assert_eq!(module_of(&*heap as *const usize as usize), 0); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let res = adopted_buffer(&dev); + let first = orig_fn(res.as_raw(), 0); + if module_of(first) != 0 { + assert!(!NATIVE_HOST.load(Ordering::Relaxed), "a host in a PE module is no native host"); + assert!(!native_host()); + } else { + assert!(NATIVE_HOST.load(Ordering::Relaxed), "a host in no PE module is a native host"); + } + } + } + + /// On a native host a kept last Release takes none of XCL's locks: with the late-release + /// lock and the maps' locks held on another thread it returns at once, and the resource + /// is forgotten and let go by the next drain. + #[test] + fn a_kept_last_release_on_a_native_host_waits_for_no_lock() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + if !super::super::late_release::enabled() { + return crate::gpu::recomp::runner::skip_test("XCL_LATE_RELEASE=0"); + } + let res = adopted_buffer(&dev); + let raw = res.as_raw() as usize; + UNMAPPABLE.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw); + + let (locked_tx, locked_rx) = std::sync::mpsc::channel(); + let (free_tx, free_rx) = std::sync::mpsc::channel::<()>(); + let locker = std::thread::spawn(move || { + let held = super::super::late_release::lock_held_for_test(); + let maps = ( + UNMAPPABLE.lock().unwrap(), + SPARSE_READBACK.lock().unwrap(), + RESERVED.lock().unwrap(), + BUFFER_DELTA.lock().unwrap(), + TITLE_ADDRESS.lock().unwrap(), + UMA_BUFFERS.lock().unwrap(), + ); + locked_tx.send(()).unwrap(); + let _ = free_rx.recv_timeout(Duration::from_secs(10)); + drop(maps); + drop(held); + }); + locked_rx.recv().unwrap(); + + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let releaser = std::thread::spawn(move || { + FORCED.with(|f| f.set(true)); + let start = Instant::now(); + drop(res); + done_tx.send(start.elapsed()).unwrap(); + }); + let waited = done_rx.recv_timeout(Duration::from_secs(3)); + free_tx.send(()).unwrap(); + locker.join().unwrap(); + releaser.join().unwrap(); + let waited = waited.expect("the last Release waited for a lock another thread held"); + assert!(waited < Duration::from_secs(1), "the last Release took {waited:?}"); + + // a drain forgets it (this thread's or the late-release thread's) + let start = Instant::now(); + while UNMAPPABLE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&raw)) { + assert!(start.elapsed() < Duration::from_secs(5), "not forgotten by a drain"); + super::super::late_release::drain_known(true); + std::thread::sleep(Duration::from_millis(5)); + } + } + } +} From 85a02de2982dfcb5f8f6fe5886c31a2f3185b344 Mon Sep 17 00:00:00 2001 From: vakaobr <15154330+vakaobr@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:38:07 -0300 Subject: [PATCH 4/4] D3D12.X: a Release on a thread XCL did not create is made on a Wine thread D3DMetal calls Release on adopted resources from native threads of its own (its queue thread, at submit). Such a thread has no Wine TEB, and a std Mutex that is contended there waits in Wine's ntdll and never returns. With the previous commit a kept last Release on a native host only goes into the late-release ring. The rest of res_release still ran on the host's thread: a last Release that is not kept (XCL_LATE_RELEASE=0, or two last-but-one releases that miss each other, whose count reaches 0 in the second Release) forgets what XCL keeps by the address there, with the maps' locks, the sparse state's and the texture table's. Now, on a native host (real::native_host), a Release on such a thread runs none of res_release there. The host's own AddRef and Release read the count to return, and the caller's reference goes into the same ring as the kept ones, with bit 0 of the address set (OWED: a Release still owed, not a resource already released for good). drain_known, on the late-release thread or at a submit, runs each owed one through res_release on its own thread. Whether it is the last one is not decided on the host's thread: a Release on another thread between that check and ours could still take the count to 0 there. With the ring full the reference is kept for good, as for the kept ones. A thread is foreign when its stack is at or above 0x7000_0000_0000. Measured on an M5 Pro (CrossOver 26.3, Rosetta 2): Wine threads 0x0180ea9f..0x0220fb37, D3DMetal threads 0x7ff2063df667..0x7ff2066c3677. The TEB pointer (gs:[0x30]) is not read: that read hangs on a D3DMetal thread. The check is made only on a native host: on Wine on Linux a Wine thread's stack may sit in that range. Measured on a MacBook Pro M5 Pro, CrossOver 26.3.0 with D3DMetal 3.0 (the test device's tables are in no PE module, so NATIVE_HOST is set), each test in its own process: the late_release tests, the native_host_tests and the new a_release_on_a_foreign_thread_is_given_back_by_a_drain pass; that test fails without the new branch in res_release ("the foreign thread's Release was made on that thread": the count was 1, not 2, when it returned). Part of #258. --- crates/xcl/src/hle/d3d12x/late_release.rs | 85 +++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 80 ++++++++++++++++++++- 2 files changed, 164 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 42a505ae61..6abb39b7e7 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -224,6 +224,52 @@ fn hand_over_to(ring: &Ring, res: usize) -> bool { false } +/// A ring entry with this bit set (an object's address is aligned, so bit 0 is free) is not a +/// resource released for good but a Release still owed: one that came on a thread XCL did not +/// create (`defer_release`). +const OWED: usize = 1; + +/// The caller's `Release` of `res` came on a thread XCL did not create (`is_foreign_thread`): +/// it is owed, in the ring, and the next drain runs it through `real::res_release` on a thread +/// of XCL's or the title's. Nothing but atomics on the calling thread. With the ring full the +/// reference is kept for good, as in `hand_over`. +pub(super) fn defer_release(res: usize) { + hand_over_to(&RING, res | OWED); +} + +/// Above this, a thread's stack is a native macOS thread's (D3DMetal's), not a Wine thread's. +/// +/// 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's thread stacks are in the low hundreds of megabytes; macOS native stacks are near the +/// top of the 47-bit user range. 0x7000_0000_0000 (112 TB) leaves tens of TB on each side. The +/// check is only made on a native host (`real::native_host`): on Wine on Linux a Wine thread's +/// stack may sit in that range. The TEB pointer (`gs:[0x30]`) is not read 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; + +/// Whether the calling thread is one XCL did not create: a native host's own (D3DMetal's), with +/// no Wine TEB. A lock of XCL's that is contended waits in Wine's ntdll there, and never returns. +pub(super) fn is_foreign_thread() -> bool { + let local = 0u8; + let foreign = super::real::native_host() && &local as *const u8 as usize >= NATIVE_STACK_BOUNDARY; + // (a test's own switch, read after the check: a thread of the host's is foreign before it + // reads this thread-local) + #[cfg(test)] + let foreign = foreign || FORCE_FOREIGN.with(|f| f.get()); + foreign +} + +#[cfg(test)] +thread_local! { + /// `is_foreign_thread` answers true on this thread (a test of the foreign thread's Release + /// on a Wine thread) + pub(super) static FORCE_FOREIGN: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + /// Release what every queue XCL knows of is past: the title's, the tile-mapping one, the /// upload ones. pub unsafe fn drain_known(seal_now: bool) { @@ -232,10 +278,16 @@ pub unsafe fn drain_known(seal_now: bool) { // address cannot come again before it is forgotten) let handed = RING.take(); if !handed.is_empty() { + // (and the Releases a thread XCL did not create owes (`OWED`): run here, through the + // whole of `real::res_release`) + let (owed, handed): (Vec, Vec) = handed.into_iter().partition(|&r| r & OWED != 0); for &res in &handed { super::real::forget_released(res); } HELD.lock().unwrap().get_or_insert_with(Held::default).open.extend(handed); + for res in owed { + super::real::res_release((res & !OWED) as *mut c_void); + } } if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { return; @@ -266,6 +318,12 @@ pub(super) fn lock_held_for_test() -> impl Sized { HELD.lock().unwrap() } +/// The ring's reader lock: no drain takes from the ring while a test holds it. +#[cfg(test)] +pub(super) fn lock_ring_for_test() -> impl Sized { + RING.reading.lock().unwrap() +} + #[cfg(test)] mod tests { use super::*; @@ -414,4 +472,31 @@ mod tests { all.dedup(); assert_eq!(all.len(), WRITERS * EACH, "none twice"); } + + /// A Wine thread (the test thread) is not foreign: off a native host the check is not + /// made, and on one its stack is below the boundary. + #[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.with(|f| f.set(true)); + assert!(is_foreign_thread(), "FORCE_FOREIGN should make it report foreign"); + FORCE_FOREIGN.with(|f| f.set(false)); + assert!(!is_foreign_thread(), "back to normal"); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 697e73daec..9802062d1e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1685,8 +1685,23 @@ 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 { +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 Release on a thread XCL did not create (a native host's own: D3DMetal's) runs none of + // what follows there: the caller's reference goes into the late-release ring, and the next + // drain runs it through here on a thread of XCL's or the title's. Whether it is the last one + // is not decided here (AddRef returning 2): a Release on another thread between that check + // and ours could still take the count to 0 on this thread, and what XCL keeps by the address + // would then be forgotten here. The count returned is what the caller's Release leaves if + // nothing else changes; the AddRef and its Release cannot reach 0, the caller's reference + // is still held. + if super::late_release::is_foreign_thread() { + let add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); + let n = add(this); + f(this); + super::late_release::defer_release(this as usize); + return n.saturating_sub(2); + } // 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.) @@ -9036,4 +9051,67 @@ mod native_host_tests { } } } + + /// A Release on a thread XCL did not create is not made there: the caller's reference is + /// still held when it returns, and a drain on a thread of XCL's gives it back. A last one + /// is forgotten by that drain too, not on the foreign thread. + #[test] + fn a_release_on_a_foreign_thread_is_given_back_by_a_drain() { + use super::super::late_release::{drain_known, is_foreign_thread, lock_ring_for_test, FORCE_FOREIGN}; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let res = adopted_buffer(&dev); + let raw = res.as_raw(); + // the count, read with the host's own AddRef and Release (not XCL's) + let count = || { + let add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(raw, 1)); + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(raw, 2)); + let n = add(raw); + rel(raw); + n - 1 + }; + let release_on_a_foreign_thread = |r: ID3D12Resource| { + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let foreign = std::thread::spawn(move || { + FORCED.with(|f| f.set(true)); + FORCE_FOREIGN.with(|f| f.set(true)); + drop(r); + done_tx.send(()).unwrap(); + }); + done_rx.recv_timeout(Duration::from_secs(3)).expect("the foreign thread's Release did not return"); + foreign.join().unwrap(); + }; + assert!(!is_foreign_thread(), "the test thread is a Wine thread"); + + // not the last reference: it stays until a drain (none can take from the ring while + // the reader's lock is held here; the late-release thread may be running) + let other = res.clone(); + assert_eq!(count(), 2); + let reader = lock_ring_for_test(); + release_on_a_foreign_thread(other); + assert_eq!(count(), 2, "the foreign thread's Release was made on that thread"); + drop(reader); + let start = Instant::now(); + while count() != 1 { + assert!(start.elapsed() < Duration::from_secs(5), "the foreign thread's Release was not given back by a drain"); + drain_known(true); + std::thread::sleep(Duration::from_millis(5)); + } + + // the last one: what XCL keeps by the address is forgotten by a drain + UNMAPPABLE.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); + let reader = lock_ring_for_test(); + release_on_a_foreign_thread(res); + assert!(UNMAPPABLE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&(raw as usize))), "forgotten on the foreign thread"); + drop(reader); + let start = Instant::now(); + while UNMAPPABLE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&(raw as usize))) { + assert!(start.elapsed() < Duration::from_secs(5), "not forgotten by a drain"); + drain_known(true); + std::thread::sleep(Duration::from_millis(5)); + } + } + } }