diff --git a/crates/xcl/src/gpu/adapter.rs b/crates/xcl/src/gpu/adapter.rs index cd0b61fd85..0aa6301d82 100644 --- a/crates/xcl/src/gpu/adapter.rs +++ b/crates/xcl/src/gpu/adapter.rs @@ -115,6 +115,21 @@ pub(crate) fn select_indices>(names: &[S], sel: &Selector) -> Vec< Vec::new() } +/// PCI vendor of the adapter the D3D12 backend opens, from the hardware adapters in +/// high-performance order as `(name, vendor)`: the first one `sel` allows, else the first one +/// `auto` allows (`real::init` falls back the same way); `None` for `warp` or no hardware. +pub(crate) fn chosen_vendor>(adapters: &[(S, u32)], sel: &Selector) -> Option { + if *sel == Selector::Warp { + return None; + } + let names: Vec<&str> = adapters.iter().map(|(n, _)| n.as_ref()).collect(); + let mut picked = select_indices(&names, sel); + if picked.is_empty() { + picked = select_indices(&names, &Selector::Auto); + } + picked.first().map(|&i| adapters[i].1) +} + /// The adapter's name from its description. pub fn name(desc: &DXGI_ADAPTER_DESC1) -> String { let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); diff --git a/crates/xcl/src/gpu/adapter_tests.rs b/crates/xcl/src/gpu/adapter_tests.rs index 70fc209aa0..99d9da506a 100644 --- a/crates/xcl/src/gpu/adapter_tests.rs +++ b/crates/xcl/src/gpu/adapter_tests.rs @@ -1,4 +1,4 @@ -use super::{select_indices, Selector}; +use super::{chosen_vendor, select_indices, Selector}; #[test] fn selector_parsing() { @@ -53,3 +53,24 @@ fn numeric_selector_falls_back_to_model_token_when_out_of_range() { assert!(select_indices(&two, &Selector::parse("80")).is_empty()); assert_eq!(select_indices(&two, &Selector::parse("2080")), vec![0]); } + +#[test] +fn chosen_vendor_is_the_adapter_the_backend_opens() { + const AMD: u32 = 0x1002; + const NV: u32 = 0x10de; + const INTEL: u32 = 0x8086; + // hybrid machines, hardware adapters in high-performance order (the dedicated GPU first) + let nv_dgpu_amd_igpu = [("NVIDIA GeForce RTX 4070", NV), ("AMD Radeon(TM) Graphics", AMD)]; + let amd_dgpu_intel_igpu = [("AMD Radeon RX 7900 XT", AMD), ("Intel(R) UHD Graphics 770", INTEL)]; + assert_eq!(chosen_vendor(&nv_dgpu_amd_igpu, &Selector::Auto), Some(NV), "AMD iGPU must not make an NVIDIA run 'AMD'"); + assert_eq!(chosen_vendor(&amd_dgpu_intel_igpu, &Selector::Auto), Some(AMD), "an AMD dGPU behind an Intel iGPU is still AMD"); + // `d3d12_adapter` / `XCL_ADAPTER` choose the other one + assert_eq!(chosen_vendor(&nv_dgpu_amd_igpu, &Selector::parse("radeon")), Some(AMD)); + assert_eq!(chosen_vendor(&nv_dgpu_amd_igpu, &Selector::Index(1)), Some(AMD)); + assert_eq!(chosen_vendor(&amd_dgpu_intel_igpu, &Selector::parse("intel")), Some(INTEL)); + // a selector that matches nothing falls back to `auto`, as `real::init` does + assert_eq!(chosen_vendor(&amd_dgpu_intel_igpu, &Selector::parse("geforce")), Some(AMD)); + // WARP or no hardware adapter: no vendor + assert_eq!(chosen_vendor(&amd_dgpu_intel_igpu, &Selector::Warp), None); + assert_eq!(chosen_vendor::<&str>(&[], &Selector::Auto), None); +} diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 2041690262..67bada0f19 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -733,7 +733,7 @@ pub fn run_with_statics( tex_back.push((i, rb)); } list.Close().map_err(e)?; - gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); + submit_list(&gpu.queue, &list)?; gpu.value += 1; wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "kernel dispatch")?; let mut p = std::ptr::null_mut(); @@ -1222,7 +1222,7 @@ fn draw_indexed_on( }; list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); list.Close().map_err(e)?; - queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); + submit_list(&queue, &list)?; wait_for_submission(dev, &queue, &fence, 1, "draw")?; let mut p = std::ptr::null_mut(); readback.Map(0, None, Some(&mut p)).map_err(e)?; @@ -1425,7 +1425,7 @@ pub fn mesh_draw_split( list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); list.CopyBufferRegion(&readback, total, &res_buf, 0, res_bytes); list.Close().map_err(e)?; - gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); + submit_list(&gpu.queue, &list)?; gpu.value += 1; wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "mesh draw")?; let mut q = std::ptr::null_mut(); @@ -1561,7 +1561,7 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result Result<(), String> { + let cmd: ID3D12CommandList = list.cast().map_err(e)?; + let _guard = crate::hle::d3d12x::real::UnadoptGuard::new(cmd.as_raw()); + queue.ExecuteCommandLists(&[Some(cmd)]); + Ok(()) +} diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 7592d044b0..a1857f1d7e 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -265,10 +265,14 @@ impl Uma { } let mut win_allocs = Vec::with_capacity(1 + coh_wins); win_allocs.push(base); + // Under Wine without userfaultfd, MEM_WRITE_WATCH uses mprotect(PROT_READ), which + // triggers amdgpu userptr MMU-notifier evictions and ~100ms GPU stalls on the + // coherent window imported via OpenExistingHeapFromAddress (`wine_amd_gpu`). + let c_flags = if wine_amd_gpu() { MEM_RESERVE | MEM_COMMIT } else { MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH }; let mut ok = true; for (c, &c_size) in coh_sizes.iter().enumerate() { let c_base = base + (sparse_wins + c) * WINDOW; - let cp = unsafe { VirtualAlloc(c_base as *const std::ffi::c_void, c_size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }; + let cp = unsafe { VirtualAlloc(c_base as *const std::ffi::c_void, c_size, c_flags, PAGE_READWRITE) }; if cp as usize != c_base { if !cp.is_null() { unsafe { VirtualFree(cp, 0, MEM_RELEASE) }; @@ -490,7 +494,8 @@ impl Uma { for k in 0..windows { let want = base + k * WINDOW; // write-watched: textures the title keeps here are uploaded again after CPU writes - let p = unsafe { VirtualAlloc(want as *const std::ffi::c_void, size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }; + let c_flags = if wine_amd_gpu() { MEM_RESERVE | MEM_COMMIT } else { MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH }; + let p = unsafe { VirtualAlloc(want as *const std::ffi::c_void, size, c_flags, PAGE_READWRITE) }; if p.is_null() { break; } @@ -561,7 +566,9 @@ impl Uma { match self.kinds[k] { WindowKind::None => k += 1, WindowKind::Committed(s) => { - out.push((self.base + k * WINDOW, s)); + if !wine_amd_gpu() { + out.push((self.base + k * WINDOW, s)); + } k += 1; } WindowKind::Sparse => { @@ -782,12 +789,40 @@ fn coherent_file() -> std::path::PathBuf { crate::state::data_dir().join("cache").join("uma_coherent.txt") } +/// Whether this process is running under Wine and XCL's D3D12 adapter (`d3d12_adapter` / +/// `XCL_ADAPTER`, as `real::init` picks it) is an AMD GPU (`amdgpu`, PCI vendor `0x1002`). +/// On `amdgpu`, a multi-GiB `userptr` BO imported via `OpenExistingHeapFromAddress` stalls +/// every Vulkan submission (~150 ms/frame), and write-watching it (`mprotect`) evicts it; NVIDIA +/// Linux does not hit that stall and keeps a larger, write-watched coherent window. +pub(crate) fn wine_amd_gpu() -> bool { + static AMD: OnceLock = OnceLock::new(); + *AMD.get_or_init(|| { + if !crate::util::under_wine() { + return false; + } + use crate::gpu::adapter::{self, Selector}; + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, IDXGIFactory6, DXGI_CREATE_FACTORY_FLAGS}; + let Ok(factory) = (unsafe { CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) }) else { + return false; + }; + let hw: Vec<(String, u32)> = adapter::hardware(&factory).iter().map(|(_, d)| (adapter::name(d), d.VendorId)).collect(); + let sel = Selector::from_env_or(&crate::state::config().d3d12_adapter); + adapter::chosen_vendor(&hw, &sel) == Some(0x1002) + }) +} + /// Bytes the coherent window(s) are made with for a runtime layout of `windows` windows. pub fn coherent_hint_for(windows: usize) -> usize { let cap = max_coherent_bytes(windows); if let Some(mb) = std::env::var("XCL_COHERENT_MB").ok().and_then(|v| v.parse::().ok()) { return (mb << 20).clamp(GRAIN, cap); } + // Under Wine/vkd3d-proton on Linux (amdgpu), a multi-GiB userptr BO imported via + // OpenExistingHeapFromAddress stalls every GPU submission (~150 ms/frame); keep the + // coherent window at 512 MiB and place overflow title GPU heaps in the sparse VRAM windows. + if wine_amd_gpu() { + return RUNTIME_COMMITTED_CAP; + } let title = std::fs::read_to_string(coherent_file()).ok().and_then(|s| s.trim().parse::().ok()).unwrap_or(0); // only with the commit for all of it: the title's ~13 GB, video memory for its render targets // and textures (WDDM charges commit for each video-memory allocation too) and the window @@ -1101,8 +1136,14 @@ mod tests { assert_eq!(u.sparse_release(y), Some(GRAIN)); assert_eq!(u.sparse_release(desc), Some(GRAIN)); assert_eq!(u.sparse_used(), 0); - // Contiguous sparse windows 0..2 are reported as one OS watch region; window 3 as another. - assert_eq!(u.watch_regions(), vec![(u.base(), 3 * WINDOW), (u.base() + 3 * WINDOW, 16 << 20)]); + // Contiguous sparse windows 0..2 are reported as one OS watch region; window 3 as another + // on native Windows (excluded under Wine on amdgpu to avoid userptr MMU-notifier stalls). + let expected = if wine_amd_gpu() { + vec![(u.base(), 3 * WINDOW)] + } else { + vec![(u.base(), 3 * WINDOW), (u.base() + 3 * WINDOW, 16 << 20)] + }; + assert_eq!(u.watch_regions(), expected); } #[test] @@ -1135,13 +1176,15 @@ mod tests { assert_eq!(u.sparse_release(d), Some(ld)); assert_eq!(u.sparse_release(r), Some(big)); assert_eq!(u.sparse_used(), 0); - assert_eq!( - u.watch_regions(), + let expected = if wine_amd_gpu() { + vec![(u.base(), MAX_RUNTIME_SPARSE_WINDOWS * WINDOW)] + } else { vec![ (u.base(), MAX_RUNTIME_SPARSE_WINDOWS * WINDOW), (u.base() + MAX_RUNTIME_SPARSE_WINDOWS * WINDOW, 16 << 20), ] - ); + }; + assert_eq!(u.watch_regions(), expected); } } diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 8b81b85913..d10f1a5a49 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -198,7 +198,7 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { let key = queue as usize; if !s.fences.contains_key(&key) { let mut dev: Option = None; - let Some(f) = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()) else { return }; + let Some(f) = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| super::real::create_raw_fence(&d).ok()) else { return }; s.fences.insert(key, (f, 0)); } let (fence, value) = { @@ -452,12 +452,15 @@ mod tests { if !super::super::real::is_adopted(a) { super::super::real::adopt(a, super::super::real::Kind::CommandAllocator); } - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let list: ID3D12GraphicsCommandList = { + let _alloc_guard = super::super::real::UnadoptGuard::new(a); + dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap() + }; let l = list.as_raw(); created_on(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0); list.Close().unwrap(); let lists = [Some(list.cast::().unwrap())]; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let fence: ID3D12Fence = super::super::real::create_raw_fence(&dev).unwrap(); let done = |v: u64| { queue.Signal(&fence, v).unwrap(); let start = std::time::Instant::now(); @@ -467,7 +470,10 @@ mod tests { assert!(fence.GetCompletedValue() >= v, "the queue finishes"); }; - queue.ExecuteCommandLists(&lists); + { + let _list_guard = super::super::real::UnadoptGuard::new(l); + queue.ExecuteCommandLists(&lists); + } executed(queue.as_raw(), &[l]); done(1); @@ -476,7 +482,10 @@ mod tests { let second = current(a as usize); assert_ne!(second, a as usize, "the list still holds its recording: another PC allocator takes the place"); // … and submits the recording again - queue.ExecuteCommandLists(&lists); + { + let _list_guard = super::super::real::UnadoptGuard::new(l); + queue.ExecuteCommandLists(&lists); + } executed(queue.as_raw(), &[l]); done(2); assert!(dev.GetDeviceRemovedReason().is_ok(), "the recording was still there"); @@ -485,10 +494,14 @@ mod tests { let second_alloc = ID3D12CommandAllocator::from_raw_borrowed(&(second as *mut c_void)).unwrap().clone(); assert_eq!(reset_list(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |pc| { assert_eq!(pc, second); + let _alloc_guard = super::super::real::UnadoptGuard::new(pc as *mut c_void); list.Reset(&second_alloc, None).map_or_else(|e| e.code().0, |_| 0) }), 0); list.Close().unwrap(); - queue.ExecuteCommandLists(&lists); + { + let _list_guard = super::super::real::UnadoptGuard::new(l); + queue.ExecuteCommandLists(&lists); + } executed(queue.as_raw(), &[l]); done(3); @@ -501,6 +514,7 @@ mod tests { // it stays (the next allocator at its address is its own) assert_eq!(reset_list(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |pc| { assert_eq!(pc, a as usize); + let _alloc_guard = super::super::real::UnadoptGuard::new(pc as *mut c_void); list.Reset(&alloc, None).map_or_else(|e| e.code().0, |_| 0) }), 0); list.Close().unwrap(); diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 0b20bfbd6a..b0958615f0 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -173,7 +173,7 @@ pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { return; } let Some(dev) = dev else { return }; - let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return }; + let Ok(fence) = super::real::create_raw_fence(&dev) else { return }; v.insert(QueueFence { fence, value: 0 }) } }; diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..a26cc7833f 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -54,7 +54,7 @@ impl Held { let key = q.as_raw() as usize; if !self.fences.contains_key(&key) { let mut dev: Option = None; - let made = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()); + let made = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| super::real::create_raw_fence(&d).ok()); let Some(f) = made else { ok = false; break; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..a7c7735075 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -674,6 +674,7 @@ impl ListState { last.1 = last.1.max(end); } if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) { + unsafe { super::sparse::ensure_lazy_mapped(va as usize, size as usize) }; if self.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); } @@ -1661,17 +1662,23 @@ unsafe fn ensure_cell_fence(va: u64, dev: &ID3D12Device, dev_raw: usize) -> Opti } } } - let created: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; - let mut g = SYNC_GRAPH.lock().unwrap(); - let cell = g.get_or_insert_with(SyncGraph::default).cells.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()); + let created: ID3D12Fence = real::create_raw_fence(&dev).ok()?; + let installed = { + let mut g = SYNC_GRAPH.lock().unwrap(); + let cell = g.get_or_insert_with(SyncGraph::default).cells.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; + true + }; + if installed { + real::track_end_title_fence(&created); } - cell.fence = Some(created.clone()); - cell.device = dev_raw; Some(created) } @@ -1991,6 +1998,9 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, return GpuWaitOutcome::FallbackCpu; } + if unsubmitted { + super::sparse::note_queue_wait(q_raw, fence.clone(), w.value); + } wake_sync_watchdog(); if unsubmitted { static LOGGED: AtomicU64 = AtomicU64::new(0); @@ -2306,7 +2316,7 @@ pub(super) unsafe fn copy_scratch_submitted(queue: *mut c_void, lists: &[*mut c_ if let std::collections::hash_map::Entry::Vacant(entry) = cache.fences.entry(key) { let mut dev: Option = None; q.GetDevice(&mut dev).ok()?; - entry.insert((dev?.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()?, 0)); + entry.insert((real::create_raw_fence(&dev?).ok()?, 0)); } let (fence, value) = cache.fences.get_mut(&key)?; let next = *value + 1; @@ -2689,7 +2699,10 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { None => super::alloc_pool::title_reset(own).unwrap_or_else(|| real::reset_pc_allocator(own)), }; if hr >= 0 { - hr = super::alloc_pool::reset_list(seg as usize, own as usize, ty.0, |pc_alloc| pc:: i32>(seg, PC_RESET)(seg, pc_alloc, 0)); + hr = super::alloc_pool::reset_list(seg as usize, own as usize, ty.0, |pc_alloc| { + let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void); + pc:: i32>(seg, PC_RESET)(seg, pc_alloc, 0) + }); } real::preserve_vtable(seg, ext); if hr < 0 { @@ -2806,6 +2819,8 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ if let Some(spare) = super::title_list::pop_spare(wrapper) { let ext_spare = *(spare as *const usize); let reset_hr = super::alloc_pool::reset_list(spare as usize, alloc, ty.0, |pc_alloc| { + let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void); + let _pso_guard = real::UnadoptGuard::new(init_pso as *mut c_void); pc:: i32>(spare, PC_RESET)(spare, pc_alloc, init_pso) }); real::preserve_vtable(spare, ext_spare); @@ -2960,7 +2975,10 @@ unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_CO let emptied = |p: &*mut c_void| { let p = *p; let ext = *(p as *const usize); - let hr = super::alloc_pool::reset_list(p as usize, own, ty.0, |pc_alloc| pc:: i32>(p, PC_RESET)(p, pc_alloc, 0)); + let hr = super::alloc_pool::reset_list(p as usize, own, ty.0, |pc_alloc| { + let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void); + pc:: i32>(p, PC_RESET)(p, pc_alloc, 0) + }); real::preserve_vtable(p, ext); hr >= 0 }; @@ -3331,7 +3349,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if let Some((_, ref prior, _)) = kickoff_split { if !prior.is_empty() { execute_with_waits_on(q_raw, prior, |chunk| { - exec(q_raw, chunk.len() as u32, chunk.as_ptr()); + { + let _list_guards: Vec<_> = chunk.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect(); + exec(q_raw, chunk.len() as u32, chunk.as_ptr()); + } copy_scratch_submitted(q_raw, chunk); super::alloc_pool::executed(q_raw, chunk); signal_write64_fences(q_raw, chunk); @@ -3350,7 +3371,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } let one = [this]; - exec(q_raw, 1, one.as_ptr()); + { + let _list_guard = real::UnadoptGuard::new(this); + exec(q_raw, 1, one.as_ptr()); + } copy_scratch_submitted(q_raw, &one); super::alloc_pool::executed(q_raw, &one); signal_write64_pairs(q_raw, &write64_signals); @@ -3403,6 +3427,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let ext_closed = *(target as *const usize); let init_pso = super::pso_async::resolve_for_bind(bound_pso); let reset_hr = super::alloc_pool::reset_list(target as usize, alloc, list_type(target).0, |pc_alloc| { + let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void); + let _pso_guard = real::UnadoptGuard::new(init_pso as *mut c_void); pc:: i32>(target, PC_RESET)(target, pc_alloc, init_pso) }); real::preserve_vtable(target, ext_closed); @@ -4063,6 +4089,8 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 // (the PC allocator the title's allocator stands for now: `alloc_pool`) let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0); let hr = super::alloc_pool::reset_list(this as usize, alloc, ty, |pc_alloc| { + let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void); + let _pso_guard = real::UnadoptGuard::new(resolved as *mut c_void); pc:: i32>(this, PC_RESET)(this, pc_alloc, resolved) }); real::preserve_vtable(this, ext); @@ -6948,15 +6976,18 @@ mod tests { let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(slot(2)); let exec: unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) = std::mem::transmute(*(*(q.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); - let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); - let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let gate: ID3D12Fence = real::create_raw_fence(dev).unwrap(); + let done: ID3D12Fence = real::create_raw_fence(dev).unwrap(); // Close, then submit as ExecuteCommandLists does: the PC lists the title's list stands for let submit = || { assert_eq!(close(w), 0); let mut segs = Vec::new(); assert!(super::super::title_list::push_segments(w, &mut segs)); let again = super::super::alloc_pool::note_resubmits(q.as_raw(), &segs); - exec(q.as_raw(), segs.len() as u32, segs.as_ptr()); + { + let _list_guards: Vec<_> = segs.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect(); + exec(q.as_raw(), segs.len() as u32, segs.as_ptr()); + } super::super::alloc_pool::executed(q.as_raw(), &segs); (segs, again) }; @@ -7020,7 +7051,7 @@ mod tests { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); let raw: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc, None).unwrap(); - let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done: ID3D12Fence = real::create_raw_fence(&dev).unwrap(); let standin = 0x7E57_D001usize; static BUILD: AtomicBool = AtomicBool::new(false); @@ -7069,7 +7100,10 @@ mod tests { type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = std::mem::transmute(*(*(queue.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); - exec(queue.as_raw(), segs.len() as u32, segs.as_ptr()); + { + let _list_guards: Vec<_> = segs.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect(); + exec(queue.as_raw(), segs.len() as u32, segs.as_ptr()); + } queue.Signal(&done, 1).unwrap(); crate::gpu::fence::wait(&done, 1, &dev, None, 2000).expect("the split list runs"); @@ -7188,7 +7222,10 @@ mod tests { execute_with_waits_on(q_comp.as_raw(), &segs_c, |chunk| { type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = std::mem::transmute(*(*(q_comp.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); - exec(q_comp.as_raw(), chunk.len() as u32, chunk.as_ptr()); + { + let _guards: Vec<_> = chunk.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect(); + exec(q_comp.as_raw(), chunk.len() as u32, chunk.as_ptr()); + } signal_write64_fences(q_comp.as_raw(), chunk); if chunk.contains(&pc_c0) { cell_a.store(frame, Ordering::Release); @@ -7201,7 +7238,10 @@ mod tests { execute_with_waits_on(q_dir.as_raw(), &one_d, |chunk| { type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = std::mem::transmute(*(*(q_dir.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); - exec(q_dir.as_raw(), chunk.len() as u32, chunk.as_ptr()); + { + let _guards: Vec<_> = chunk.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect(); + exec(q_dir.as_raw(), chunk.len() as u32, chunk.as_ptr()); + } signal_write64_fences(q_dir.as_raw(), chunk); cell_b.store(frame, Ordering::Release); }); diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d47e67841e..3ab2538e41 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -947,7 +947,7 @@ unsafe fn new_presenter(queue: usize) -> Option { let actual_slots = if spare_alloc.is_some() { 2 } else { 1 }; let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).ok()?; list.Close().ok()?; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let fence: ID3D12Fence = super::real::create_raw_fence(dev).ok()?; let event = CreateEventW(None, false, false, None).ok()?; Some(Presenter { queue, dev: dev.clone(), sc: None, w: 0, h: 0, fmt: DXGI_FORMAT_UNKNOWN, diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 91085d3933..864110aaf8 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -622,14 +622,73 @@ struct Class { static CLASSES: Mutex> = Mutex::new(Vec::new()); static EXTS: Mutex>> = Mutex::new(None); +const EXT_FAST_CAP: usize = 64; +static EXT_FAST: [AtomicUsize; EXT_FAST_CAP] = [const { AtomicUsize::new(0) }; EXT_FAST_CAP]; +static EXT_FAST_N: AtomicUsize = AtomicUsize::new(0); +static NATIVE_FAST: [AtomicUsize; EXT_FAST_CAP] = [const { AtomicUsize::new(0) }; EXT_FAST_CAP]; +static NATIVE_FAST_N: AtomicUsize = AtomicUsize::new(0); +static NATIVE_FAST_LOCK: Mutex<()> = Mutex::new(()); + +fn register_ext(ext: usize) { + let mut g = EXTS.lock().unwrap(); + if g.get_or_insert_with(HashSet::new).insert(ext) { + let n = EXT_FAST_N.load(Ordering::Relaxed); + if n < EXT_FAST_CAP { + EXT_FAST[n].store(ext, Ordering::Relaxed); + EXT_FAST_N.store(n + 1, Ordering::Release); + } + } +} + +fn is_ext_fast(v: usize) -> bool { + let n = EXT_FAST_N.load(Ordering::Acquire); + for slot in &EXT_FAST[..n.min(EXT_FAST_CAP)] { + if slot.load(Ordering::Relaxed) == v { + return true; + } + } + n >= EXT_FAST_CAP && is_ext(v) +} + +fn register_native(orig: usize) { + if is_known_native(orig) { + return; + } + let _g = NATIVE_FAST_LOCK.lock().unwrap(); + let n = NATIVE_FAST_N.load(Ordering::Relaxed); + for slot in &NATIVE_FAST[..n.min(EXT_FAST_CAP)] { + if slot.load(Ordering::Relaxed) == orig { + return; + } + } + if n < EXT_FAST_CAP { + NATIVE_FAST[n].store(orig, Ordering::Relaxed); + NATIVE_FAST_N.store(n + 1, Ordering::Release); + } +} + +fn is_known_native(v: usize) -> bool { + let n = NATIVE_FAST_N.load(Ordering::Acquire); + for slot in &NATIVE_FAST[..n.min(EXT_FAST_CAP)] { + if slot.load(Ordering::Relaxed) == v { + return true; + } + } + false +} unsafe fn vt(obj: *mut c_void) -> *const usize { - *(obj as *const *const usize) + (*(obj as *const AtomicUsize)).load(Ordering::Acquire) as *const usize } /// Original function of `slot` for an adopted object. pub unsafe fn orig_fn(this: *mut c_void, slot: usize) -> usize { let ext = vt(this); + if crate::util::under_wine() && is_known_native(ext as usize) { + // Another thread's UnadoptGuard temporarily restored the native vtable on this + // shared object (e.g. a pipeline state); `ext` is already the original table. + return *ext.add(slot); + } let orig = *ext.sub(1) as *const usize; *orig.add(slot) } @@ -712,6 +771,101 @@ pub(super) unsafe fn readopt(obj: *mut c_void, kind: Kind) { *(obj as *mut usize) = class_for(obj, orig, kind); } +/// Active `UnadoptGuard` counts per object pointer so concurrent guards on a shared object +/// (such as a pipeline state, heap, or resource) keep the native vtable installed until the +/// last guard drops, while pinning a COM reference (`AddRef` before unadopt, hooked `Release` +/// after restoring the extended vtable) so a concurrent `Release` through the native vtable +/// cannot drop the refcount to zero and bypass XCL's final-release cleanup (`pso_release`, +/// `heap_release`, `res_release`, `cl_release`, `alloc_release`). +static UNADOPTED: Mutex>> = Mutex::new(None); + +/// Temporarily restores an adopted object's native vtable for a call into `d3d12core.dll` +/// (vkd3d-proton validates `iface->lpVtbl` on command allocators and command lists). +pub(crate) struct UnadoptGuard { + obj: *mut c_void, +} + +impl UnadoptGuard { + pub(crate) unsafe fn new(obj: *mut c_void) -> Option { + if !crate::util::under_wine() || obj.is_null() || (obj as usize) & 7 != 0 || !crate::gpu::shader::readable(obj as usize, 8) { + return None; + } + let mut g = UNADOPTED.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + if let Some((_, count)) = map.get_mut(&(obj as usize)) { + *count += 1; + return Some(Self { obj }); + } + let cur = (*(obj as *const AtomicUsize)).load(Ordering::Acquire); + if !is_ext_fast(cur) { + return None; + } + let orig = *(cur as *const usize).sub(1); + // Pin +1 COM reference via native AddRef before exposing `orig`, so any concurrent + // Release observing the native vtable sees refcount >= 2 and cannot finalize the object. + let add_ref: RefFn = std::mem::transmute(*(orig as *const usize).add(1)); + add_ref(obj); + register_native(orig); + (*(obj as *const AtomicUsize)).store(orig, Ordering::Release); + map.insert(obj as usize, (cur, 1)); + Some(Self { obj }) + } + + #[cfg(test)] + unsafe fn enter(obj: *mut c_void) -> Self { + let mut g = UNADOPTED.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + if let Some((_, count)) = map.get_mut(&(obj as usize)) { + *count += 1; + return Self { obj }; + } + let ext = (*(obj as *const AtomicUsize)).load(Ordering::Acquire); + let orig = *(ext as *const usize).sub(1); + let add_ref: RefFn = std::mem::transmute(*(orig as *const usize).add(1)); + add_ref(obj); + register_native(orig); + (*(obj as *const AtomicUsize)).store(orig, Ordering::Release); + map.insert(obj as usize, (ext, 1)); + Self { obj } + } +} + +impl Drop for UnadoptGuard { + fn drop(&mut self) { + let release_ext = { + let mut g = UNADOPTED.lock().unwrap(); + if let Some(map) = g.as_mut() { + if let Some((ext, count)) = map.get_mut(&(self.obj as usize)) { + *count -= 1; + if *count == 0 { + let ext = *ext; + map.remove(&(self.obj as usize)); + unsafe { + (*(self.obj as *const AtomicUsize)).store(ext, Ordering::Release); + } + Some(ext) + } else { + None + } + } else { + None + } + } else { + None + } + }; + // Release our pinned reference outside `UNADOPTED` via XCL's hooked Release slot so if + // another thread dropped the last title reference while the guard was active, the final + // 1 -> 0 transition always runs XCL's cleanup hook. + if let Some(ext) = release_ext { + unsafe { + let rel: RefFn = std::mem::transmute(*(ext as *const usize).add(2)); + rel(self.obj); + } + } + } +} + /// Give a genuine D3D12 object the extended vtable for `kind`. pub unsafe fn adopt(obj: *mut c_void, kind: Kind) { if obj.is_null() { @@ -834,7 +988,7 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { } let leaked: &'static [usize] = Box::leak(v.into_boxed_slice()); let ext = leaked.as_ptr() as usize + 8; - EXTS.lock().unwrap().get_or_insert_with(HashSet::new).insert(ext); + register_ext(ext); crate::xlog_info!( "D3D12.X: {} – {public} PC methods, {} internal slots under the guard, +{EXTRA_SLOTS} stubs ({kind:?}, PC vtable {})", iface.name, @@ -2399,6 +2553,20 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + let elem = if raw { + 4 + } else if b.StructureByteStride != 0 { + b.StructureByteStride + } else { + crate::gpu::desc::format_bytes(crate::gpu::desc::gfx10_format(v.Format).unwrap_or(22)) + }; + let uav_start = va.saturating_add(b.FirstElement.saturating_mul(elem as u64)) as usize; + let uav_bytes = (b.NumElements as u64).saturating_mul(elem as u64) as usize; + super::sparse::ensure_lazy_mapped(uav_start, uav_bytes); + let counter = (view.add(0x30) as *const u64).read_unaligned(); + if counter != 0 { + super::sparse::ensure_lazy_mapped(counter as usize, 4); + } return super::console_heap::write(&slot, &words); } dev_create_uav_x(this, resource_at(this, rdesc, va), std::ptr::null_mut(), &v, cpu); @@ -2902,7 +3070,12 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("Close", cl_close as usize), ("Reset", cl_reset as usize), ]), - Kind::CommandQueue => v.extend_from_slice(&[("Release", q_release as usize), ("ExecuteCommandLists", q_execute_command_lists as usize)]), + Kind::CommandQueue => v.extend_from_slice(&[ + ("Release", q_release as usize), + ("ExecuteCommandLists", q_execute_command_lists as usize), + ("Signal", q_signal_pc as usize), + ("Wait", q_wait_pc as usize), + ]), Kind::CommandAllocator => v.extend_from_slice(&[("Release", alloc_release as usize), ("Reset", alloc_reset as usize)]), Kind::Resource => v.extend_from_slice(&[ ("Release", res_release as usize), @@ -2983,7 +3156,11 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Reset"))); let resolved = super::pso_async::resolve_for_bind(initial_state as usize) as *mut c_void; - let hr = f(this, allocator, resolved); + let hr = { + let _alloc_guard = UnadoptGuard::new(allocator); + let _pso_guard = UnadoptGuard::new(resolved); + f(this, allocator, resolved) + }; preserve_vtable(this, ext); if hr >= 0 { super::list_x::on_pc_reset(this); @@ -3160,7 +3337,12 @@ macro_rules! creator { creator!(dev_create_command_queue, "CreateCommandQueue", Kind::CommandQueue, [a1]); creator!(dev_create_command_queue1, "CreateCommandQueue1", Kind::CommandQueue, [a1, a2]); creator!(dev_create_command_allocator, "CreateCommandAllocator", Kind::CommandAllocator, [a1]); -creator!(dev_create_command_list, "CreateCommandList", Kind::CommandList, [a1, a2, a3, a4]); +creator!(dev_create_command_list_inner, "CreateCommandList", Kind::CommandList, [a1, a2, a3, a4]); +pub(super) unsafe extern "system" fn dev_create_command_list(this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _alloc_guard = UnadoptGuard::new(a3 as *mut c_void); + let _pso_guard = UnadoptGuard::new(a4 as *mut c_void); + dev_create_command_list_inner(this, a1, a2, a3, a4, riid, ppv) +} creator!(dev_create_command_list1, "CreateCommandList1", Kind::CommandList, [a1, a2, a3]); /// Create a raw adopted PC `ID3D12GraphicsCommandList` without wrapping it in `title_list` @@ -3182,6 +3364,8 @@ pub(super) unsafe fn create_raw_pc_command_list( type F = unsafe extern "system" fn(*mut c_void, u32, D3D12_COMMAND_LIST_TYPE, usize, usize, *const GUID, *mut *mut c_void) -> HRESULT; let slot = layout::slot(layout::find("ID3D12Device")?, "CreateCommandList")?; let f: F = std::mem::transmute(*vt(dev).add(slot)); + let _alloc_guard = UnadoptGuard::new(alloc as *mut c_void); + let _pso_guard = UnadoptGuard::new(init_pso as *mut c_void); let hr = f(dev, 0, ty, alloc, init_pso, &iid, &mut out); if hr >= 0 && !out.is_null() { adopt(out, Kind::CommandList); @@ -3194,7 +3378,11 @@ creator!(dev_create_descriptor_heap, "CreateDescriptorHeap", Kind::DescriptorHea creator!(dev_create_committed_resource, "CreateCommittedResource", Kind::Resource, [a1, a2, a3, a4, a5]); creator!(dev_create_committed_resource1, "CreateCommittedResource1", Kind::Resource, [a1, a2, a3, a4, a5, a6]); creator!(dev_create_committed_resource2, "CreateCommittedResource2", Kind::Resource, [a1, a2, a3, a4, a5, a6]); -creator!(dev_create_placed_resource, "CreatePlacedResource", Kind::Resource, [a1, a2, a3, a4, a5]); +creator!(dev_create_placed_resource_inner, "CreatePlacedResource", Kind::Resource, [a1, a2, a3, a4, a5]); +pub(super) unsafe extern "system" fn dev_create_placed_resource(this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _heap_guard = UnadoptGuard::new(a1 as *mut c_void); + dev_create_placed_resource_inner(this, a1, a2, a3, a4, a5, riid, ppv) +} /// D3D12_RESOURCE_STATES the PC knows (as `list_x::PC_STATES`) pub(super) const PC_RESOURCE_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80 | 0x100 | 0x200 | 0x400 | 0x800 | 0x1000 | 0x2000 | 0xF_0000 | 0x20_0000 | 0x40_0000 | 0x80_0000 | 0x100_0000; @@ -3338,7 +3526,11 @@ unsafe fn pc_allocation_size(device: *mut c_void, d: &[u8; 0x38]) -> u64 { f(device, &mut r, 0, 1, &safe); r[0] } -creator!(dev_create_placed_resource1, "CreatePlacedResource1", Kind::Resource, [a1, a2, a3, a4, a5]); +creator!(dev_create_placed_resource1_inner, "CreatePlacedResource1", Kind::Resource, [a1, a2, a3, a4, a5]); +unsafe extern "system" fn dev_create_placed_resource1(this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _heap_guard = UnadoptGuard::new(a1 as *mut c_void); + dev_create_placed_resource1_inner(this, a1, a2, a3, a4, a5, riid, ppv) +} creator!(pc_create_reserved_resource, "CreateReservedResource", Kind::Resource, [a1, a2, a3]); creator!(pc_create_reserved_resource1, "CreateReservedResource1", Kind::Resource, [a1, a2, a3, a4]); @@ -3556,6 +3748,121 @@ unsafe extern "system" fn mem_heap_release(this: *mut c_void) -> u32 { } creator!(dev_create_fence_pc, "CreateFence", Kind::Fence, [a1, a2]); +/// Thin COM proxy around `ID3D12Fence1` used under Wine/vkd3d-proton so the underlying +/// fence's native `lpVtbl` stays intact (`vkd3d-proton` compares `fence->lpVtbl` against +/// `&d3d12_fence_vtbl` in `CommandQueue::Signal` / `Wait` and on its queue thread). +#[repr(C)] +struct FenceProxy { + vt: usize, + pc: *mut c_void, +} + +fn fence_proxy_vtable() -> usize { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| { + const SLOTS: usize = 32; + let mut v = vec![0usize; SLOTS]; + for slot in 0..12 { + // mov rcx, [rcx + 8]; mov rax, [rcx]; jmp [rax + slot * 8] + let mut c = vec![0x48u8, 0x8B, 0x49, 0x08, 0x48, 0x8B, 0x01, 0xFF, 0xA0]; + c.extend_from_slice(&((slot * 8) as u32).to_le_bytes()); + let p = crate::stubs::alloc_code(c.len()); + unsafe { std::ptr::copy_nonoverlapping(c.as_ptr(), p, c.len()) }; + v[slot] = p as usize; + } + v[0] = fence_proxy_qi as usize; + v[2] = fence_proxy_release as usize; + v[10] = fence_proxy_signal as usize; + v[12] = super::fence_x::completed_value_address as usize; + for slot in 13..SLOTS { + let (addr, _) = stubs::make_stub_info(DLL, &format!("ID3D12Fence1::#{slot} (not on PC)"), 0); + v[slot] = addr; + } + Box::leak(v.into_boxed_slice()).as_ptr() as usize + }) +} + +unsafe extern "system" fn fence_proxy_qi(this: *mut c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let pc = (*(this as *const FenceProxy)).pc; + let f: QiFn = std::mem::transmute(*vt(pc)); + let hr = f(pc, riid, ppv); + if hr >= 0 && !ppv.is_null() && *ppv == pc { + *ppv = this; + } else if hr == E_NOINTERFACE && !riid.is_null() { + let s = layout::guid_string(&*riid); + if UNKNOWN_IIDS.lock().unwrap().insert(s.clone()) { + crate::xlog_warn!("D3D12.X: QueryInterface({s}) – interface unknown on the PC (console-only?)"); + } + } + hr +} + +unsafe extern "system" fn fence_proxy_release(this: *mut c_void) -> u32 { + let pc = (*(this as *const FenceProxy)).pc; + let f: RefFn = std::mem::transmute(*vt(pc).add(2)); + let n = f(pc); + if n == 0 { + drop(Box::from_raw(this as *mut FenceProxy)); + } + n +} + +unsafe extern "system" fn fence_proxy_signal(this: *mut c_void, value: u64) -> HRESULT { + let pc = (*(this as *const FenceProxy)).pc; + let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(*vt(pc).add(10)); + let hr = f(pc, value); + super::fence_x::note_cpu_signal(this as usize); + hr +} + +unsafe fn wrap_fence_proxy(pc: *mut c_void) -> *mut c_void { + Box::into_raw(Box::new(FenceProxy { vt: fence_proxy_vtable(), pc })) as *mut c_void +} + +unsafe fn unwrap_fence(p: *mut c_void) -> *mut c_void { + if crate::util::under_wine() { unwrap_fence_proxy(p) } else { p } +} + +unsafe fn unwrap_fence_proxy(p: *mut c_void) -> *mut c_void { + if !p.is_null() && crate::gpu::shader::readable(p as usize, 16) && *(p as *const usize) == fence_proxy_vtable() { + (*(p as *const FenceProxy)).pc + } else { + p + } +} + +/// Create an un-adopted, un-proxied `ID3D12Fence` for XCL's own internal queue tracking +/// (`late_release`, `alloc_pool`, `list_x`, `cpu_writes`, `present`, `vram`, `drain_gpu`) +/// so under Wine/vkd3d-proton it can be signalled on raw internal queues (`sparse::queue()`) +/// and passed to native APIs without hitting `FenceProxy` vtable mismatches. +pub(super) unsafe fn create_raw_fence(dev: &ID3D12Device) -> windows::core::Result { + let raw = dev.as_raw(); + if crate::util::under_wine() && is_ext(vt(raw) as usize) { + type F = unsafe extern "system" fn(*mut c_void, u64, D3D12_FENCE_FLAGS, *const GUID, *mut *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "CreateFence"))); + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = f(raw, 0, D3D12_FENCE_FLAG_NONE, (&ID3D12Fence::IID as *const windows::core::GUID).cast(), &mut out); + if hr < 0 { + return Err(windows::core::Error::from_hresult(windows::core::HRESULT(hr))); + } + return Ok(ID3D12Fence::from_raw(out)); + } + dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) +} + +/// Remember a raw fence (e.g. a `list_x` cell fence created via `create_raw_fence` under Wine) +/// in `FENCES` so `end_title` signals it to `u64::MAX` before `drain_gpu`. No-op if already +/// tracked (e.g. off Wine, where `create_raw_fence` goes through `dev_create_fence`). +pub(super) unsafe fn track_end_title_fence(fence: &ID3D12Fence) { + let raw = fence.as_raw(); + let mut g = FENCES.write().unwrap(); + if !g.contains(&(raw as usize)) { + let add: RefFn = std::mem::transmute(*vt(raw).add(1)); + add(raw); + g.push(raw as usize); + } +} + /// fences created through the device (AddRef'd: they are released at the end only) /// (a read-write lock: `is_fence` reads it on every queue call, and `end_title` reads it with /// the title's threads suspended – a reader that holds it then blocks no other reader) @@ -3563,7 +3870,21 @@ static FENCES: std::sync::RwLock> = std::sync::RwLock::new(Vec::new() /// CreateFence: as on the PC; the fence is remembered for `end_title` unsafe extern "system" fn dev_create_fence(this: *mut c_void, value: usize, flags: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let hr = dev_create_fence_pc(this, value, flags, riid, ppv); + let hr = if crate::util::under_wine() { + type F = unsafe extern "system" fn(*mut c_void, usize, usize, *const GUID, *mut *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateFence"))); + let mut hr = f(this, value, flags, riid, ppv); + if hr == E_NOINTERFACE { + let iid = pc_iid(Kind::Fence); + hr = f(this, value, flags, &iid, ppv); + } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + *ppv = wrap_fence_proxy(*ppv); + } + hr + } else { + dev_create_fence_pc(this, value, flags, riid, ppv) + }; if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { let add: RefFn = std::mem::transmute(*vt(*ppv).add(1)); add(*ppv); @@ -6816,7 +7137,10 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); } let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); - f(this, res, desc, handle); + { + let _res_guard = UnadoptGuard::new(res); + f(this, res, desc, handle); + } super::present::note_rtv(handle, res); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); @@ -6878,7 +7202,10 @@ unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_v type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "SetPipelineState"))); let bound = super::pso_async::resolve(pso as usize); - f(this, bound as *mut c_void); + { + let _pso_guard = UnadoptGuard::new(bound as *mut c_void); + f(this, bound as *mut c_void); + } super::dred::mark_pipeline(this, pso as usize, bound); super::list_x::on_set_pipeline_state(this, pso as usize); } @@ -6894,10 +7221,13 @@ unsafe extern "system" fn cl_set_marker(this: *mut c_void, metadata: u32, data: unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ClearState"))); - let bound = super::pso_async::resolve_for_bind(pso as usize); - f(this, bound as *mut c_void); + let resolved = super::pso_async::resolve_for_bind(pso as usize); + { + let _pso_guard = UnadoptGuard::new(resolved as *mut c_void); + f(this, resolved as *mut c_void); + } if !pso.is_null() { - super::dred::mark_pipeline(this, pso as usize, bound); + super::dred::mark_pipeline(this, pso as usize, resolved); } super::list_x::on_clear_state(this, pso as usize); super::bind::clear_state(this, pso as usize); @@ -6949,6 +7279,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::sparse::forget_queue(this as usize); } n } @@ -6968,7 +7299,10 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void) -> HRESULT; let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "Reset"))); - let hr = f(raw); + let hr = { + let _alloc_guard = UnadoptGuard::new(raw); + f(raw) + }; if hr >= 0 { dispatch_chain::allocator_reset(raw as usize); } hr } @@ -7068,7 +7402,8 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a super::list_x::break_cycles_before_title_signal(this as usize, a1, a2 as u64); } let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(if older == 14 { PC_SIGNAL } else { PC_WAIT })); - let hr = f(this, a1, a2); + let raw_fence = unwrap_fence(a1 as *mut c_void) as usize; + let hr = f(this, raw_fence, a2); if hr >= 0 { if older == 14 { super::fence_x::note_queue_signal(a1, a2 as u64); @@ -7076,6 +7411,10 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a } else { super::fence_x::note_queue_wait(a1, a2 as u64); super::list_x::note_title_queue_wait(this as usize, a1, a2 as u64); + let raw_ptr = raw_fence as *mut c_void; + if let Some(fe) = ID3D12Fence::from_raw_borrowed(&raw_ptr) { + super::sparse::note_queue_wait(this as usize, fe.clone(), a2 as u64); + } } } hr as u32 as usize @@ -7154,6 +7493,28 @@ macro_rules! queue_slots { } queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35); +/// command queue #14 Signal (PC callers, e.g. XCL's own drain/present/sparse helpers) +unsafe extern "system" fn q_signal_pc(this: *mut c_void, fence: *mut c_void, value: u64) -> HRESULT { + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Signal"))); + f(this, unwrap_fence(fence), value) +} + +/// command queue #15 Wait (PC callers) +unsafe extern "system" fn q_wait_pc(this: *mut c_void, fence: *mut c_void, value: u64) -> HRESULT { + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Wait"))); + let raw = unwrap_fence(fence); + let hr = f(this, raw, value); + // Only record title fences: XCL's own internal waits (e.g. sparse::before_execute / + // vram::before_execute) always have their producer signal already submitted on an internal + // queue and must not make readback_after_execute treat the title queue as stalled. + if hr >= 0 && is_fence(fence as usize) { + if let Some(fe) = ID3D12Fence::from_raw_borrowed(&raw) { + super::sparse::note_queue_wait(this as usize, fe.clone(), value); + } + } + hr +} + /// command queue #23 SignalX(fence, value, flush flags): Signal with the console's cache flush /// options – the PC's Signal makes the queue's writes visible itself. (A stub that signalled /// nothing left Fortnite's render fences pending: its render thread waited, textures were @@ -7162,7 +7523,7 @@ unsafe extern "system" fn q_signal_x(this: *mut c_void, fence: *mut c_void, valu const PC_SIGNAL: usize = 14; super::list_x::break_cycles_before_title_signal(this as usize, fence as usize, value); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, PC_SIGNAL)); - let hr = f(this, fence, value); + let hr = f(this, unwrap_fence(fence), value); if hr >= 0 { super::fence_x::note_queue_signal(fence as usize, value); super::list_x::note_title_queue_signal(this as usize, fence as usize, value); @@ -7208,7 +7569,10 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis super::list_x::note_queue_for_lists(this as usize, &mapped); super::list_x::execute_with_waits_on(this, &mapped, |chunk| { let _ = super::alloc_pool::note_resubmits(this, chunk); - f(this, chunk.len() as u32, chunk.as_ptr()); + { + let _list_guards: Vec<_> = chunk.iter().filter_map(|&l| UnadoptGuard::new(l)).collect(); + f(this, chunk.len() as u32, chunk.as_ptr()); + } super::list_x::copy_scratch_submitted(this, chunk); super::alloc_pool::executed(this, chunk); super::list_x::signal_write64_fences(this, chunk); @@ -7235,7 +7599,7 @@ pub fn drain_gpu() { let qr = q as *mut c_void; let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qr) else { continue }; let submit = || { - let f: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) + let f: ID3D12Fence = create_raw_fence(dev) .map_err(|e| fence::api_error(dev, "CreateFence", e))?; q.Signal(&f, 1).map_err(|e| fence::api_error(dev, "Signal", e))?; Ok(f) @@ -8905,3 +9269,200 @@ void main() { } } +#[cfg(test)] +mod wine_vtable_tests { + use super::*; + use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + + #[test] + fn unadopt_guard_restores_native_vtable_and_reapplies_extended_on_drop() { + #[repr(C)] + struct FakeObj { + vt: usize, + refs: AtomicU32, + hook_releases: AtomicU32, + } + unsafe extern "system" fn native_add_ref(this: *mut c_void) -> u32 { + (*(this as *const FakeObj)).refs.fetch_add(1, Ordering::AcqRel) + 1 + } + unsafe extern "system" fn native_release(this: *mut c_void) -> u32 { + (*(this as *const FakeObj)).refs.fetch_sub(1, Ordering::AcqRel) - 1 + } + unsafe extern "system" fn hooked_release(this: *mut c_void) -> u32 { + (*(this as *const FakeObj)).hook_releases.fetch_add(1, Ordering::AcqRel); + native_release(this) + } + + // Place a zero word immediately before `orig_vt` (matching vkd3d-proton's layout) so a + // buggy `orig_fn` that reads `native[-1]` would dereference null instead of `orig_vt[2]`. + let mut orig_buf = [0usize; 9]; + orig_buf[1 + 1] = native_add_ref as usize; + orig_buf[1 + 2] = native_release as usize; + let orig_vt = unsafe { orig_buf.as_ptr().add(1) as usize }; + let mut ext_buf = [0usize; 9]; + ext_buf[0] = orig_vt; + ext_buf[1 + 1] = native_add_ref as usize; + ext_buf[1 + 2] = hooked_release as usize; + let ext_vt = unsafe { ext_buf.as_ptr().add(1) as usize }; + let mut fake = FakeObj { vt: ext_vt, refs: AtomicU32::new(1), hook_releases: AtomicU32::new(0) }; + let obj = &mut fake as *mut FakeObj as *mut c_void; + + unsafe { + assert_eq!(*(obj as *const usize), ext_vt); + { + let g1 = UnadoptGuard::enter(obj); + assert_eq!(*(obj as *const usize), orig_vt); + assert_eq!(fake.refs.load(Ordering::Acquire), 2, "guard must pin +1 COM ref"); + // Overlapping guard on the same shared object must keep the native vtable until + // the last guard drops. + let g2 = UnadoptGuard::enter(obj); + assert_eq!(fake.refs.load(Ordering::Acquire), 2, "nested guard reuses outer ref pin"); + drop(g1); + assert_eq!(*(obj as *const usize), orig_vt, "first drop must not restore ext while g2 is active"); + if crate::util::under_wine() { + assert_eq!(orig_fn(obj, 2), native_release as usize, "orig_fn must read native slot while guarded"); + } + drop(g2); + } + assert_eq!(*(obj as *const usize), ext_vt); + assert_eq!(fake.refs.load(Ordering::Acquire), 1, "refcount restored on drop"); + assert_eq!(fake.hook_releases.load(Ordering::Acquire), 1, "drop releases via hooked Release slot"); + } + } + + /// Regression for concurrent COM `Release` while `UnadoptGuard` temporarily exposes the + /// native vtable on a shared object: even if another thread loads the native vtable and calls + /// native `Release` directly, the guard's pinned reference keeps the object alive (rc >= 1) + /// and the guard's drop restores the extended vtable and performs the final 1 -> 0 release + /// through XCL's hooked `Release` so cleanup bookkeeping is never bypassed. + #[test] + fn concurrent_release_during_unadopt_guard_still_runs_hooked_cleanup() { + #[repr(C)] + struct SharedPso { + vt: usize, + refs: AtomicU32, + cleanup_ran: AtomicU32, + } + unsafe extern "system" fn native_add_ref(this: *mut c_void) -> u32 { + (*(this as *const SharedPso)).refs.fetch_add(1, Ordering::AcqRel) + 1 + } + unsafe extern "system" fn native_release(this: *mut c_void) -> u32 { + (*(this as *const SharedPso)).refs.fetch_sub(1, Ordering::AcqRel) - 1 + } + unsafe extern "system" fn hooked_pso_release(this: *mut c_void) -> u32 { + let f: RefFn = std::mem::transmute(orig_fn(this, 2)); + let rc = f(this); + if rc == 0 { + (*(this as *const SharedPso)).cleanup_ran.fetch_add(1, Ordering::AcqRel); + } + rc + } + + let mut orig_buf = [0usize; 9]; + orig_buf[1 + 1] = native_add_ref as usize; + orig_buf[1 + 2] = native_release as usize; + let orig_vt = unsafe { orig_buf.as_ptr().add(1) as usize }; + let mut ext_buf = [0usize; 9]; + ext_buf[0] = orig_vt; + ext_buf[1 + 1] = native_add_ref as usize; + ext_buf[1 + 2] = hooked_pso_release as usize; + let ext_vt = unsafe { ext_buf.as_ptr().add(1) as usize }; + + let mut pso = Box::new(SharedPso { vt: ext_vt, refs: AtomicU32::new(1), cleanup_ran: AtomicU32::new(0) }); + let raw = pso.as_mut() as *mut SharedPso as usize; + + unsafe { + let guard = UnadoptGuard::enter(raw as *mut c_void); + // Concurrent thread loads `*obj` during the guard window (seeing `orig_vt`) and + // invokes COM slot #2 (`Release`) directly through the native vtable. + let concurrent_rc = std::thread::spawn(move || { + let p = raw as *mut c_void; + let vt_seen = (*(p as *const AtomicUsize)).load(Ordering::Acquire); + assert_eq!(vt_seen, orig_vt, "concurrent caller observes native vtable during guard"); + let rel: RefFn = std::mem::transmute(*(vt_seen as *const usize).add(2)); + rel(p) + }) + .join() + .unwrap(); + assert_eq!(concurrent_rc, 1, "pinned ref must prevent native Release from finalizing the object"); + assert_eq!(pso.cleanup_ran.load(Ordering::Acquire), 0); + + drop(guard); + assert_eq!((*(raw as *const AtomicUsize)).load(Ordering::Acquire), ext_vt, "extended vtable restored"); + assert_eq!(pso.refs.load(Ordering::Acquire), 0, "final reference dropped on guard exit"); + assert_eq!(pso.cleanup_ran.load(Ordering::Acquire), 1, "hooked pso_release cleanup must run on 1 -> 0"); + } + } + + #[test] + fn fence_proxy_forwards_signal_unwraps_and_frees_on_final_release() { + #[repr(C)] + struct FakeFence { + vt: *const usize, + refs: AtomicU32, + signaled: AtomicU64, + } + unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 { + (*(this as *const FakeFence)).refs.fetch_sub(1, Ordering::Relaxed) - 1 + } + unsafe extern "system" fn fake_signal(this: *mut c_void, value: u64) -> HRESULT { + (*(this as *const FakeFence)).signaled.store(value, Ordering::Relaxed); + 0 + } + + let mut vt = [0usize; 16]; + vt[2] = fake_release as usize; + vt[10] = fake_signal as usize; + let fake = Box::new(FakeFence { vt: vt.as_ptr(), refs: AtomicU32::new(1), signaled: AtomicU64::new(0) }); + let raw = &*fake as *const FakeFence as *mut c_void; + + unsafe { + let proxy = wrap_fence_proxy(raw); + assert_ne!(proxy, raw); + assert_eq!(unwrap_fence_proxy(proxy), raw); + assert_eq!(unwrap_fence_proxy(raw), raw); + assert_eq!(*(raw as *const usize), vt.as_ptr() as usize, "native fence vtable must remain unmodified"); + + let signal_fn: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(*(*(proxy as *const *const usize)).add(10)); + assert_eq!(signal_fn(proxy, 42), 0); + assert_eq!(fake.signaled.load(Ordering::Relaxed), 42); + + let release_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(proxy as *const *const usize)).add(2)); + assert_eq!(release_fn(proxy), 0); + } + } + + #[test] + fn track_end_title_fence_registers_once_and_addrefs() { + #[repr(C)] + struct FakeFence { + vt: *const usize, + refs: AtomicU32, + } + unsafe extern "system" fn fake_add_ref(this: *mut c_void) -> u32 { + (*(this as *const FakeFence)).refs.fetch_add(1, Ordering::AcqRel) + 1 + } + unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 { + (*(this as *const FakeFence)).refs.fetch_sub(1, Ordering::AcqRel) - 1 + } + + let mut vt = [0usize; 4]; + vt[1] = fake_add_ref as usize; + vt[2] = fake_release as usize; + let fake = Box::new(FakeFence { vt: vt.as_ptr(), refs: AtomicU32::new(1) }); + let raw = &*fake as *const FakeFence as *mut c_void; + + unsafe { + let borrowed = ID3D12Fence::from_raw_borrowed(&raw).expect("borrowed fake fence"); + assert!(!is_fence(raw as usize)); + track_end_title_fence(borrowed); + assert!(is_fence(raw as usize), "tracked raw fence must be visible to end_title"); + assert_eq!(fake.refs.load(Ordering::Acquire), 2, "tracking must AddRef once"); + track_end_title_fence(borrowed); + assert_eq!(fake.refs.load(Ordering::Acquire), 2, "duplicate tracking must be a no-op"); + FENCES.write().unwrap().retain(|&f| f != raw as usize); + fake_release(raw); + assert_eq!(fake.refs.load(Ordering::Acquire), 1); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b7560f861e..ba5b974f48 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -19,7 +19,7 @@ use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; use std::hash::{BuildHasherDefault, Hasher}; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::Mutex; use windows::core::Interface; @@ -258,6 +258,12 @@ struct State { rb_alloc: ID3D12CommandAllocator, rb_list: ID3D12GraphicsCommandList, rb_last_fence: u64, + /// monotonic sequence bumped each time `readback_ranges` records copied segments in `last_rb` + rb_seq: u64, + /// `(seg_start, seg_len) -> (rb_seq, hash)` of segments written by a recent readback while + /// another async/deferred readback was in flight, so consecutive deferred readbacks on the + /// same range do not mistake an earlier readback's copy for a newer CPU write + last_rb: FxHashMap<(usize, u8), (u64, u64)>, /// the fence value each title queue last waited for waited: FxHashMap, /// `mapped` as sorted (start, end) runs (None: to be made again) @@ -319,6 +325,18 @@ fn chunk_hash(c: &[u8]) -> u64 { hash_words(read_chunk_words(c)) } +/// hash of a 1..=64 byte segment within a single 64-byte chunk +#[inline(always)] +fn slice_hash(bytes: &[u8]) -> u64 { + debug_assert!(!bytes.is_empty() && bytes.len() <= CHUNK); + if bytes.len() == CHUNK { + return chunk_hash(bytes); + } + let mut buf = [0u8; CHUNK]; + buf[..bytes.len()].copy_from_slice(bytes); + chunk_hash(&buf) +} + #[inline(always)] fn push_run(out: &mut Vec<(usize, usize)>, addr: usize, len: usize) { match out.last_mut() { @@ -427,6 +445,37 @@ pub fn pool_bytes() -> (usize, usize) { /// every page committed so far. Like `committed` / `decommitted` with a state, a range counts /// every page it touches; `init` commits them once the windows exist. static EARLY: Mutex> = Mutex::new(BTreeMap::new()); +/// Ranges committed on the CPU in sparse windows whose VRAM tiles are mapped lazily on first +/// non-zero CPU write (`alloc_lazy`) or GPU write target registration, avoiding eager VRAM +/// allocation for untouched pages or GPU-owned render targets placed inside large title heaps. +static LAZY_RANGES: Mutex> = Mutex::new(BTreeMap::new()); +static LAZY_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +fn in_lazy_range(lazy: &BTreeMap, a: usize) -> bool { + lazy.range(..=a).next_back().is_some_and(|(_, &e)| a < e) +} + +fn lazy_overlaps_tile(lazy: &BTreeMap, t: usize) -> bool { + lazy.range(..t.saturating_add(TILE)).next_back().is_some_and(|(_, &e)| e > t) +} + +fn lazy_tile_holes(lazy: &BTreeMap, t: usize) -> u16 { + let mut holes = 0u16; + for k in 0..PAGES_PER_TILE { + if !in_lazy_range(lazy, t + k * PAGE) { + holes |= 1u16 << k; + } + } + holes +} + +fn page_has_nonzero(bytes: &[u8]) -> bool { + let mut chunks = bytes.chunks_exact(8); + if chunks.any(|c| u64::from_ne_bytes(c.try_into().unwrap()) != 0) { + return true; + } + chunks.remainder().iter().any(|&b| b != 0) +} /// The pages `[a, a + n)` touches, as `[start, end)`. fn page_span(a: usize, n: usize) -> (usize, usize) { @@ -523,8 +572,8 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { } let made = (|| -> windows::core::Result { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let fence: ID3D12Fence = super::real::create_raw_fence(dev)?; + let rb_fence: ID3D12Fence = super::real::create_raw_fence(dev)?; let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; let mut slots = Vec::with_capacity(UPLOAD_SLOTS); for _ in 0..UPLOAD_SLOTS { @@ -572,6 +621,8 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { rb_alloc, rb_list, rb_last_fence: 0, + rb_seq: 0, + last_rb: FxHashMap::default(), waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), @@ -587,6 +638,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { let old = STATE.lock().unwrap().replace(s); drop(old); drop(old_queue); + MAPPED_GEN.fetch_add(1, Ordering::Release); for (a, b) in std::mem::take(&mut *EARLY.lock().unwrap()) { committed(a, b - a); } @@ -1018,14 +1070,59 @@ impl State { } } + /// Snapshot the current CPU bytes of committed 64-byte-bounded segments in `ranges` (sorted, + /// non-overlapping) so a later asynchronous or deferred `readback_ranges` can skip any segment + /// the title's CPU has modified since this job was recorded. + unsafe fn snapshot_ranges(&self, ranges: &[(usize, usize)]) -> RbSnapshot { + let mut chunks = Vec::new(); + for &(a, n) in ranges { + if n == 0 { + continue; + } + let mut at = a; + let end = a.saturating_add(n); + while at < end { + let pg = at & !(PAGE - 1); + let t = pg & !(TILE - 1); + let idx = (pg - t) / PAGE; + let page_end = (pg + PAGE).min(end); + if self.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { + while at < page_end { + let chunk_end = ((at & !(CHUNK - 1)) + CHUNK).min(page_end); + let step = chunk_end - at; + let h = slice_hash(std::slice::from_raw_parts(at as *const u8, step)); + chunks.push((at, step as u8, h)); + at = chunk_end; + } + } else { + at = page_end; + } + } + } + RbSnapshot { seq: self.rb_seq, chunks } + } + /// Copy `ranges` (address, bytes) from sparse VRAM back into the CPU view and refresh /// `sent` hashes. Caller has already ordered `self.queue` after any GPU writes if needed. - unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)]) { + /// When `snapshot` is `Some`, each 64-byte-bounded segment is copied only if its current CPU + /// bytes still match the snapshot (or an intervening readback recorded after `snapshot.seq`), + /// so a newer title CPU write is never overwritten by a late/deferred readback. + unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)], snapshot: Option<&RbSnapshot>) { + const LAST_RB_CAP: usize = 16_384; let Some((rb, p)) = self.readback_buf() else { return }; + let other_in_flight = IN_FLIGHT_RB.load(Ordering::Acquire) > usize::from(snapshot.is_some()); + let mut snap_idx = 0usize; + let mut next_seq = 0u64; let mut pending: Vec<(usize, usize, usize)> = Vec::new(); // (va, rb_off, chunk) let mut used = 0usize; let mut open = false; - let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| { + let flush_and_copy = |s: &mut State, + open: &mut bool, + pending: &mut Vec<(usize, usize, usize)>, + used: &mut usize, + snap_idx: &mut usize, + next_seq: &mut u64, + p: *mut u8| { if *open { *open = false; if s.rb_list.Close().is_ok() { @@ -1040,6 +1137,18 @@ impl State { s.wait_for(s.value); s.reclaim_ring(); } + let mut cur_chunk = usize::MAX; + let mut chunk_copied = false; + let mut chunk_skipped = false; + let flush_chunk_sent = + |s: &mut State, cur_chunk: &mut usize, chunk_copied: &mut bool, chunk_skipped: &mut bool| { + if *cur_chunk != usize::MAX && *chunk_copied && !*chunk_skipped { + s.sync_sent_range(*cur_chunk, CHUNK); + } + *cur_chunk = usize::MAX; + *chunk_copied = false; + *chunk_skipped = false; + }; for &(dst, off, len) in pending.iter() { // copy only committed (non-hole) bytes let mut at = dst; @@ -1049,14 +1158,79 @@ impl State { let pg = at & !(PAGE - 1); let t = pg & !(TILE - 1); let idx = (pg - t) / PAGE; - let step = (pg + PAGE).min(end) - at; + let page_end = (pg + PAGE).min(end); if s.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { - std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); + if let Some(snap) = snapshot { + while at < page_end { + let chunk_base = at & !(CHUNK - 1); + let chunk_end = (chunk_base + CHUNK).min(page_end); + let step = chunk_end - at; + if chunk_base != cur_chunk { + flush_chunk_sent(s, &mut cur_chunk, &mut chunk_copied, &mut chunk_skipped); + cur_chunk = chunk_base; + } + while *snap_idx < snap.chunks.len() && snap.chunks[*snap_idx].0 < at { + *snap_idx += 1; + } + let expected = snap.chunks.get(*snap_idx).and_then(|&(a, l, h)| { + (a == at && l as usize == step).then_some(h) + }); + let cur_hash = slice_hash(std::slice::from_raw_parts(at as *const u8, step)); + let allow_copy = expected.is_some_and(|h| { + cur_hash == h + || s.last_rb + .get(&(at, step as u8)) + .is_some_and(|&(rb_seq, rb_hash)| rb_seq > snap.seq && rb_hash == cur_hash) + }); + if allow_copy { + std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); + chunk_copied = true; + if other_in_flight && s.last_rb.len() < LAST_RB_CAP { + if *next_seq == 0 { + s.rb_seq += 1; + *next_seq = s.rb_seq; + } + let copied_hash = slice_hash(std::slice::from_raw_parts(at as *const u8, step)); + s.last_rb.insert((at, step as u8), (*next_seq, copied_hash)); + } + } else { + chunk_skipped = true; + } + at = chunk_end; + src_off += step; + } + } else { + let step = page_end - at; + std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); + if other_in_flight && s.last_rb.len() < LAST_RB_CAP { + let mut seg = at; + while seg < page_end && s.last_rb.len() < LAST_RB_CAP { + let seg_end = ((seg & !(CHUNK - 1)) + CHUNK).min(page_end); + let seg_len = seg_end - seg; + if *next_seq == 0 { + s.rb_seq += 1; + *next_seq = s.rb_seq; + } + let copied_hash = slice_hash(std::slice::from_raw_parts(seg as *const u8, seg_len)); + s.last_rb.insert((seg, seg_len as u8), (*next_seq, copied_hash)); + seg = seg_end; + } + } + at = page_end; + src_off += step; + } + } else { + let step = page_end - at; + at = page_end; + src_off += step; } - at += step; - src_off += step; } - s.sync_sent_range(dst, len); + if snapshot.is_none() { + s.sync_sent_range(dst, len); + } + } + if snapshot.is_some() { + flush_chunk_sent(s, &mut cur_chunk, &mut chunk_copied, &mut chunk_skipped); } pending.clear(); *used = 0; @@ -1076,8 +1250,10 @@ impl State { done += (n - done).min(to_tile_end); continue; } - if used == READBACK_STAGING { - flush_and_copy(self, &mut open, &mut pending, &mut used, p); + // Flush with at least one full tile of headroom so `chunk` stops only on a tile + // boundary or range end and never splits a 64-byte snapshot segment across flushes. + if used > READBACK_STAGING - TILE { + flush_and_copy(self, &mut open, &mut pending, &mut used, &mut snap_idx, &mut next_seq, p); } let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); @@ -1094,7 +1270,10 @@ impl State { } } if open { - flush_and_copy(self, &mut open, &mut pending, &mut used, p); + flush_and_copy(self, &mut open, &mut pending, &mut used, &mut snap_idx, &mut next_seq, p); + } + if !other_in_flight { + self.last_rb.clear(); } } @@ -1194,6 +1373,56 @@ impl State { } } +/// Allocate a zeroed, write-watched block in the sparse VRAM windows (never straddling a +/// 4 GiB window boundary when `size <= 4 GiB`). Commits CPU pages immediately but defers +/// mapping 64 KiB VRAM tiles until the CPU writes non-zero data (or `place_buffer` pins them). +pub unsafe fn alloc_lazy(size: usize, align: usize) -> Option<(usize, usize)> { + let u = crate::gpu::uma::get()?; + let (addr, rounded) = u.sparse_alloc(size, align)?; + if VirtualAlloc(addr as *const c_void, rounded, MEM_COMMIT, PAGE_READWRITE).is_null() { + u.sparse_release(addr); + return None; + } + let (start, end) = page_span(addr, rounded); + early_add(&mut LAZY_RANGES.lock().unwrap(), start, end); + LAZY_ACTIVE.store(true, Ordering::Release); + if let Some(s) = STATE.lock().unwrap().as_mut() { + s.runs = None; + } + MAPPED_GEN.fetch_add(1, Ordering::Release); + Some((addr, rounded)) +} + +/// Ensure any lazily-allocated sparse tiles overlapping `[a, a + n)` are backed by VRAM +/// (called when the GPU is about to write directly to a buffer UAV or memory-op target). +pub unsafe fn ensure_lazy_mapped(a: usize, n: usize) { + if n == 0 || !LAZY_ACTIVE.load(Ordering::Acquire) { + return; + } + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if s.window_index(a).is_none() { + return; + } + let lazy = LAZY_RANGES.lock().unwrap(); + if lazy.is_empty() { + return; + } + let first = a & !(TILE - 1); + let end = a.saturating_add(n); + let mut t = first; + while t < end { + if !s.mapped.contains_key(&t) && lazy_overlaps_tile(&lazy, t) { + let holes = lazy_tile_holes(&lazy, t); + s.ensure_mapped(t, TILE, |_| holes); + } + match t.checked_add(TILE) { + Some(next) => t = next, + None => break, + } + } +} + /// Allocate a zeroed, write-watched block in the sparse VRAM windows (never straddling a /// 4 GiB window boundary when `size <= 4 GiB`). Commits the CPU pages and maps VRAM tiles /// (or queues them until the D3D12 device exists). Returns `(address, rounded_size)`. @@ -1244,14 +1473,246 @@ pub fn queue() -> Option { QUEUE.lock().unwrap().clone() } +#[derive(Clone, Debug, Default)] +struct RbSnapshot { + seq: u64, + /// Sorted by address: `(addr, len, hash)` for each committed 64-byte-bounded segment in + /// `ranges` at the moment the readback job was recorded. + chunks: Vec<(usize, u8, u64)>, +} + +/// Number of `RbJob`s currently queued or running across all per-queue readback workers. +static IN_FLIGHT_RB: AtomicUsize = AtomicUsize::new(0); + +struct InFlightGuard; + +impl InFlightGuard { + fn acquire() -> Self { + IN_FLIGHT_RB.fetch_add(1, Ordering::AcqRel); + Self + } +} + +impl Drop for InFlightGuard { + fn drop(&mut self) { + IN_FLIGHT_RB.fetch_sub(1, Ordering::AcqRel); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RbStatus { + Pending, + Completed, + Deferred, +} + +struct RbJob { + fence: ID3D12Fence, + value: u64, + ranges: Vec<(usize, usize)>, + snapshot: RbSnapshot, + done: Option, std::sync::Condvar)>>, + _in_flight: InFlightGuard, +} + +// SAFETY: ID3D12Fence is a free-threaded COM object; ranges and Condvar are Send. +unsafe impl Send for RbJob {} + +struct RbQueueState { + fence: ID3D12Fence, + value: u64, + tx: std::sync::mpsc::Sender, +} + +unsafe impl Send for RbQueueState {} + +struct QueueWait(ID3D12Fence, u64); + +// SAFETY: ID3D12Fence is a free-threaded COM object. +unsafe impl Send for QueueWait {} + +static RB_QUEUES: Mutex>> = Mutex::new(None); +static QUEUE_WAITS: Mutex>>> = Mutex::new(None); + +/// Record an active GPU `queue.Wait(&fence, value)` on `queue` so `readback_after_execute` +/// knows when `queue` is blocked on an unsatisfied fence and must dispatch asynchronously. +pub unsafe fn note_queue_wait(queue: usize, fence: ID3D12Fence, value: u64) { + if value == 0 || fence.GetCompletedValue() >= value { + return; + } + let mut g = QUEUE_WAITS.lock().unwrap(); + let v = g.get_or_insert_with(FxHashMap::default).entry(queue).or_default(); + v.retain(|w| w.0.GetCompletedValue() < w.1); + v.push(QueueWait(fence, value)); +} + +unsafe fn queue_has_unsatisfied_wait(queue: usize) -> bool { + let mut g = QUEUE_WAITS.lock().unwrap(); + let Some(m) = g.as_mut() else { return false }; + let Some(v) = m.get_mut(&queue) else { return false }; + v.retain(|w| w.0.GetCompletedValue() < w.1); + if v.is_empty() { + m.remove(&queue); + return false; + } + true +} + +/// Drop per-queue readback and wait-tracking state when a title command queue is released. +pub fn forget_queue(queue: usize) { + if let Some(m) = QUEUE_WAITS.lock().unwrap().as_mut() { + m.remove(&queue); + } + if let Some(m) = RB_QUEUES.lock().unwrap().as_mut() { + m.remove(&queue); + } +} + +unsafe fn wait_fence_ms(fence: &ID3D12Fence, target: u64, event: HANDLE, timeout_ms: u32) -> bool { + if target == 0 || fence.GetCompletedValue() >= target { + return true; + } + let _ = windows::Win32::System::Threading::ResetEvent(event); + if fence.SetEventOnCompletion(target, event).is_err() { + return fence.GetCompletedValue() >= target; + } + let deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms as u64); + while fence.GetCompletedValue() < target { + let rem = deadline.saturating_duration_since(std::time::Instant::now()); + if rem.is_zero() { + return false; + } + let ms = rem.as_millis().clamp(1, u32::MAX as u128) as u32; + windows::Win32::System::Threading::WaitForSingleObject(event, ms); + } + true +} + +const RB_WAIT_TIMEOUT_MS: u32 = 5000; + +fn notify_rb_status(done: Option, std::sync::Condvar)>>, status: RbStatus) { + if let Some(done) = done { + *done.0.lock().unwrap() = status; + done.1.notify_all(); + } +} + +fn spawn_rb_worker(queue_id: usize) -> std::sync::mpsc::Sender { + spawn_rb_worker_with(queue_id, RB_WAIT_TIMEOUT_MS, |ranges, snapshot| unsafe { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + s.readback_ranges(ranges, Some(snapshot)); + } + }) +} + +fn spawn_rb_worker_with(queue_id: usize, timeout_ms: u32, mut readback: F) -> std::sync::mpsc::Sender +where + F: FnMut(&[(usize, usize)], &RbSnapshot) + Send + 'static, +{ + let (tx, rx) = std::sync::mpsc::channel::(); + let name = format!("xcl-sparse-rb-{queue_id:x}"); + let spawned = std::thread::Builder::new().name(name).spawn(move || unsafe { + let Ok(event) = windows::Win32::System::Threading::CreateEventW(None, false, false, None) else { + return; + }; + let mut deferred: VecDeque = VecDeque::new(); + let drain_deferred = |deferred: &mut VecDeque, readback: &mut F| { + while let Some(front) = deferred.front() { + let completed = front.fence.GetCompletedValue(); + if completed == u64::MAX { + deferred.clear(); + break; + } + if completed < front.value { + break; + } + let ready = deferred.pop_front().unwrap(); + readback(&ready.ranges, &ready.snapshot); + } + }; + loop { + drain_deferred(&mut deferred, &mut readback); + let recv = if deferred.is_empty() { + rx.recv().map_err(|_| std::sync::mpsc::RecvTimeoutError::Disconnected) + } else { + rx.recv_timeout(std::time::Duration::from_millis(20)) + }; + let job = match recv { + Ok(job) => job, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue, + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + }; + // Wait for the title queue outside `STATE` and without stalling `s.queue`: + // a queue may carry a wait-before-signal `Wait64BitValueX` whose producer has not + // been submitted yet on the caller's thread. + let wait_ok = wait_fence_ms(&job.fence, job.value, event, timeout_ms); + let completed = job.fence.GetCompletedValue(); + if completed == u64::MAX { + deferred.clear(); + notify_rb_status(job.done, RbStatus::Deferred); + continue; + } + if wait_ok && completed >= job.value { + drain_deferred(&mut deferred, &mut readback); + readback(&job.ranges, &job.snapshot); + notify_rb_status(job.done, RbStatus::Completed); + } else { + drain_deferred(&mut deferred, &mut readback); + static LATE: AtomicU64 = AtomicU64::new(0); + let k = LATE.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_warn!( + "sparse: readback for queue {queue_id:#x} timed out after {timeout_ms} ms (fence at {completed}, wanted {}); deferred for retry", + job.value + ); + } + // Do not claim synchronous completion: wake the caller as Deferred and retain + // the job so CPU coherence catches up once the fence completes. + notify_rb_status(job.done, RbStatus::Deferred); + deferred.push_back(RbJob { done: None, ..job }); + } + } + // Drain any remaining deferred jobs on queue teardown while fences complete, bounded + // so a permanently unsignaled fence cannot leak the worker thread indefinitely. + let shutdown_deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms as u64); + while let Some(front) = deferred.front() { + let completed = front.fence.GetCompletedValue(); + if completed == u64::MAX { + break; + } + if completed >= front.value { + let ready = deferred.pop_front().unwrap(); + readback(&ready.ranges, &ready.snapshot); + continue; + } + let rem = shutdown_deadline.saturating_duration_since(std::time::Instant::now()); + if rem.is_zero() { + break; + } + let ms = rem.as_millis().clamp(1, u32::MAX as u128) as u32; + let _ = wait_fence_ms(&front.fence, front.value, event, ms); + } + let _ = CloseHandle(event); + }); + if let Err(e) = spawned { + crate::xlog_error!("sparse: failed to spawn readback thread for queue {queue_id:#x}: {e}"); + } + tx +} + +/// Schedule a readback of GPU-written sparse ranges after `queue` finishes its submission. +/// Always waits on `queue`'s fence outside `STATE.lock()` and without stalling +/// `sparse::State::queue`. When `queue` is blocked on an unsatisfied `queue.Wait` +/// (wait-before-signal `Wait64BitValueX` whose producer is submitted later on this thread), +/// returns immediately while the per-queue worker finishes asynchronously; otherwise waits for +/// the worker so CPU reads immediately after a GPU fence wait see the updated bytes. pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)]) { if ranges.is_empty() { return; } - let mut g = lock_state(); - let Some(s) = g.as_mut() else { return }; - s.note_queue(queue); - let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); + let Some(u) = crate::gpu::uma::get() else { return }; + let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && u.is_sparse(a)).collect(); if filtered.is_empty() { return; } @@ -1266,13 +1727,65 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz _ => merged.push((a, n)), } } - s.rb_value += 1; - let v = s.rb_value; - if queue.Signal(&s.rb_fence, v).is_ok() { - let _ = s.queue.Wait(&s.rb_fence, v); - super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); + let qid = queue.as_raw() as usize; + let stalled = queue_has_unsatisfied_wait(qid); + let done = (!stalled).then(|| std::sync::Arc::new((Mutex::new(RbStatus::Pending), std::sync::Condvar::new()))); + let (tx, fence, value, is_new) = { + let mut g = RB_QUEUES.lock().unwrap(); + let m = g.get_or_insert_with(FxHashMap::default); + let mut is_new = false; + let entry = match m.entry(qid) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(v) => { + let mut dev: Option = None; + if queue.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let Ok(fence) = super::real::create_raw_fence(&dev) else { return }; + let tx = spawn_rb_worker(qid); + is_new = true; + v.insert(RbQueueState { fence, value: 0, tx }) + } + }; + entry.value += 1; + if queue.Signal(&entry.fence, entry.value).is_err() { + return; + } + (entry.tx.clone(), entry.fence.clone(), entry.value, is_new) + }; + let (snapshot, in_flight) = { + let mut g = lock_state(); + let Some(s) = g.as_mut() else { return }; + if is_new { + s.note_queue(queue); + } + (s.snapshot_ranges(&merged), InFlightGuard::acquire()) + }; + let job = RbJob { fence, value, ranges: merged, snapshot, done: done.clone(), _in_flight: in_flight }; + if tx.send(job).is_err() { + return; + } + if let Some(done) = done { + let (lk, cv) = &*done; + let (status, _) = cv + .wait_timeout_while( + lk.lock().unwrap(), + std::time::Duration::from_millis(RB_WAIT_TIMEOUT_MS as u64 + 500), + |status| *status == RbStatus::Pending, + ) + .unwrap(); + if *status != RbStatus::Completed { + static SYNC_DEFERRED: AtomicU64 = AtomicU64::new(0); + let k = SYNC_DEFERRED.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_warn!( + "sparse: synchronous readback on queue {qid:#x} deferred ({:?}); CPU coherence will catch up when the fence completes", + *status + ); + } + } } - s.readback_ranges(&merged); } /// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with @@ -1318,7 +1831,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { if !dirty_runs.is_empty() { s.upload_dirty(&dirty_runs); } - s.readback_ranges(&[(va, len)]); + s.readback_ranges(&[(va, len)], None); } /// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that @@ -1343,13 +1856,29 @@ pub unsafe fn decommitted(a: usize, n: usize) { if n == 0 { return; } + let (start, end) = page_span(a, n); + let lazy_changed = { + let mut lazy = LAZY_RANGES.lock().unwrap(); + let before = lazy.len(); + let had = lazy.range(..end).next_back().is_some_and(|(_, &e)| e > start); + if had { + early_remove(&mut lazy, start, end); + } + had || lazy.len() != before + }; let mut g = lock_state(); let Some(s) = g.as_mut() else { - let (start, end) = page_span(a, n); early_remove(&mut EARLY.lock().unwrap(), start, end); + if lazy_changed { + MAPPED_GEN.fetch_add(1, Ordering::Release); + } return; }; s.decommit_range(a, n); + if lazy_changed { + s.runs = None; + MAPPED_GEN.fetch_add(1, Ordering::Release); + } } impl State { @@ -1428,7 +1957,7 @@ impl State { if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self.dev.as_raw()) { return true; } - match self.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { + match super::real::create_raw_fence(&self.dev) { Ok(fence) => { self.queue_fences.insert(key, (q.clone(), fence, 0)); true @@ -1524,13 +2053,17 @@ pub fn mapped_ranges() -> Vec<(usize, usize)> { let mut g = lock_state(); let Some(s) = g.as_mut() else { return Vec::new() }; if s.runs.is_none() { - let mut tiles: Vec = s.mapped.keys().copied().collect(); - tiles.sort_unstable(); + let mut spans: Vec<(usize, usize)> = s.mapped.keys().map(|&t| (t, t + TILE)).collect(); + { + let lazy = LAZY_RANGES.lock().unwrap(); + spans.extend(lazy.iter().map(|(&a, &b)| (a, b))); + } + spans.sort_unstable(); let mut runs: Vec<(usize, usize)> = Vec::new(); - for t in tiles { + for (a, b) in spans { match runs.last_mut() { - Some(last) if last.1 == t => last.1 = t + TILE, - _ => runs.push((t, t + TILE)), + Some(last) if a <= last.1 => last.1 = last.1.max(b), + _ => runs.push((a, b)), } } s.runs = Some(runs); @@ -1564,12 +2097,14 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: } let t_locked = std::time::Instant::now(); PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Ordering::Relaxed); - let zero_runs = std::mem::take(&mut s.to_zero); + let mut zero_runs = std::mem::take(&mut s.to_zero); for &(a, n) in &zero_runs { s.clear_sent_range(a, n); } let mut dirty_runs = std::mem::take(&mut s.scratch_runs); dirty_runs.clear(); + let lazy = LAZY_RANGES.lock().unwrap(); + let has_lazy = !lazy.is_empty(); let mut i = 0; while i < dirty.len() { let a = dirty[i]; @@ -1579,25 +2114,60 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: n += page; i += 1; } - // only what has video memory (committed tiles of a sparse window) + // only what has video memory (committed tiles of a sparse window), lazily mapping tiles + // in `LAZY_RANGES` on the first non-zero CPU write let mut x = a; while x < a + n { let t = x & !(TILE - 1); let end = (t + TILE).min(a + n); - if let Some(entry) = s.mapped.get_mut(&t) { + let mut just_mapped = false; + if !s.mapped.contains_key(&t) && has_lazy && lazy_overlaps_tile(&lazy, t) { let mut pg = x & !(PAGE - 1); + let mut any_nz = false; while pg < end { - let idx = (pg - t) / PAGE; - if entry.holes & (1u16 << idx) == 0 { - let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); - scan_page(bytes, pg, &mut entry.sent[idx], &mut dirty_runs); + if in_lazy_range(&lazy, pg) && page_has_nonzero(std::slice::from_raw_parts(pg as *const u8, PAGE)) { + any_nz = true; + break; } pg += PAGE; } + if any_nz { + let holes = lazy_tile_holes(&lazy, t); + s.ensure_mapped(t, TILE, |_| holes); + just_mapped = true; + if let Some(entry) = s.mapped.get_mut(&t) { + for idx in 0..PAGES_PER_TILE { + if entry.holes & (1u16 << idx) == 0 { + let pg = t + idx * PAGE; + let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); + scan_page(bytes, pg, &mut entry.sent[idx], &mut dirty_runs); + } + } + } + } + } + if !just_mapped { + if let Some(entry) = s.mapped.get_mut(&t) { + let mut pg = x & !(PAGE - 1); + while pg < end { + let idx = (pg - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); + scan_page(bytes, pg, &mut entry.sent[idx], &mut dirty_runs); + } + pg += PAGE; + } + } } x = end; } } + drop(lazy); + // Any recycled pool tiles mapped lazily above must be zeroed BEFORE `dirty_runs` uploads + // their non-zero chunks (keep the `sent` hashes `scan_page` just computed). + if !s.to_zero.is_empty() { + zero_runs.extend(s.to_zero.drain(..)); + } let t_scanned = std::time::Instant::now(); PHASES[1].fetch_add((t_scanned - t_locked).as_micros() as u64, Ordering::Relaxed); PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); @@ -1863,6 +2433,8 @@ mod tests { rb_alloc, rb_list, rb_last_fence: 0, + rb_seq: 0, + last_rb: FxHashMap::default(), waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), @@ -2071,6 +2643,8 @@ mod tests { rb_alloc, rb_list, rb_last_fence: 0, + rb_seq: 0, + last_rb: FxHashMap::default(), waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), @@ -2082,7 +2656,7 @@ mod tests { assert_eq!(s.mapped[&(base + TILE)].holes, 0xFFFF, "fully reserved tile must have all 16 holes set"); // Reading back the full 2-tile span must not fault on uncommitted pages. - s.readback_ranges(&[(base, 2 * TILE)]); + s.readback_ranges(&[(base, 2 * TILE)], None); // Now incrementally commit [base, base + 4*PAGE) and clear its hole bits (as `committed` does). assert!(!VirtualAlloc(base as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); @@ -2168,6 +2742,8 @@ mod tests { rb_alloc, rb_list, rb_last_fence: 0, + rb_seq: 0, + last_rb: FxHashMap::default(), waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), @@ -2293,6 +2869,8 @@ mod tests { rb_alloc, rb_list, rb_last_fence: 0, + rb_seq: 0, + last_rb: FxHashMap::default(), waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), @@ -2533,6 +3111,27 @@ mod tests { assert_eq!(early.into_iter().collect::>(), vec![(a, a + TILE), (a + 2 * TILE, a + 4 * TILE)]); } + #[test] + fn lazy_range_helpers_track_tile_overlap_holes_and_nonzero_pages() { + let base = 0x5_0000_0000usize; + let mut lazy = BTreeMap::new(); + // Partially cover tile 0 (pages 4..8) and fully cover tile 2. + early_add(&mut lazy, base + 4 * PAGE, base + 8 * PAGE); + early_add(&mut lazy, base + 2 * TILE, base + 3 * TILE); + + assert!(lazy_overlaps_tile(&lazy, base)); + assert!(!lazy_overlaps_tile(&lazy, base + TILE)); + assert!(lazy_overlaps_tile(&lazy, base + 2 * TILE)); + assert_eq!(lazy_tile_holes(&lazy, base), 0xFFFF & !(0b1111u16 << 4)); + assert_eq!(lazy_tile_holes(&lazy, base + TILE), 0xFFFF); + assert_eq!(lazy_tile_holes(&lazy, base + 2 * TILE), 0); + + let mut page = vec![0u8; PAGE]; + assert!(!page_has_nonzero(&page)); + page[PAGE - 1] = 1; + assert!(page_has_nonzero(&page)); + } + /// Time for n 64 KiB pages committed one at a time and decommitted one at a time in /// reverse, before the device exists (`cargo test --release -p xcl --lib -- /// --ignored --exact hle::d3d12x::sparse::tests::early_commit_timing --nocapture`, @@ -2559,4 +3158,311 @@ mod tests { println!("early: {n} pages: commit {:.1} ms, decommit {:.1} ms", commit.as_secs_f64() * 1e3, decommit.as_secs_f64() * 1e3); } } + + /// `readback_after_execute` must return immediately when `queue` is blocked on an unsignaled + /// GPU fence (wait-before-signal `Wait64BitValueX`) rather than deadlocking the submitter + /// thread and `sparse::State::queue` for 5 seconds, and complete synchronously once no + /// unsatisfied `queue.Wait` remains. + #[test] + fn readback_after_execute_does_not_block_on_stalled_queue() { + unsafe { + if super::super::real::init().is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let Some(dev) = STATE.lock().unwrap().as_ref().map(|s| s.dev.clone()) else { + crate::gpu::recomp::runner::skip_test("no sparse state"); + return; + }; + let Some((va, _len)) = alloc(TILE, TILE) else { + crate::gpu::recomp::runner::skip_test("no sparse UMA"); + return; + }; + assert!(crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va)), "allocated VA must be sparse"); + + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }) + .expect("compute queue"); + let gate = super::super::real::create_raw_fence(&dev).expect("gate fence"); + queue.Wait(&gate, 1).expect("queue.Wait"); + assert!( + !queue_has_unsatisfied_wait(queue.as_raw() as usize), + "internal raw-fence wait must not mark the queue stalled" + ); + note_queue_wait(queue.as_raw() as usize, gate.clone(), 1); + assert!(queue_has_unsatisfied_wait(queue.as_raw() as usize)); + + let started = std::time::Instant::now(); + readback_after_execute(&queue, &[(va, 64)]); + assert!( + started.elapsed() < std::time::Duration::from_secs(1), + "readback_after_execute blocked submitter thread on stalled queue ({:?})", + started.elapsed() + ); + assert!(STATE.try_lock().is_ok(), "STATE must not remain locked while stalled queue waits"); + + // Release the stalled queue so the async readback worker drains cleanly, then verify + // an unstalled submit completes synchronously without error. + gate.Signal(1).expect("gate.Signal"); + assert!(!queue_has_unsatisfied_wait(queue.as_raw() as usize)); + let done = super::super::real::create_raw_fence(&dev).expect("done fence"); + queue.Signal(&done, 1).expect("queue.Signal"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while done.GetCompletedValue() < 1 && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(done.GetCompletedValue() >= 1, "queue did not drain after gate signaled"); + readback_after_execute(&queue, &[(va, 64)]); + forget_queue(queue.as_raw() as usize); + assert!(free(va), "free sparse test allocation"); + } + } + + /// XCL's own internal queue waits (such as `sparse::before_execute` waiting on `s.fence`) use + /// raw internal fences whose producer signal is already submitted. They must not mark `queue` + /// as stalled; otherwise `readback_after_execute` returns before the worker finishes copying + /// GPU writes back to CPU memory (e.g. under `XCL_D3D12_DEBUG=1`). + #[test] + fn internal_fence_wait_keeps_readback_synchronous() { + unsafe { + if super::super::real::init().is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let Some(dev) = STATE.lock().unwrap().as_ref().map(|s| s.dev.clone()) else { + crate::gpu::recomp::runner::skip_test("no sparse state"); + return; + }; + let Some((va, _len)) = alloc(TILE, TILE) else { + crate::gpu::recomp::runner::skip_test("no sparse UMA"); + return; + }; + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .expect("direct queue"); + let internal_gate = super::super::real::create_raw_fence(&dev).expect("internal gate fence"); + queue.Wait(&internal_gate, 1).expect("queue.Wait"); + assert!(!queue_has_unsatisfied_wait(queue.as_raw() as usize)); + + let gate_raw = internal_gate.as_raw() as usize; + let releaser = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(40)); + let p = gate_raw as *mut c_void; + if let Some(f) = ID3D12Fence::from_raw_borrowed(&p) { + let _ = f.Signal(1); + } + }); + readback_after_execute(&queue, &[(va, 64)]); + assert!( + internal_gate.GetCompletedValue() >= 1, + "readback_after_execute returned early while only an internal fence wait was in flight" + ); + releaser.join().unwrap(); + forget_queue(queue.as_raw() as usize); + assert!(free(va), "free sparse test allocation"); + } + } + + /// A readback job whose fence times out must report `RbStatus::Deferred` (not `Completed`) + /// and remain queued so CPU readback still runs in FIFO order once the fence later completes. + #[test] + fn timeout_then_completes_still_reads_back_cpu_memory() { + unsafe { + if super::super::real::init().is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let Some(dev) = STATE.lock().unwrap().as_ref().map(|s| s.dev.clone()) else { + crate::gpu::recomp::runner::skip_test("no sparse state"); + return; + }; + let fence = super::super::real::create_raw_fence(&dev).expect("raw fence"); + let seen = std::sync::Arc::new((Mutex::new(Vec::>::new()), std::sync::Condvar::new())); + let seen_cb = seen.clone(); + let tx = spawn_rb_worker_with(0xdead_beef, 50, move |ranges, _| { + let mut g = seen_cb.0.lock().unwrap(); + g.push(ranges.to_vec()); + seen_cb.1.notify_all(); + }); + + // Job 1: fence is still 0, so the 50 ms wait times out and must report Deferred. + let done1 = std::sync::Arc::new((Mutex::new(RbStatus::Pending), std::sync::Condvar::new())); + tx.send(RbJob { + fence: fence.clone(), + value: 1, + ranges: vec![(0x1000, 64)], + snapshot: RbSnapshot::default(), + done: Some(done1.clone()), + _in_flight: InFlightGuard::acquire(), + }) + .expect("send job 1"); + let (status1, _) = done1 + .1 + .wait_timeout_while(done1.0.lock().unwrap(), std::time::Duration::from_secs(2), |s| *s == RbStatus::Pending) + .unwrap(); + assert_eq!(*status1, RbStatus::Deferred, "timed-out job must report Deferred, not Completed"); + assert!(seen.0.lock().unwrap().is_empty(), "readback must not run before fence completes"); + + // Fence later completes: the retained deferred job must be retried automatically. + fence.Signal(1).expect("signal 1"); + let (guard, _) = seen + .1 + .wait_timeout_while(seen.0.lock().unwrap(), std::time::Duration::from_secs(2), |v| v.is_empty()) + .unwrap(); + assert_eq!(*guard, vec![vec![(0x1000, 64)]], "deferred job must run once fence completes"); + drop(guard); + + // Job 2: already signaled fence completes synchronously with RbStatus::Completed. + fence.Signal(2).expect("signal 2"); + let done2 = std::sync::Arc::new((Mutex::new(RbStatus::Pending), std::sync::Condvar::new())); + tx.send(RbJob { + fence: fence.clone(), + value: 2, + ranges: vec![(0x2000, 128)], + snapshot: RbSnapshot::default(), + done: Some(done2.clone()), + _in_flight: InFlightGuard::acquire(), + }) + .expect("send job 2"); + let (status2, _) = done2 + .1 + .wait_timeout_while(done2.0.lock().unwrap(), std::time::Duration::from_secs(2), |s| *s == RbStatus::Pending) + .unwrap(); + assert_eq!(*status2, RbStatus::Completed, "completed job must report Completed"); + assert_eq!(*seen.0.lock().unwrap(), vec![vec![(0x1000, 64)], vec![(0x2000, 128)]]); + drop(tx); + } + } + + /// A late/deferred readback must not overwrite bytes the title's CPU wrote after the submit + /// was recorded, must still copy back untouched chunks from VRAM, must leave `sent` stale for + /// skipped chunks so the next `before_execute` uploads the CPU write, and must let consecutive + /// deferred readbacks on the same range both land when the CPU has not written between them. + #[test] + fn deferred_readback_preserves_newer_cpu_writes() { + unsafe { + if super::super::real::init().is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let Some((dev, win_base, win_buf)) = ({ + let g = STATE.lock().unwrap(); + g.as_ref().and_then(|s| s.windows.first().map(|(b, r)| (s.dev.clone(), *b, r.clone()))) + }) else { + crate::gpu::recomp::runner::skip_test("no sparse state"); + return; + }; + let Some((va, _len)) = alloc(TILE, TILE) else { + crate::gpu::recomp::runner::skip_test("no sparse UMA"); + return; + }; + assert!(va >= win_base && va + TILE <= win_base + crate::gpu::uma::WINDOW); + + // Seed initial CPU bytes in chunk 0 (0x11) and chunk 1 (0x22); chunk 2 stays 0x00. + std::ptr::write_bytes(va as *mut u8, 0x11, CHUNK); + std::ptr::write_bytes((va + CHUNK) as *mut u8, 0x22, CHUNK); + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .expect("direct queue"); + let qid = queue.as_raw() as usize; + before_execute(&queue, &[va], PAGE); + + // Create a small upload buffer with GPU payloads: + // [0..64) = 0xAA (GPU write to chunk 0) + // [64..128) = 0xBB (GPU write to chunk 1) + // [128..192) = 0xDD (1st deferred GPU write to chunk 2) + // [192..256) = 0xEE (2nd deferred GPU write to chunk 2) + let mut src_res: Option = None; + let mut src_desc = buffer_desc(256); + src_desc.Flags = D3D12_RESOURCE_FLAG_NONE; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &src_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut src_res, + ) + .expect("upload src"); + let src_res = src_res.expect("upload src"); + let mut src_ptr = std::ptr::null_mut(); + src_res.Map(0, None, Some(&mut src_ptr)).expect("map src"); + let sp = src_ptr as *mut u8; + std::ptr::write_bytes(sp, 0xAA, CHUNK); + std::ptr::write_bytes(sp.add(CHUNK), 0xBB, CHUNK); + std::ptr::write_bytes(sp.add(2 * CHUNK), 0xDD, CHUNK); + std::ptr::write_bytes(sp.add(3 * CHUNK), 0xEE, CHUNK); + src_res.Unmap(0, None); + + let make_copy_list = |src_off: u64, dst_va: usize, bytes: u64| -> (ID3D12CommandAllocator, ID3D12CommandList) { + let alloc: ID3D12CommandAllocator = + dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = + dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.CopyBufferRegion(&win_buf, (dst_va - win_base) as u64, &src_res, src_off, bytes); + list.Close().expect("close"); + (alloc, list.cast::().expect("cast")) + }; + + // 1. Stall queue on `gate`, submit GPU write of [0xAA, 0xBB] to chunks 0..2, and record + // the async readback while CPU still holds [0x11, 0x22]. + let gate = super::super::real::create_raw_fence(&dev).expect("gate fence"); + queue.Wait(&gate, 1).expect("queue.Wait gate"); + note_queue_wait(qid, gate.clone(), 1); + let (_a1, l1) = make_copy_list(0, va, (2 * CHUNK) as u64); + queue.ExecuteCommandLists(&[Some(l1)]); + readback_after_execute(&queue, &[(va, 2 * CHUNK)]); + + // Title's CPU now overwrites chunk 0 with 0xCC before the stalled GPU work completes. + std::ptr::write_bytes(va as *mut u8, 0xCC, CHUNK); + + // Release the gate and issue a synchronous readback on an unrelated chunk so we know + // the FIFO worker has finished the deferred readback above. + gate.Signal(1).expect("signal gate"); + readback_after_execute(&queue, &[(va + 4 * CHUNK, CHUNK)]); + + let c0 = std::slice::from_raw_parts(va as *const u8, CHUNK); + let c1 = std::slice::from_raw_parts((va + CHUNK) as *const u8, CHUNK); + assert!(c0.iter().all(|&b| b == 0xCC), "newer CPU write in chunk 0 was overwritten by late readback: {:02x?}", &c0[..8]); + assert!(c1.iter().all(|&b| b == 0xBB), "untouched chunk 1 did not receive GPU data: {:02x?}", &c1[..8]); + { + let g = STATE.lock().unwrap(); + let entry = &g.as_ref().unwrap().mapped[&va]; + let sent = entry.sent[0].as_ref().expect("sent hashes"); + assert_ne!(sent[0], chunk_hash(c0), "skipped chunk 0 must stay dirty in `sent` for next upload"); + assert_eq!(sent[1], chunk_hash(c1), "copied chunk 1 must be synced in `sent`"); + } + + // 2. Two consecutive deferred readbacks on chunk 2 (0xDD then 0xEE) with no CPU write + // between them: job 1's copy-back must not cause job 2 to skip its copy. + let gate1 = super::super::real::create_raw_fence(&dev).expect("gate1"); + let gate2 = super::super::real::create_raw_fence(&dev).expect("gate2"); + queue.Wait(&gate1, 1).expect("wait gate1"); + note_queue_wait(qid, gate1.clone(), 1); + let (_a2, l2) = make_copy_list((2 * CHUNK) as u64, va + 2 * CHUNK, CHUNK as u64); + queue.ExecuteCommandLists(&[Some(l2)]); + readback_after_execute(&queue, &[(va + 2 * CHUNK, CHUNK)]); + + queue.Wait(&gate2, 1).expect("wait gate2"); + note_queue_wait(qid, gate2.clone(), 1); + let (_a3, l3) = make_copy_list((3 * CHUNK) as u64, va + 2 * CHUNK, CHUNK as u64); + queue.ExecuteCommandLists(&[Some(l3)]); + readback_after_execute(&queue, &[(va + 2 * CHUNK, CHUNK)]); + + gate1.Signal(1).expect("signal gate1"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while std::ptr::read_volatile((va + 2 * CHUNK) as *const u8) != 0xDD && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(std::ptr::read_volatile((va + 2 * CHUNK) as *const u8), 0xDD, "first deferred readback did not land"); + + gate2.Signal(1).expect("signal gate2"); + readback_after_execute(&queue, &[(va + 4 * CHUNK, CHUNK)]); + let c2 = std::slice::from_raw_parts((va + 2 * CHUNK) as *const u8, CHUNK); + assert!(c2.iter().all(|&b| b == 0xEE), "second consecutive deferred readback was falsely skipped: {:02x?}", &c2[..8]); + + forget_queue(qid); + assert!(free(va), "free sparse test allocation"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 6d97bc6e4e..6c83758dad 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -491,6 +491,32 @@ pub fn note_gpu_write(res: usize) { static GPU_WRITTEN: AtomicU64 = AtomicU64::new(0); +/// Under Wine, the coherent UMA window has no `MEM_WRITE_WATCH` (to avoid `amdgpu` userptr +/// MMU-notifier stalls), so DirectStorage writes into it notify us directly here. +pub fn mark_dirty_range(va: usize, len: usize) { + if !any() || len == 0 { + return; + } + if !crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, len)) { + return; + } + let mut t = TEXTURES.lock().unwrap(); + let end = va.saturating_add(len); + let hits = t.active_overlaps(va, end); + let mut added = 0usize; + for (_, res, _) in hits { + if let Some(e) = t.by_res.get_mut(&res) { + if !e.gpu_written && !e.pending { + e.pending = true; + added += 1; + } + } + } + if added > 0 { + PENDING.fetch_add(added, Ordering::Relaxed); + } +} + /// The textures kept in step whose memory `[va, va + len)` overlaps (PC texture, its address). pub fn overlapping(va: usize, len: usize) -> Vec<(usize, usize)> { TEXTURES.lock().unwrap().overlapping(va, len) @@ -796,25 +822,42 @@ unsafe fn refresh_once(queue: *mut c_void) { p.max(b) }; recheck_streamed_unwatched(&ranges, recheck_frame); - if dirty_len == 0 && PENDING.load(Ordering::Relaxed) == 0 { + // the coherent window is not write-watched there (`uma::wine_amd_gpu`): its textures are hashed + let wine_hash_committed = crate::gpu::uma::wine_amd_gpu() && TEXTURES_LEN.load(Ordering::Relaxed) > 0; + if dirty_len == 0 && PENDING.load(Ordering::Relaxed) == 0 && !wine_hash_committed { return; } + static HASH_TICK: AtomicU64 = AtomicU64::new(0); + let hash_tick = if wine_hash_committed { HASH_TICK.fetch_add(1, Ordering::Relaxed) } else { 0 }; // textures made since the last submit and those with a written page; a reference each // while they are uploaded let todo: Vec<(ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); let mut t = TEXTURES.lock().unwrap(); + let last = if wine_hash_committed { Some(LAST_CONTENT.lock().unwrap()) } else { None }; t.by_res .iter_mut() - .filter(|(_, e)| { + .filter(|(&res, e)| { if e.pending { return true; } if e.gpu_written { return false; } + let size = e.tex.size() as usize; + if wine_hash_committed && u.in_committed_window(e.src, size) { + // Hash dynamic/small textures (Bink video, glyph caches, UI) every submit; + // large static textures are notified by DirectStorage (`mark_dirty_range`) + // and swept round-robin so submits stay < 1 ms. + if size > (4 << 20) && (e.seq & 15) != (hash_tick & 15) { + return false; + } + let bytes = read_committed(e.src, size); + let h = content_hash(&bytes); + return last.as_ref().unwrap().get(&res).copied() != Some(h); + } let i = dirty.partition_point(|&p| p + page as usize <= e.src); - dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) + dirty.get(i).is_some_and(|&p| p < e.src + size) }) .filter_map(|(&res, e)| { if e.pending { @@ -1386,9 +1429,9 @@ unsafe fn read_committed(at: usize, len: usize) -> Vec { let mut out = vec![0u8; len]; let Some(limit) = at.checked_add(len) else { return out }; // (the coherent window is committed as a whole: no `VirtualQuery`, which sizes a region by - // walking it) + // walking it; still copy via `ReadProcessMemory` so an unreadable page never faults) if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) { - std::ptr::copy_nonoverlapping(at as *const u8, out.as_mut_ptr(), len); + copy_committed_region(at, out.as_mut_ptr(), len); return out; } let mut p = at; @@ -1457,7 +1500,8 @@ unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> V /// The title's bytes at `at`: where they are when all of them are readable (a copy first cost /// as much as the detile of a video frame), else read page run by page run. unsafe fn title_bytes(at: usize, len: usize) -> std::borrow::Cow<'static, [u8]> { - if crate::gpu::shader::readable(at, len) { + let wine_coherent = crate::util::under_wine() && crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)); + if !wine_coherent && crate::gpu::shader::readable(at, len) { std::borrow::Cow::Borrowed(std::slice::from_raw_parts(at as *const u8, len)) } else { std::borrow::Cow::Owned(read_committed(at, len)) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index ea49ce6b89..409c180482 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -626,7 +626,7 @@ impl Pages { } let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; let _ = queue.SetName(windows::core::w!("xcl vram tile-mapping queue")); - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let fence: ID3D12Fence = super::real::create_raw_fence(&dev).ok()?; crate::xlog_info!("D3D12.X: textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); Some(Pages { queue, @@ -1181,7 +1181,7 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla if newly_reclaimed.is_empty() && !map.contains_key(&dev_key) { return; } let rq = map.entry(dev_key).or_insert_with(RetireQueue::new); let before = rq.batches.len(); - let immediate = rq.retire_with(newly_reclaimed, unmap_mark, &queues, || dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok(), |q, f, v| q.Signal(f, v).is_ok()); + let immediate = rq.retire_with(newly_reclaimed, unmap_mark, &queues, || super::real::create_raw_fence(dev).ok(), |q, f, v| q.Signal(f, v).is_ok()); let (done, pruned) = rq.sweep_with(&live_keys, |f| f.GetCompletedValue()); RETIRING_BATCHES.fetch_add(rq.batches.len().wrapping_sub(before), std::sync::atomic::Ordering::AcqRel); (immediate, done, pruned) diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 2ae4fe1b66..553066e50f 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -981,6 +981,9 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us } } else if n > 0 { std::ptr::copy_nonoverlapping(payload.as_ptr(), r.destination as *mut u8, n); + if crate::util::under_wine() { + crate::hle::d3d12x::title_textures::mark_dirty_range(r.destination as usize, n); + } } Ok(()) } diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 4144a1144e..7411a4178d 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -342,6 +342,13 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: trace_mem("VirtualAlloc (graphics, coherent window)", 0, size, t as u64, p, q as usize); return q as *mut c_void; } + if crate::util::under_wine() { + let rounded = size.max(1).div_ceil(align) * align; + if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc_lazy(rounded, align) { + trace_mem("VirtualAlloc (graphics, sparse VRAM lazy fallback)", 0, rounded, t as u64, p, q); + return q as *mut c_void; + } + } } } // GPU-visible title memory the windows above had no room for (a retail game: a 24 GB