diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 199f7241a..b0ed33164 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -6,11 +6,12 @@ //! The PC GPU cannot write there; dropped, the title waited for ever after its second frame. //! Here each queue gets a fence of XCL's: after a submission whose lists carry such writes the //! queue signals it, and a worker thread does the writes, in submission order, when the GPU is -//! there – what bottom of pipe means. +//! there – what bottom of pipe means. A GPU timestamp goes the same way: the GPU resolves it +//! into a readback buffer of XCL's and the worker copies those 8 bytes to the title's address. use std::collections::HashMap; use std::ffi::c_void; -use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use std::sync::{mpsc, Mutex, OnceLock}; use windows::core::Interface; @@ -18,8 +19,17 @@ use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D12::*; use windows_sys::Win32::System::Threading as th; -/// (address, the dwords from there) -pub(super) type Write = (usize, Vec); +/// What goes to an address once the GPU is there. +#[derive(Clone)] +pub(super) enum Value { + /// these dwords + Words(Vec), + /// the 8 bytes the GPU resolved at this address of a mapped readback buffer (a timestamp) + Resolved(usize), +} + +/// (address, what goes there) +pub(super) type Write = (usize, Value); struct Job { fence: ID3D12Fence, @@ -54,8 +64,19 @@ fn worker() -> &'static Mutex> { if job.fence.GetCompletedValue() < job.value && job.fence.SetEventOnCompletion(job.value, HANDLE(event as *mut c_void)).is_ok() { th::WaitForSingleObject(event, WAIT_MS); } - for (va, words) in &job.writes { - write_now(*va, words); + for (va, value) in &job.writes { + match value { + Value::Words(words) => write_now(*va, words), + Value::Resolved(at) => { + // one 8-byte store: a title polling it never sees half of a new value + let v = std::ptr::read_volatile(*at as *const u64); + if va % 8 == 0 && can_write_now(*va, 8) { + (*(*va as *const AtomicU64)).store(v, Ordering::Release); + } else { + write_now(*va, &[v as u32, (v >> 32) as u32]); + } + } + } } } }); @@ -68,12 +89,7 @@ fn worker() -> &'static Mutex> { /// The dwords at `va`, if the memory is still there and writable. unsafe fn write_now(va: usize, words: &[u32]) { - use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; - let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); - if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { - return; - } - if m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 || (m.BaseAddress as usize + m.RegionSize) < va + 4 * words.len() { + if !can_write_now(va, 4 * words.len()) { return; } for (i, &w) in words.iter().enumerate() { @@ -81,18 +97,22 @@ unsafe fn write_now(va: usize, words: &[u32]) { } } -/// Whether `[va, va + bytes)` is memory the CPU can write for the GPU later. -pub(super) fn writable(va: usize, bytes: usize) -> bool { - crate::hle::kernelx::lazy::ensure(va, bytes); +/// Whether `[va, va + bytes)` is still committed, writable memory. +unsafe fn can_write_now(va: usize, bytes: usize) -> bool { use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; - let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - let found = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0; - found + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 && m.State == MEM_COMMIT && m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 && m.BaseAddress as usize + m.RegionSize >= va + bytes } +/// Whether `[va, va + bytes)` is memory the CPU can write for the GPU later. +pub(super) fn writable(va: usize, bytes: usize) -> bool { + crate::hle::kernelx::lazy::ensure(va, bytes); + unsafe { can_write_now(va, bytes) } +} + /// `writes` of lists just submitted to `queue`: done when the GPU has finished them. pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { if writes.is_empty() || queue.is_null() { @@ -146,13 +166,66 @@ mod tests { let cell = Box::new([0u32; 2]); let va = cell.as_ptr() as usize; assert!(writable(va, 8)); - after(q.as_raw(), vec![(va, vec![7, 9])]); + after(q.as_raw(), vec![(va, Value::Words(vec![7, 9]))]); let t = std::time::Instant::now(); - while (*(va as *const AtomicU32)).load(Ordering::Acquire) != 7 { + let words = || [0, 1].map(|i| (*((va + 4 * i) as *const AtomicU32)).load(Ordering::Acquire)); + while words() != [7, 9] { assert!(t.elapsed().as_secs() < 5, "never written"); std::thread::yield_now(); } assert_eq!(*cell, [7, 9]); } } + + /// A timestamp the GPU resolved into a readback buffer lands at the address once the queue + /// has written it. + #[test] + fn resolved_values_land_after_the_queue() { + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap(); + let warp: IDXGIAdapter = factory.EnumWarpAdapter().unwrap(); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.unwrap(); + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let mut heap: Option = None; + dev.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: 1, NodeMask: 0 }, &mut heap).unwrap(); + let heap = heap.unwrap(); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 8, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + let props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + dev.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback).unwrap(); + let readback = readback.unwrap(); + let mut p: *mut c_void = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.EndQuery(&heap, D3D12_QUERY_TYPE_TIMESTAMP, 0); + list.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, 1, &readback, 0); + list.Close().unwrap(); + q.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + let cell = Box::new(std::sync::atomic::AtomicU64::new(0)); + let va = cell.as_ptr() as usize; + assert!(writable(va, 8)); + after(q.as_raw(), vec![(va, Value::Resolved(p as usize))]); + let t = std::time::Instant::now(); + while cell.load(Ordering::Acquire) != std::ptr::read_volatile(p as *const u64) || cell.load(Ordering::Acquire) == 0 { + assert!(t.elapsed().as_secs() < 5, "never written"); + std::thread::yield_now(); + } + assert_eq!(cell.load(Ordering::Acquire), std::ptr::read_volatile(p as *const u64)); + readback.Unmap(0, None); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 80f0ce347..d01fcff73 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1098,7 +1098,7 @@ unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFF // the title's own memory: written by the CPU once the GPU is there if super::cpu_writes::writable(va as usize, n as usize) { if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { - s.cpu_writes.push((va as usize, words.to_vec())); + s.cpu_writes.push((va as usize, super::cpu_writes::Value::Words(words.to_vec()))); return; } } @@ -1111,40 +1111,90 @@ unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFF as_copy_dest(list, d, || pc::(list, PC_WRITE_BUFFER_IMMEDIATE)(list, params.len() as u32, params.as_ptr(), modes.as_ptr())); } -/// timestamp queries (one heap per device, used round-robin) -static TIMESTAMPS: Mutex>> = Mutex::new(None); +/// Per device: the timestamp query heap (used round-robin) and, once a timestamp goes to the +/// title's own memory, a readback buffer with a slot per query and where it is mapped. +struct Timestamps { + heap: ID3D12QueryHeap, + readback: Option<(ID3D12Resource, usize)>, +} + +static TIMESTAMPS: Mutex>> = Mutex::new(None); const TIMESTAMP_SLOTS: u32 = 4096; static NEXT_TIMESTAMP: AtomicU32 = AtomicU32::new(0); +/// The device's timestamp heap and, with `readback`, its readback buffer and mapping. +unsafe fn timestamp_heap(dev: &ID3D12Device, readback: bool) -> Option<(usize, Option<(usize, usize)>)> { + let mut m = TIMESTAMPS.lock().unwrap(); + let m = m.get_or_insert_with(HashMap::new); + let t = match m.entry(dev.as_raw() as usize) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(slot) => { + let mut h: Option = None; + let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: TIMESTAMP_SLOTS, NodeMask: 0 }; + dev.CreateQueryHeap(&desc, &mut h).ok()?; + slot.insert(Timestamps { heap: h?, readback: None }) + } + }; + if readback && t.readback.is_none() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 8 * TIMESTAMP_SLOTS as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let mut rb: Option = None; + dev.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).ok()?; + let rb = rb?; + // mapped for good: the CPU reads a slot only after the queue's fence says it is written + let mut p: *mut c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).ok()?; + t.readback = Some((rb, p as usize)); + } + Some((t.heap.as_raw() as usize, t.readback.as_ref().map(|(r, p)| (r.as_raw() as usize, *p)))) +} + /// The GPU timestamp (the PC queue's ticks) written at `va` when the work before it is done. +/// In the title's own memory (outside the unified memory windows) the GPU resolves it into a +/// readback buffer and the CPU copies it there afterwards, like the values `write` puts there. unsafe fn timestamp(list: *mut c_void, va: u64, what: &str) { static N: AtomicU64 = AtomicU64::new(0); let ty = list_type(list); if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { return warn(&N, what, format_args!("a timestamp on a type-{} list", ty.0)); } - let Some((d, off)) = real::uma_window_buffer(va as usize, 8).filter(|_| va.is_multiple_of(8)) else { - return warn(&N, what, format_args!("{va:#x} is not 8-byte aligned in unified memory")); - }; + if !va.is_multiple_of(8) { + return warn(&N, what, format_args!("{va:#x} is not 8-byte aligned")); + } + let uma = real::uma_window_buffer(va as usize, 8); + if uma.is_none() && !super::cpu_writes::writable(va as usize, 8) { + return warn(&N, what, format_args!("{va:#x} is not in unified memory")); + } let Some(dev) = device_of(list) else { return }; - let heap = { - let mut m = TIMESTAMPS.lock().unwrap(); - let m = m.get_or_insert_with(HashMap::new); - if let std::collections::hash_map::Entry::Vacant(slot) = m.entry(dev.as_raw() as usize) { - let mut h: Option = None; - let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: TIMESTAMP_SLOTS, NodeMask: 0 }; - match dev.CreateQueryHeap(&desc, &mut h) { - Ok(()) if h.is_some() => slot.insert(h.unwrap()), - _ => return warn(&N, what, format_args!("no timestamp query heap")), - }; - } - m[&(dev.as_raw() as usize)].as_raw() as usize + let Some((heap, readback)) = timestamp_heap(&dev, uma.is_none()) else { + return warn(&N, what, format_args!("no timestamp query heap or readback buffer")); }; - note_write(list as usize, va, 8); let i = NEXT_TIMESTAMP.fetch_add(1, Ordering::Relaxed) % TIMESTAMP_SLOTS; - pc::(list, PC_END_QUERY)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i); type Resolve = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); - as_copy_dest(list, d, || pc::(list, PC_RESOLVE_QUERY_DATA)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i, 1, d, off)); + match (uma, readback) { + (Some((d, off)), _) => { + note_write(list as usize, va, 8); + pc::(list, PC_END_QUERY)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i); + as_copy_dest(list, d, || pc::(list, PC_RESOLVE_QUERY_DATA)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i, 1, d, off)); + } + (None, Some((rb, mapped))) => { + pc::(list, PC_END_QUERY)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i); + // a readback buffer stays in COPY_DEST + pc::(list, PC_RESOLVE_QUERY_DATA)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i, 1, rb, 8 * i as u64); + let write = (va as usize, super::cpu_writes::Value::Resolved(mapped + 8 * i as usize)); + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default().cpu_writes.push(write); + } + (None, None) => {} + } } /// command list #69 Write32BitValueBottomOfPipeX(address, value, flush, flags) diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index d84d465d9..39e70d2f8 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -552,6 +552,23 @@ pub fn console_list_methods() -> Result<(), String> { ensure!(r32(0x300) == 0xDEAD_00AA && r64(0x308) == 0x0000_0003_0000_0000, "wait cells not written"); ensure!(r32(0x310) == 0x55AA_55AA, "post-Wait32/64 write failed ({:#x})", r32(0x310)); + // 4. A GPU timestamp into the title's own memory (its heap, outside unified memory), as a + // retail title asks for one: written by the CPU once the GPU is there, after the first one + let own = Box::new(std::sync::atomic::AtomicU64::new(0)); + alloc.Reset().map_err(e)?; + list.Reset(&alloc, None).map_err(e)?; + write64_bottom(l, own.as_ptr() as u64, 0, 0, 1); + list.Close().map_err(e)?; + queue.ExecuteCommandLists(&[Some(list.cast::().map_err(e)?)]); + wait(&queue, &fence, 4)?; + let t0 = std::time::Instant::now(); + while own.load(std::sync::atomic::Ordering::Acquire) == 0 && t0.elapsed() < std::time::Duration::from_secs(2) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let ts = own.load(std::sync::atomic::Ordering::Acquire); + ensure!(ts != 0, "no GPU timestamp in the title's own memory"); + ensure!(ts >= r64(0x10), "GPU timestamp in the title's own memory before an earlier one ({ts:#x} < {:#x})", r64(0x10)); + crate::XMemFree(mem as *mut c_void, graphics); Ok(()) }