diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index b5ef5a2ee..e85010261 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 7592d044b..55a22b43b 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. + let c_flags = if crate::util::under_wine() { 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 crate::util::under_wine() { 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 !crate::util::under_wine() { + out.push((self.base + k * WINDOW, s)); + } k += 1; } WindowKind::Sparse => { @@ -782,12 +789,45 @@ fn coherent_file() -> std::path::PathBuf { crate::state::data_dir().join("cache").join("uma_coherent.txt") } +/// Whether this process is running under Wine on an AMD GPU (`amdgpu`, PCI vendor `0x1002`). +/// On `amdgpu`, a multi-GiB `userptr` BO imported via `OpenExistingHeapFromAddress` stalls +/// every Vulkan submission (~150 ms/frame), whereas NVIDIA Linux does not hit that stall and +/// benefits from a larger coherent window. +fn wine_amd_gpu() -> bool { + static AMD: OnceLock = OnceLock::new(); + *AMD.get_or_init(|| { + if !crate::util::under_wine() { + return false; + } + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIFactory1, DXGI_ADAPTER_FLAG_SOFTWARE}; + let Ok(factory) = (unsafe { CreateDXGIFactory1::() }) else { + return false; + }; + let mut i = 0u32; + while let Ok(adapter) = unsafe { factory.EnumAdapters1(i) } { + i += 1; + if let Ok(desc) = unsafe { adapter.GetDesc1() } { + if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32) == 0 { + return desc.VendorId == 0x1002; + } + } + } + false + }) +} + /// 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 +1141,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 to avoid amdgpu userptr MMU-notifier stalls). + let expected = if crate::util::under_wine() { + 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 +1181,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 crate::util::under_wine() { + 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 e821d6074..67cb7ea82 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) = { @@ -443,12 +443,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(); @@ -458,7 +461,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); @@ -467,7 +473,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"); @@ -476,10 +485,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); @@ -492,6 +505,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 0b20bfbd6..b0958615f 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 18ddc684e..a26cc7833 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 ef98c131b..70a5c8ef4 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -664,6 +664,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); } @@ -1626,7 +1627,7 @@ 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 created: ID3D12Fence = real::create_raw_fence(&dev).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 { @@ -2270,7 +2271,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; @@ -2667,6 +2668,8 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { 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); @@ -3165,7 +3168,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); @@ -3218,6 +3224,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); @@ -3878,6 +3886,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); @@ -6656,15 +6666,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) }; @@ -6807,7 +6820,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); @@ -6820,7 +6836,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 2958aa0e9..88cefb35c 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -670,7 +670,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 4ea637488..966ab24b7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -712,6 +712,37 @@ pub(super) unsafe fn readopt(obj: *mut c_void, kind: Kind) { *(obj as *mut usize) = class_for(obj, orig, kind); } +/// 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, + ext: usize, +} + +impl UnadoptGuard { + pub(crate) unsafe fn new(obj: *mut c_void) -> Option { + if !crate::util::under_wine() || !is_adopted(obj) { + return None; + } + Some(Self::enter(obj)) + } + + unsafe fn enter(obj: *mut c_void) -> Self { + let ext = *(obj as *const usize); + let orig = *(ext as *const usize).sub(1); + *(obj as *mut usize) = orig; + Self { obj, ext } + } +} + +impl Drop for UnadoptGuard { + fn drop(&mut self) { + unsafe { + *(self.obj as *mut usize) = self.ext; + } + } +} + /// Give a genuine D3D12 object the extended vtable for `kind`. pub unsafe fn adopt(obj: *mut c_void, kind: Kind) { if obj.is_null() { @@ -2391,6 +2422,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); @@ -2891,7 +2936,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), @@ -2972,7 +3022,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); @@ -3135,7 +3189,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` @@ -3157,6 +3216,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); @@ -3169,7 +3230,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; @@ -3309,7 +3374,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]); @@ -3527,6 +3596,108 @@ 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 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) +} + /// 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) @@ -3534,7 +3705,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); @@ -6701,7 +6886,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); @@ -6762,9 +6950,12 @@ pub(super) unsafe fn bind_pipeline(this: *mut c_void, pso: *mut c_void) { unsafe extern "system" fn cl_set_pipeline_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, "SetPipelineState"))); - let bound = super::pso_async::resolve_for_bind(pso as usize); - f(this, bound as *mut c_void); - super::dred::mark_pipeline(this, pso as usize, bound); + 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); + } + super::dred::mark_pipeline(this, pso as usize, resolved); super::list_x::on_set_pipeline_state(this, pso as usize); } @@ -6779,10 +6970,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); @@ -6853,7 +7047,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 } @@ -6953,7 +7150,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); @@ -7039,6 +7237,18 @@ 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"))); + f(this, unwrap_fence(fence), value) +} + /// 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 @@ -7047,7 +7257,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); @@ -7090,7 +7300,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); @@ -7117,7 +7330,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) @@ -8736,3 +8949,65 @@ 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() { + let orig_vt = [0usize; 8]; + let mut ext_buf = [0usize; 9]; + ext_buf[0] = orig_vt.as_ptr() as usize; + let ext_vt = unsafe { ext_buf.as_ptr().add(1) as usize }; + let mut fake_obj = ext_vt; + let obj = &mut fake_obj as *mut usize as *mut c_void; + + unsafe { + assert_eq!(*(obj as *const usize), ext_vt); + { + let _guard = UnadoptGuard::enter(obj); + assert_eq!(*(obj as *const usize), orig_vt.as_ptr() as usize); + } + assert_eq!(*(obj as *const usize), ext_vt); + } + } + + #[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); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 91eb2ba35..41e524b7d 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -417,6 +417,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) { @@ -513,8 +544,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 { @@ -575,6 +606,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); } @@ -1181,6 +1213,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)`. @@ -1329,13 +1411,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 { @@ -1430,13 +1528,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); @@ -1467,12 +1569,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]; @@ -1482,25 +1586,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); @@ -2272,6 +2411,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`, diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 683b05593..f351b677a 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -482,6 +482,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) @@ -783,25 +809,41 @@ 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 { + let wine_hash_committed = crate::util::under_wine() && 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 { @@ -1348,9 +1390,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; @@ -1419,7 +1461,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 6ac17631f..d20a6a8bc 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -535,8 +535,8 @@ 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 retire_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let fence: ID3D12Fence = super::real::create_raw_fence(&dev).ok()?; + let retire_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, diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 5dd9d2e70..9d3232b8b 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -952,6 +952,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 4f463543f..085cdebe9 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