diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 4d8feee..3566f9b 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1459,23 +1459,24 @@ unsafe fn set_index_buffer(list: *mut c_void, view: Option<&D3D12_INDEX_BUFFER_V f(list, view.map_or(std::ptr::null(), |v| v as *const _)); } -/// The heaps a list binds for console code: a view heap in the shared shader-visible heap -/// is that one (`console_heap`), which is bound whatever the title names (a console -/// descriptor table may be in any heap); sampler heaps as they are. +/// Bind the shared heap for shared view indices and the selected private heap for local +/// view indices. Sampler heaps are passed through. pub(super) unsafe fn pc_heaps(n: u32, heaps: *const usize) -> Vec> { - let shared = super::console_heap::global_heap(); - let mut out: Vec> = shared.iter().cloned().map(Some).collect(); + let mut view_heap = super::console_heap::global_heap(); + let mut out = Vec::new(); for k in 0..n as usize { let p = *heaps.add(k) as *mut c_void; - if p.is_null() || (shared.is_some() && super::console_heap::in_global(p as usize)) { + if p.is_null() || super::console_heap::in_global(p as usize) { continue; } let Some(h) = ID3D12DescriptorHeap::from_raw_borrowed(&p) else { continue }; - if shared.is_some() && h.GetDesc().Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV { - continue; + if h.GetDesc().Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV { + view_heap = Some(h.clone()); + } else { + out.push(Some(h.clone())); } - out.push(Some(h.clone())); } + out.extend(view_heap.map(Some)); out } @@ -1643,7 +1644,7 @@ const PC_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80 | 0x100 /// #26 ResourceBarrier(count, barriers): console barriers (D3D12_RESOURCE_BARRIER, 32 bytes) as /// PC ones – state bits the PC does not know are dropped (logged: the console's own), a -/// transition left with nothing to do goes, aliasing barriers cover any resources +/// transition left with nothing to do goes, aliasing barriers name placed textures pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u32, barriers: *const [u32; 8]) { static N: AtomicU64 = AtomicU64::new(0); if barriers.is_null() || n == 0 { @@ -1669,10 +1670,14 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 continue; } if ty == 1 { - // aliasing (resource before +8, after +16): on the PC only between placed / reserved - // resources, and the console's texture memory is mostly XCL's committed resources - // (the list would fail to Close) – an aliasing barrier for any resources instead - b[2..6].fill(0); + // Keep the identity of textures that really share placed GPU memory. + // Committed resources still need the wildcard form on the PC. + for words in b[2..6].chunks_exact_mut(2) { + let resource = (words[0] as u64 | (words[1] as u64) << 32) as usize; + if resource != 0 && !super::vram::is_placed_texture(resource) { + words.fill(0); + } + } } if ty == 0 { // transition: resource (+8), subresource (+16), before (+20), after (+24) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index e4ffba8..924fbe7 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -41,6 +41,7 @@ static LAST_BOUNDARY_MS: AtomicU64 = AtomicU64::new(0); static HWND_RAW: AtomicIsize = AtomicIsize::new(0); /// the title called PresentX: the fallback guessing is off static PRESENTX: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static PRESENTX_LOCK: Mutex<()> = Mutex::new(()); /// command queue #30 PresentX(planeCount, planes, parameters): plane 0's first resource is /// the frame; S_OK always (a console present does not fail for the title). @@ -48,7 +49,16 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl if plane_count == 0 || planes.is_null() || !crate::gpu::shader::readable(planes as usize, 0x18) { return 0; } - super::frame::mark_flipped((planes as *const u64).read_unaligned()); + let token = (planes as *const u64).read_unaligned(); + let _present = PRESENTX_LOCK.lock().unwrap(); + present_x_frame(queue, plane_count, planes); + // The title can use flip statistics to decide when to reuse its buffer. + // Queue our copy before reporting the flip. + super::frame::mark_flipped(token); + 0 +} + +unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u8) { let frames = BOUNDARIES.fetch_add(1, Ordering::Relaxed) + 1; if frames % 300 == 0 { // the title's frame rate, for comparing runs (every 300 frames) @@ -75,11 +85,11 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl let count = (planes.add(8) as *const u32).read_unaligned(); let list = (planes.add(0x10) as *const usize).read_unaligned(); if count == 0 || !crate::gpu::shader::readable(list, 8) || !enabled() { - return 0; + return; } let res = (list as *const usize).read_unaligned(); if res == 0 { - return 0; + return; } { let mut p = PRESENTED.lock().unwrap(); @@ -112,19 +122,7 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl crate::xlog_info!("frame trace: PresentX #{n} of {res:#x} {:?} – rt binds {}, UAV views {}, copy destination {}, clears {}; most used: {}", d, u[0], u[1], u[2], u[3], busiest.join("; ")); } } - { - let mut c = CANDIDATE.lock().unwrap(); - if c.map(|(_, r)| r) != Some(res) { - add_ref(res); - if let Some((_, old)) = c.replace((queue as usize, res)) { - release(old); - } - } else if let Some(cur) = c.as_mut() { - cur.0 = queue as usize; - } - } - present_now(Duration::ZERO); - 0 + present_now(Duration::ZERO, Some((queue as usize, res))); } thread_local! { @@ -287,7 +285,7 @@ pub unsafe fn note_execute(queue: *mut c_void, lists: &[*mut c_void]) { } // no console present call seen recently → present on submissions (rate limited) if now_ms().saturating_sub(LAST_BOUNDARY_MS.load(Ordering::Relaxed)) > 500 { - present_now(Duration::from_millis(15)); + present_now(Duration::from_millis(15), None); } } @@ -298,7 +296,7 @@ pub fn on_queue_console_method(_info: &StubInfo, _caller: usize) { } BOUNDARIES.fetch_add(1, Ordering::Relaxed); LAST_BOUNDARY_MS.store(now_ms(), Ordering::Relaxed); - unsafe { present_now(Duration::from_millis(4)) }; + unsafe { present_now(Duration::from_millis(4), None) }; } // --------------------------------------------------------------------------------------- @@ -451,6 +449,7 @@ struct Presenter { alloc: ID3D12CommandAllocator, list: ID3D12GraphicsCommandList, fence: ID3D12Fence, + copy_source: Option, value: u64, event: HANDLE, last: Instant, @@ -483,7 +482,7 @@ unsafe fn new_presenter(queue: usize) -> Option { list.Close().ok()?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; let event = CreateEventW(None, false, false, None).ok()?; - Some(Presenter { queue, sc: None, w: 0, h: 0, fmt: DXGI_FORMAT_UNKNOWN, alloc, list, fence, value: 0, event, last: Instant::now() - Duration::from_secs(1) }) + Some(Presenter { queue, sc: None, w: 0, h: 0, fmt: DXGI_FORMAT_UNKNOWN, alloc, list, fence, copy_source: None, value: 0, event, last: Instant::now() - Duration::from_secs(1) }) } unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: DXGI_FORMAT) -> bool { @@ -532,7 +531,7 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D } } -unsafe fn present_now(min_interval: Duration) { +unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { if IN_PRESENT.with(|c| c.replace(true)) { return; } @@ -543,8 +542,21 @@ unsafe fn present_now(min_interval: Duration) { } } let _reset = Reset; - let Some((queue, res)) = *CANDIDATE.lock().unwrap() else { return }; - let Ok(mut guard) = PRESENTER.try_lock() else { return }; + let (queue, src, mut guard) = if let Some((queue, res)) = frame { + let raw = res as *mut c_void; + let Some(src) = ID3D12Resource::from_raw_borrowed(&raw) else { return }; + (queue, src.clone(), PRESENTER.lock().unwrap()) + } else { + let Ok(guard) = PRESENTER.try_lock() else { return }; + if PRESENTX.load(Ordering::Relaxed) { + return; + } + let candidate = CANDIDATE.lock().unwrap(); + let Some((queue, res)) = *candidate else { return }; + let raw = res as *mut c_void; + let Some(src) = ID3D12Resource::from_raw_borrowed(&raw) else { return }; + (queue, src.clone(), guard) + }; if guard.is_none() { *guard = new_presenter(queue); } @@ -552,7 +564,7 @@ unsafe fn present_now(min_interval: Duration) { if p.last.elapsed() < min_interval { return; } - let Some(desc) = backbuffer_like(res) else { return }; + let Some(desc) = backbuffer_like(src.as_raw() as usize) else { return }; let Some(fmt) = swap_format(desc.Format) else { return }; let Some(hwnd) = ensure_window() else { return }; if p.queue != queue { @@ -562,22 +574,24 @@ unsafe fn present_now(min_interval: Duration) { if p.fence.GetCompletedValue() < p.value { let _ = p.fence.SetEventOnCompletion(p.value, p.event); WaitForSingleObject(p.event, 100); + if p.fence.GetCompletedValue() < p.value { + return; + } } + p.copy_source = None; if !ensure_swapchain(p, hwnd, desc.Width as u32, desc.Height, fmt) { return; } let Some(sc) = p.sc.clone() else { return }; - let rraw = res as *mut c_void; - let Some(src) = ID3D12Resource::from_raw_borrowed(&rraw) else { return }; let Ok(bb) = sc.GetBuffer::(sc.GetCurrentBackBufferIndex()) else { return }; if p.alloc.Reset().is_err() || p.list.Reset(&p.alloc, None).is_err() { return; } let b1 = [transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST)]; p.list.ResourceBarrier(&b1); - p.list.CopyResource(&bb, src); + p.list.CopyResource(&bb, &src); let due = frame_dump_due(); - let dump = due.then(|| readback_copy(&p.list, src, &desc)).flatten(); + let dump = due.then(|| readback_copy(&p.list, &src, &desc)).flatten(); // with `XCL_TRACE_FRAME`: also the render target the title binds most (its scene / UI) // (and the targets the watched one's contents went on to: rt__) let rt_dump: Vec<_> = if due && trace_frame() { @@ -603,6 +617,7 @@ unsafe fn present_now(min_interval: Duration) { let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qraw) else { return }; let Ok(cl) = p.list.cast::() else { return }; q.ExecuteCommandLists(&[Some(cl)]); + p.copy_source = Some(src); p.value += 1; let _ = q.Signal(&p.fence, p.value); let _ = sc.Present(0, DXGI_PRESENT(0)); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 814f0df..829be16 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1318,6 +1318,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { m.remove(&(this as usize)); } super::sparse::forget_buffer(this as usize); + super::vram::forget(this as usize); super::title_textures::forget(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index e4caf3f..6d1632a 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -26,12 +26,11 @@ use windows::Win32::Graphics::Direct3D12::*; use crate::gpu::texture::{self, Subresource}; use crate::hle::xg; -/// GetWriteWatch / ResetWriteWatch +/// GetWriteWatch with atomic reset of the reported writes. const WRITE_WATCH_FLAG_RESET: u32 = 1; #[link(name = "kernel32")] extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; - fn ResetWriteWatch(base: *const c_void, size: usize) -> u32; } /// (device, address, layout, state) of an upload @@ -58,6 +57,9 @@ unsafe impl Send for Entry {} /// PC texture → its place in the title's memory static TEXTURES: Mutex> = Mutex::new(BTreeMap::new()); +// The dirty-page scan consumes write-watch state for every submission thread. +// Keep the scan, pending-list update and GPU uploads together. +static REFRESH: Mutex<()> = Mutex::new(()); static TEXTURES_GEN: AtomicU64 = AtomicU64::new(0); static TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// cached `watch_ranges` keyed by `(sparse::mapped_gen, TEXTURES_GEN, graphics_reservations_gen)` @@ -78,14 +80,10 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, if tex.planes.len() != 1 || tex.texels().is_none() { return Err("a render target / depth buffer".into()); } - let bytes = tex.size() as usize; if ID3D12Resource::from_raw_borrowed(&res).is_none() { return Err("no resource".into()); } let e = Entry { device: device as usize, va, tex: Arc::new(tex), state, pending: true, gpu_written: false }; - if crate::gpu::uma::get().is_some_and(|u| u.contains(va)) || crate::hle::kernelx::in_graphics_reservation(va) { - ResetWriteWatch(va as *const c_void, bytes); - } { let mut t = TEXTURES.lock().unwrap(); if let Some(old) = t.insert(res as usize, e) { @@ -94,9 +92,9 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, } } TEXTURES_LEN.store(t.len(), Ordering::Relaxed); + PENDING.fetch_add(1, Ordering::Relaxed); } TEXTURES_GEN.fetch_add(1, Ordering::Release); - PENDING.fetch_add(1, Ordering::Relaxed); Ok(()) } @@ -198,6 +196,7 @@ pub(super) unsafe fn refresh(queue: *mut c_void) { if BUSY.with(|b| b.get()) { return; } + let _refresh = REFRESH.lock().unwrap(); own_work(|| refresh_once(queue)); } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 89e9544..75f145c 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -11,6 +11,7 @@ //! description: the same PC layout, so the same texels). The CPU never sees these textures //! (on the console it could, but GPU-owned targets are not CPU-written). +use std::collections::HashSet; use std::ffi::c_void; use std::sync::Mutex; @@ -34,6 +35,18 @@ struct Arena { unsafe impl Send for Arena {} static ARENAS: Mutex> = Mutex::new(Vec::new()); +static PLACED_TEXTURES: Mutex>> = Mutex::new(None); + +/// A texture backed by one of the aliasable D3D12 heaps. +pub(super) fn is_placed_texture(resource: usize) -> bool { + PLACED_TEXTURES.lock().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) +} + +pub(super) fn forget(resource: usize) { + if let Some(textures) = PLACED_TEXTURES.lock().unwrap().as_mut() { + textures.remove(&resource); + } +} /// Whether a console texture with these D3D12_RESOURCE_FLAGS is the GPU's (render target, /// depth buffer, UAV). @@ -87,5 +100,9 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st } let (heap, offset) = arena_for(dev, va, info.SizeInBytes as usize)?; let hr = super::real::dev_create_placed_resource(this, heap.as_raw() as usize, offset as usize, desc as *const _ as usize, state as usize, clear as usize, riid, ppv); - (hr >= 0 && !(*ppv).is_null()).then_some(hr) + if hr < 0 || (*ppv).is_null() { + return None; + } + PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + Some(hr) }