diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..9dd50dec03 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}; @@ -92,6 +93,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); @@ -113,18 +124,124 @@ 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 only while it is less than N past the tail (one compare-exchange, so +/// writers at once cannot claim past it together), then writes its slot; one reader at a time +/// empties a slot before it moves the tail past it, so a claimed slot is always an empty one. +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, +} + +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); + let mut i = self.head.load(Ordering::Acquire); + loop { + // (the tail is stored after its slot is emptied: index i - N's slot is empty once + // the tail is past it) + if i.wrapping_sub(self.tail.load(Ordering::Acquire)) >= N { + return false; + } + match self.head.compare_exchange_weak(i, i.wrapping_add(1), Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => break, + Err(now) => i = now, + } + } + 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; } @@ -148,6 +265,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::*; @@ -208,4 +331,126 @@ 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; + 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]); + } + + /// More writers at once than there is room, all let go by one barrier: exactly the free + /// slots are claimed, and nothing already in the ring is overwritten. + #[test] + fn writers_at_once_past_the_free_room_overwrite_nothing() { + const N: usize = 512; + const FILLED: usize = 255; + const WRITERS: usize = 300; + let ring: &'static Ring = Box::leak(Box::new(Ring::new())); + for r in 1..=FILLED { + assert!(ring.push(r)); + } + let go = std::sync::Arc::new(std::sync::Barrier::new(WRITERS)); + let writers: Vec<_> = (0..WRITERS) + .map(|w| { + let go = go.clone(); + std::thread::spawn(move || { + let res = (w + 1) << 32; + go.wait(); + ring.push(res).then_some(res) + }) + }) + .collect(); + let pushed: Vec = writers.into_iter().filter_map(|w| w.join().unwrap()).collect(); + assert_eq!(pushed.len(), N - FILLED, "exactly the free slots are claimed"); + let got = ring.take(); + assert_eq!(got.len(), N, "the ring holds every claimed resource"); + assert_eq!(got[..FILLED], (1..=FILLED).collect::>()[..], "nothing that was in the ring is overwritten"); + let mut rest = got[FILLED..].to_vec(); + let mut want = pushed; + rest.sort_unstable(); + want.sort_unstable(); + assert_eq!(rest, want, "every accepted resource comes out once"); + } + + /// 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 01e3e1015e..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, @@ -721,6 +744,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; } @@ -746,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; @@ -1673,33 +1704,17 @@ 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 { - 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); @@ -1707,6 +1722,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); @@ -8879,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)); + } + } + } +}