diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index afa4f91e4..e9f0a92d9 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -578,6 +578,8 @@ struct ListState { pending_waits: Vec, /// bottom-of-pipe writes into memory the GPU does not see (`cpu_writes`) cpu_writes: Vec, + /// upload buffers for `CopyMemoryToMemoryX` from CPU memory outside unified memory, filled at submit + pending_uploads: Vec, /// Dedicated 256-byte buffer holding the current predicate value (created lazily in COMMON state). pred_buf: Option, /// True while `pred_buf` is in `D3D12_RESOURCE_STATE_PREDICATION` on this open recording. @@ -799,6 +801,7 @@ pub(super) fn clear_segment_state(list: usize) { s.clear_write64_signals(); s.clear_waits(); s.cpu_writes.clear(); + s.pending_uploads.clear(); s.predication = None; s.pred_in_state = false; s.bindings = Bindings::default(); @@ -1900,16 +1903,30 @@ pub(super) unsafe fn readback_sparse_writes(queue: *mut c_void, lists: &[*mut c_ } } -/// After `lists` went to `queue`: their writes into memory the GPU does not see (`cpu_writes`). +/// After `lists` went to `queue`: their writes into memory the GPU does not see. pub(super) unsafe fn cpu_writes_after(queue: *mut c_void, lists: &[*mut c_void]) { let writes: Vec = { let g = LISTS.lock().unwrap(); let Some(m) = g.as_ref() else { return }; - lists.iter().filter_map(|&l| m.get(&(l as usize))).flat_map(|s| s.cpu_writes.iter().cloned()).collect() + lists + .iter() + .filter_map(|&l| m.get(&(l as usize))) + .flat_map(|s| s.cpu_writes.iter().cloned()) + .collect() }; super::cpu_writes::after(queue, writes); } +/// Fill the buffers just before submission and keep the references through ExecuteCommandLists. +pub(super) unsafe fn fill_uploads(lists: &[*mut c_void]) -> Vec { + let uploads: Vec = { + let g = LISTS.lock().unwrap(); + let Some(m) = g.as_ref() else { return Vec::new() }; + lists.iter().filter_map(|&l| m.get(&(l as usize))).flat_map(|s| s.pending_uploads.iter().cloned()).collect() + }; + uploads.into_iter().map(|u| u.fill()).collect() +} + /// Submit `lists` through `submit`, splitting the batch before any list whose `Wait32/64BitValueX` /// condition is not yet satisfied so earlier lists in the same batch can run on the GPU first. /// When `queue` is non-null, monotonic 64-bit waits backed by a recorded `Write64BitValue*` are @@ -1956,6 +1973,24 @@ pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], submit: impl FnMu // memory copy / fill / immediate write / timestamp // --------------------------------------------------------------------------------------- +#[derive(Clone)] +struct PendingUpload { + src: usize, + size: usize, + mapped: usize, + buf: ID3D12Resource, +} + +impl PendingUpload { + unsafe fn fill(self) -> ID3D12Resource { + let dst = self.mapped as *mut u8; + if !super::title_textures::copy_gpu_view(self.src, dst, self.size) && crate::gpu::shader::readable(self.src, self.size) { + std::ptr::copy_nonoverlapping(self.src as *const u8, dst, self.size); + } + self.buf + } +} + /// command list #60 CopyMemoryToMemoryX(destination, source, size, flags) pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, src: u64, size: u64, _flags: u32) { static N: AtomicU64 = AtomicU64::new(0); @@ -1963,10 +1998,33 @@ pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, if size == 0 || !size.is_multiple_of(4) { return warn(&N, W, format_args!("size {size:#x} is not a non-zero multiple of 4")); } - let (Some((d, doff)), Some((s, soff))) = (real::uma_window_buffer(dst as usize, size as usize), real::uma_window_buffer(src as usize, size as usize)) else { + let Some((d, doff)) = real::uma_window_buffer(dst as usize, size as usize) else { note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) is not in unified memory")); }; + let Some((s, soff)) = real::uma_window_buffer(src as usize, size as usize) else { + if !crate::gpu::shader::readable(src as usize, size as usize) + && crate::hle::kernelx::mirrors::source_range(src as usize, size as usize).is_none() { + note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); + return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) is not in unified memory")); + } + let Some((buf, mapped)) = create_mapped_upload(this, size) else { + note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); + return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes): no upload buffer")); + }; + let buf_raw = buf.as_raw() as usize; + note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); + note_write(this as usize, dst, size); + as_copy_dest(this, d, || copy_buffer_region(this, d, doff, buf_raw, 0, size)); + if let Some(st) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + st.pending_uploads.push(PendingUpload { src: src as usize, size: size as usize, mapped: mapped as usize, buf }); + } + static FIRST: std::sync::Once = std::sync::Once::new(); + FIRST.call_once(|| { + crate::xlog_info!("D3D12.X: CopyMemoryToMemoryX from memory outside unified memory goes through an upload buffer ({size:#x} bytes)"); + }); + return; + }; note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); if d == s && dst < src + size && src < dst + size { return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) overlap")); @@ -2021,10 +2079,16 @@ impl CopyScratch { } } +struct SubmittedUploads { + mark: Option<(ID3D12Fence, u64)>, + _buffers: Vec, +} + #[derive(Default)] struct CopyScratchCache { active: HashMap, released: Vec, + uploads: Vec, fences: HashMap, bytes: u64, reaping: bool, @@ -2041,6 +2105,10 @@ impl CopyScratchCache { }); } + fn needs_reaper(&self) -> bool { + self.released.iter().any(|s| !s.untracked_submission) || self.uploads.iter().any(|batch| batch.mark.is_some()) + } + fn release(&mut self, list: usize) { if let Some(scratch) = self.active.remove(&list) { self.released.push(scratch); @@ -2081,19 +2149,26 @@ static COPY_SCRATCH: LazyLock> = LazyLock::new(|| Mutex: fn release_copy_scratch(list: usize) { let mut cache = COPY_SCRATCH.lock().unwrap(); cache.release(list); - if cache.reaping || !cache.released.iter().any(|s| !s.untracked_submission) { + reap_copy_buffers(&mut cache); +} + +fn reap_copy_buffers(cache: &mut CopyScratchCache) { + if cache.reaping || !cache.needs_reaper() { return; } - // A title can stop submitting work after releasing the list. Reclaim its scratch when - // the GPU finishes even if no call touches the cache again. + // A title can stop submitting after releasing its list. Reclaim completed buffers then too. cache.reaping = std::thread::Builder::new().name("xcl-copy-scratch".into()).spawn(|| loop { - { - let mut cache = COPY_SCRATCH.lock().unwrap(); - cache.collect_released(); - if !cache.released.iter().any(|s| !s.untracked_submission) { - cache.reaping = false; - return; - } + let mut cache = COPY_SCRATCH.lock().unwrap(); + cache.collect_released(); + let completed: Vec<_> = cache.uploads.extract_if(.., |batch| { + batch.mark.as_ref().is_some_and(|(fence, value)| unsafe { fence.GetCompletedValue() >= *value }) + }).collect(); + let more = cache.needs_reaper(); + cache.reaping = more; + drop(cache); + drop(completed); // a resource's final Release can call back into XCL + if !more { + return; } std::thread::sleep(Duration::from_millis(16)); }).is_ok(); @@ -2113,11 +2188,11 @@ fn reset_copy_scratch(list: *mut c_void) { } } -/// Mark GPU ownership on the queue that actually submitted each PC list or split segment. -pub(super) unsafe fn copy_scratch_submitted(queue: *mut c_void, lists: &[*mut c_void]) { +/// Scratch and staged uploads share a completion mark on the queue that submitted this segment. +pub(super) unsafe fn copy_buffers_submitted(queue: *mut c_void, lists: &[*mut c_void], uploads: Vec) { let mut cache = COPY_SCRATCH.lock().unwrap(); cache.collect_released(); - if !lists.iter().any(|l| cache.active.get(&(*l as usize)).is_some_and(|s| s.recorded)) { + if uploads.is_empty() && !lists.iter().any(|l| cache.active.get(&(*l as usize)).is_some_and(|s| s.recorded)) { return; } let mark = (|| { @@ -2130,13 +2205,15 @@ pub(super) unsafe fn copy_scratch_submitted(queue: *mut c_void, lists: &[*mut c_ } let (fence, value) = cache.fences.get_mut(&key)?; let next = *value + 1; - q.Signal(&*fence, next).ok()?; - *value = next; - Some((fence.clone(), next)) + let signaled = q.Signal(&*fence, next).is_ok(); + if signaled { + *value = next; + } + Some((fence.clone(), next, signaled)) })(); for list in lists { if let Some(scratch) = cache.active.get_mut(&(*list as usize)).filter(|s| s.recorded) { - if let Some((fence, value)) = &mark { + if let Some((fence, value, true)) = &mark { scratch.marks.insert(fence.as_raw() as usize, (fence.clone(), *value)); } else { // Without a completion mark the GPU could still access this buffer. @@ -2144,6 +2221,13 @@ pub(super) unsafe fn copy_scratch_submitted(queue: *mut c_void, lists: &[*mut c_ } } } + if !uploads.is_empty() { + // If Signal failed, a later successful signal on this queue can still reach its value. + // With no fence at all there is no safe completion point for these references. + let mark = mark.map(|(fence, value, _)| (fence, value)); + cache.uploads.push(SubmittedUploads { mark, _buffers: uploads }); + reap_copy_buffers(&mut cache); + } } unsafe fn make_copy_scratch(list: *mut c_void, bytes: u64) -> Option { @@ -2170,21 +2254,8 @@ unsafe fn device_of(list: *mut c_void) -> Option { dev } -/// upload buffers holding a repeated 16-byte pattern: (pattern, buffer, bytes) -static PATTERNS: Mutex> = Mutex::new(Vec::new()); - -/// A buffer of at least `n` bytes repeating `pat` (the device's upload heap). -unsafe fn pattern_buffer(list: *mut c_void, pat: [u8; 16], n: u64) -> Option { - let mut cache = PATTERNS.lock().unwrap(); - if let Some((_, b, _)) = cache.iter().find(|(p, _, len)| *p == pat && *len >= n) { - return Some(b.as_raw() as usize); - } - // a larger one replaces an older pattern buffer only when nothing may still read it: kept - if cache.len() >= 32 { - return None; - } +unsafe fn create_mapped_upload(list: *mut c_void, len: u64) -> Option<(ID3D12Resource, *mut u8)> { let dev = device_of(list)?; - let len = n.next_power_of_two().max(0x1_0000); let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: len, @@ -2208,7 +2279,25 @@ unsafe fn pattern_buffer(list: *mut c_void, pat: [u8; 16], n: u64) -> Option> = Mutex::new(Vec::new()); + +/// A buffer of at least `n` bytes repeating `pat` (the device's upload heap). +unsafe fn pattern_buffer(list: *mut c_void, pat: [u8; 16], n: u64) -> Option { + let mut cache = PATTERNS.lock().unwrap(); + if let Some((_, b, _)) = cache.iter().find(|(p, _, len)| *p == pat && *len >= n) { + return Some(b.as_raw() as usize); + } + // a larger one replaces an older pattern buffer only when nothing may still read it: kept + if cache.len() >= 32 { + return None; + } + let len = n.next_power_of_two().max(0x1_0000); + let (b, p) = create_mapped_upload(list, len)?; + for chunk in std::slice::from_raw_parts_mut(p, len as usize).chunks_exact_mut(16) { chunk.copy_from_slice(&pat); } b.Unmap(0, None); @@ -2923,11 +3012,12 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let write64_signals = s.clear_write64_signals(); s.written_ranges.clear(); let cpu_writes = std::mem::take(&mut s.cpu_writes); + let uploads = std::mem::take(&mut s.pending_uploads); let pred_in_state = std::mem::replace(&mut s.pred_in_state, false); let pred_buf = s.pred_buf.as_ref().map(|r| r.as_raw() as usize); - (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, waits, (sparse_writes, write64_signals, cpu_writes)) + (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, waits, (sparse_writes, write64_signals, cpu_writes, uploads)) }; - let (sparse_writes, write64_signals, cpu_writes) = sparse_writes; + let (sparse_writes, write64_signals, cpu_writes, uploads) = sparse_writes; // End any active occlusion query before Close (PC forbids closing with an open query). if let Some(((h, i), qty)) = active_query { @@ -2957,8 +3047,9 @@ 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| { + let uploads = fill_uploads(chunk); exec(q_raw, chunk.len() as u32, chunk.as_ptr()); - copy_scratch_submitted(q_raw, chunk); + copy_buffers_submitted(q_raw, chunk, uploads); super::alloc_pool::executed(q_raw, chunk); signal_write64_fences(q_raw, chunk); readback_sparse_writes(q_raw, chunk); @@ -2974,10 +3065,11 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if !waits.is_empty() { wait_all_on(q_raw, &waits, &write64_signals); } + let uploads = uploads.into_iter().map(|u| u.fill()).collect(); let one = [this]; exec(q_raw, 1, one.as_ptr()); - copy_scratch_submitted(q_raw, &one); + copy_buffers_submitted(q_raw, &one, uploads); super::alloc_pool::executed(q_raw, &one); signal_write64_pairs(q_raw, &write64_signals); // what ran is in the textures' states; the list records anew after its Reset below @@ -3019,6 +3111,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { s.clear_write64_signals(); s.clear_waits(); s.cpu_writes.clear(); + s.pending_uploads.clear(); s.bindings = bindings_copy; } primary @@ -3630,6 +3723,7 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz s.clear_write64_signals(); s.clear_waits(); s.cpu_writes.clear(); + s.pending_uploads.clear(); s.predication = None; s.pred_in_state = false; s.bindings = Bindings::default(); @@ -4067,6 +4161,95 @@ mod tests { use super::*; use std::sync::Arc; + #[test] + fn staged_copy_waits_for_its_own_queue_without_blocking_cpu_writes() { + use std::io::Write; + use windows::core::IUnknown; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + + // Other tests use the process's default D3D12 device and expect its queues to be idle. + const CHILD: &str = "XCL_TEST_HELD_COPY_CHILD"; + if std::env::var_os(CHILD).is_none() { + let thread = std::thread::current(); + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", thread.name().unwrap(), "--nocapture"]) + .env(CHILD, "1").output().unwrap(); + std::io::stderr().write_all(&result.stderr).unwrap(); + assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stdout)); + return; + } + + unsafe fn refs(buffer: &ID3D12Resource) -> u32 { + let raw = buffer.clone().into_raw(); + (IUnknown::from_raw_borrowed(&raw).unwrap().vtable().Release)(raw) + } + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let desc = D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }; + let held: ID3D12CommandQueue = dev.CreateCommandQueue(&desc).unwrap(); + let free: ID3D12CommandQueue = dev.CreateCommandQueue(&desc).unwrap(); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let (upload, mapped) = create_mapped_upload(list.as_raw(), 4).unwrap(); + let mut readback: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, &upload.GetDesc(), D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback).unwrap(); + let readback = readback.unwrap(); + list.CopyBufferRegion(&readback, 0, &upload, 0, 4); + list.Close().unwrap(); + let source = 0x1234_abcdu32; + let initial = refs(&upload); // keep our reference even if XCL releases its own too early + on_create(list.as_raw(), alloc.as_raw() as usize, 0, ty); + LISTS.lock().unwrap().as_mut().unwrap().get_mut(&(list.as_raw() as usize)).unwrap().pending_uploads.push( + PendingUpload { src: &source as *const u32 as usize, size: 4, mapped: mapped as usize, buf: upload.clone() }); + real::adopt(held.as_raw(), real::Kind::CommandQueue); + held.Wait(&gate, 1).unwrap(); + held.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + held.Signal(&done, 1).unwrap(); + on_release(list.as_raw() as usize); + + static WRITTEN: AtomicU32 = AtomicU32::new(0); + let start = Instant::now(); + use super::super::cpu_writes; + cpu_writes::after(free.as_raw(), vec![cpu_writes::Write::Immediate(&WRITTEN as *const _ as usize, vec![7])]); + while WRITTEN.load(Ordering::Acquire) == 0 && start.elapsed() < Duration::from_secs(12) { + std::thread::sleep(Duration::from_millis(1)); + } + let independent_write = start.elapsed(); + // The old CPU-write worker relinquished the buffer after its ten-second watchdog. + std::thread::sleep(Duration::from_millis(10_250).saturating_sub(start.elapsed())); + let pending = done.GetCompletedValue(); + let held_refs = refs(&upload); + gate.Signal(1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 5000).unwrap(); + let mut data = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut data)).unwrap(); + let actual = data.cast::().read(); + readback.Unmap(0, None); + let release = Instant::now(); + while refs(&upload) > initial && release.elapsed() < Duration::from_secs(2) { + std::thread::sleep(Duration::from_millis(1)); + } + let final_refs = refs(&upload); + eprintln!("independent write {independent_write:?}, held fence {pending}, upload refs {initial}/{held_refs}/{final_refs}, readback {actual:#010x}"); + assert_eq!(pending, 0); + assert_eq!(actual, source); + assert!(held_refs > initial, "the blocked queue still needs the upload"); + assert_eq!(final_refs, initial); + assert_eq!(WRITTEN.load(Ordering::Acquire), 7); + assert!(independent_write < Duration::from_secs(5), "an unrelated upload delayed the write"); + } + } + #[test] fn copy_scratch_budget_counts_resources_until_gpu_completion() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ac7ab4c4d..341f7693b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5401,8 +5401,9 @@ 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 uploads = super::list_x::fill_uploads(chunk); f(this, chunk.len() as u32, chunk.as_ptr()); - super::list_x::copy_scratch_submitted(this, chunk); + super::list_x::copy_buffers_submitted(this, chunk, uploads); super::alloc_pool::executed(this, chunk); super::list_x::signal_write64_fences(this, chunk); super::list_x::readback_sparse_writes(this, chunk); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ada439cba..241e59812 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -401,13 +401,37 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, /// before its first use too, while it is still reserved memory (`kernelx::physical_page_at`). fn mirror_source(va: usize) -> usize { let Some(src) = crate::hle::kernelx::mirrors::source(va) else { return va }; + mirror_source_span(va, src).0 +} + +/// The address to read and how far the choice between the two views holds. +fn mirror_source_span(va: usize, cpu: usize) -> (usize, usize) { + let page = crate::hle::kernelx::PHYS_PAGE_SIZE; + let remaining = page - va % page; if crate::hle::kernelx::physical_page_at(va) { - return va; + return (va, remaining); } use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - let mapped = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0 && m.State == MEM_COMMIT; - if mapped { va } else { src } + if unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return (cpu, remaining); + } + let span = m.RegionSize - (va - m.BaseAddress as usize); + (if m.State == MEM_COMMIT { va } else { cpu }, remaining.min(span)) +} + +/// Fill a copy upload from a registered GPU view. Page mappings may have changed since recording. +pub(super) unsafe fn copy_gpu_view(va: usize, dst: *mut u8, len: usize) -> bool { + let Some(cpu) = crate::hle::kernelx::mirrors::source_range(va, len) else { return false }; + std::ptr::write_bytes(dst, 0, len); + let mut offset = 0; + while offset < len { + let (src, span) = mirror_source_span(va + offset, cpu + offset); + let bytes = span.min(len - offset); + copy_committed_into(src, dst.add(offset), bytes); + offset += bytes; + } + true } /// Physical pages were mapped or unmapped in a GPU view since the last look: textures there @@ -1084,14 +1108,20 @@ unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { /// `len` bytes at `at`: the committed, readable pages copied, the rest zero (a streaming pool /// has only some of its pages mapped). unsafe fn read_committed(at: usize, len: usize) -> Vec { - use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; let mut out = vec![0u8; len]; - let Some(limit) = at.checked_add(len) else { return out }; + copy_committed_into(at, out.as_mut_ptr(), len); + out +} + +/// Copy readable spans into a pre-zeroed destination, leaving any gaps zero. +unsafe fn copy_committed_into(at: usize, dst: *mut u8, len: usize) { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let Some(limit) = at.checked_add(len) else { return }; // (the coherent window is committed as a whole: no `VirtualQuery`, which sizes a region by // walking it) 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); - return out; + std::ptr::copy_nonoverlapping(at as *const u8, dst, len); + return; } let mut p = at; while p < limit { @@ -1105,11 +1135,10 @@ unsafe fn read_committed(at: usize, len: usize) -> Vec { } let readable = m.State == MEM_COMMIT && m.Protect & 0xEE != 0 && m.Protect & 0x100 == 0; // R / RW / WC / X-R…, no guard if readable { - copy_committed_region(p, out.as_mut_ptr().add(p - at), end - p); + copy_committed_region(p, dst.add(p - at), end - p); } p = end; } - out } /// Batches of at least this many bytes are detiled on several threads (`subresources_of_all`) @@ -1921,6 +1950,41 @@ mod tests { } } + #[test] + fn copy_gpu_view_reads_each_mapping_and_leaves_holes_zero() { + use crate::hle::kernelx::{mirrors, PHYS_PAGE_SIZE as PAGE}; + use windows_sys::Win32::System::Memory as mem; + struct View(usize); + impl Drop for View { + fn drop(&mut self) { + mirrors::released(self.0); + unsafe { mem::VirtualFree(self.0 as *mut c_void, 0, mem::MEM_RELEASE); } + } + } + unsafe { + let reserve = |protect| { + let at = mem::VirtualAlloc(std::ptr::null(), 3 * PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE); + assert!(!at.is_null()); + mirrors::reserved(at as usize, 3 * PAGE, 0x2040_2000, protect); + View(at as usize) + }; + let cpu = reserve(mem::PAGE_READWRITE); + let gpu = reserve(0x801); + let back = mem::VirtualAlloc(cpu.0 as *const _, 2 * PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE); + let direct = mem::VirtualAlloc((gpu.0 + PAGE) as *const _, 4096, mem::MEM_COMMIT, mem::PAGE_READWRITE); + assert!(!back.is_null() && !direct.is_null()); + std::ptr::write_bytes(back.cast::(), 0x22, 2 * PAGE); + std::ptr::write_bytes(direct.cast::(), 0x33, 4096); + let mut bytes = [0xFF; 8]; + for (boundary, left, right) in [(PAGE, 0x22, 0x33), (PAGE + 4096, 0x33, 0x22), (2 * PAGE, 0x22, 0)] { + assert!(copy_gpu_view(gpu.0 + boundary - 4, bytes.as_mut_ptr(), bytes.len())); + assert_eq!(bytes, [left, left, left, left, right, right, right, right]); + } + assert!(!copy_gpu_view(gpu.0 + 3 * PAGE - 4, bytes.as_mut_ptr(), bytes.len())); + assert_eq!(bytes, [0x22, 0x22, 0x22, 0x22, 0, 0, 0, 0]); + } + } + /// `read_committed` copies committed pages and leaves uncommitted gaps zeroed, including /// unaligned start/end offsets. #[test] diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 8aa3bc200..dda1bbdd7 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -209,9 +209,16 @@ pub mod mirrors { /// The CPU-view address behind `va` when `va` lies in a GPU view. pub fn source(va: usize) -> Option { + source_range(va, 1) + } + + /// The corresponding CPU address when the whole nonempty range lies in one GPU view. + pub fn source_range(va: usize, len: usize) -> Option { let s = STATE.lock().unwrap(); let (&gpu, &(size, cpu)) = s.gpu.range(..=va).next_back()?; - (va < gpu + size).then(|| cpu + (va - gpu)) + let offset = va - gpu; + if len == 0 || offset.checked_add(len)? > size { return None; } + cpu.checked_add(offset) } } diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index d84d465d9..20a9e5225 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -494,13 +494,28 @@ pub fn console_list_methods() -> Result<(), String> { let kickoff: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(slot(93)); // 1. Memory writes, timestamp, fill, copy, and same-list write-then-wait (must not deadlock) + let mut heap_src = vec![0u8; 64]; + // Reserve address space larger than the sparse windows so these are paired CPU and GPU + // views outside unified memory. Only the first CPU page needs backing. + let view_size = 13usize << 30; + let cpu = crate::XMemVirtualAlloc(std::ptr::null(), view_size, 0x2040_2000, 0, 4); + let gpu = crate::XMemVirtualAlloc(std::ptr::null(), view_size, 0x2040_2000, 0, 0x801); + ensure!(!cpu.is_null() && !gpu.is_null(), "reserve graphics views"); + ensure!(crate::XMemVirtualAlloc(cpu, 0x10000, 0x1000, 0, 4) == cpu, "commit the CPU view"); write32_bottom(l, at(0), 0x1234_5678, 0, 0); write64_top(l, at(8), 0x1122_3344_5566_7788, 0); write64_bottom(l, at(0x10), 0, 0, 1); // GPU timestamp fill32(l, at(0x100), 0x100, 0xABCD_EF01); copy(l, at(0x2000), at(0x1000), 64, 0); + copy(l, at(0x2100), heap_src.as_ptr() as u64, 64, 0); + copy(l, at(0x2300), gpu as u64, 64, 0); wait32(l, at(0), 3, 0x1234_5678, u32::MAX, 0); list.Close().map_err(e)?; + // Write the title heap after recording and before submitting. + for (i, b) in heap_src.iter_mut().enumerate() { + *b = i as u8 ^ 0xA5; + } + std::ptr::copy_nonoverlapping(heap_src.as_ptr(), cpu.cast(), 64); queue.ExecuteCommandLists(&[Some(list.cast::().map_err(e)?)]); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; wait(&queue, &fence, 1)?; @@ -511,11 +526,23 @@ pub fn console_list_methods() -> Result<(), String> { ensure!(r64(0x10) != 0, "no GPU timestamp"); ensure!((0..64).all(|i| r32(0x100 + 4 * i) == 0xABCD_EF01) && r32(0x200) == 0 && r32(0xFC) == 0, "FillMemoryWith32BitValueX"); ensure!((0..64).all(|i| *mem.add(0x2000 + i) == i as u8 ^ 0x5A) && *mem.add(0x2040) == 0, "CopyMemoryToMemoryX"); + ensure!((0..64).all(|i| *mem.add(0x2100 + i) == i as u8 ^ 0xA5) && *mem.add(0x2140) == 0, "CopyMemoryToMemoryX from title heap"); + let executed = (0..64).all(|i| *mem.add(0x2300 + i) == heap_src[i]) && *mem.add(0x2340) == 0; // 2. KickoffX (#93): flushes work to the GPU BEFORE Close() is called, then continues recording alloc.Reset().map_err(e)?; list.Reset(&alloc, None).map_err(e)?; + copy(l, at(0x2200), heap_src.as_ptr() as u64, 64, 0); + copy(l, at(0x2400), gpu as u64, 64, 0); + // A wait on a different, already-satisfied cell splits the list after this write. + write64_bottom(l, at(0x420), 1, 0, 0); + wait64(l, at(0x428), 3, 0, u64::MAX, 0); + copy(l, at(0x2480), gpu as u64, 64, 0); write32_bottom(l, at(0x400), 0x1111_2222, 0, 0); + for (i, b) in heap_src.iter_mut().enumerate() { + *b = i as u8 ^ 0x3C; + } + std::ptr::copy_nonoverlapping(heap_src.as_ptr(), cpu.cast(), 64); kickoff(l); // Wait for the kicked-off write on the GPU while the list is still open! let t0 = std::time::Instant::now(); @@ -525,6 +552,13 @@ pub fn console_list_methods() -> Result<(), String> { std::thread::sleep(std::time::Duration::from_millis(1)); } ensure!(r32(0x400) == 0x1111_2222, "KickoffX did not flush work before Close ({:#x})", r32(0x400)); + ensure!((0..64).all(|i| *mem.add(0x2200 + i) == i as u8 ^ 0x3C) && *mem.add(0x2240) == 0, "CopyMemoryToMemoryX from title heap before KickoffX"); + let kicked = [0x2400, 0x2480].into_iter().all(|dest| { + (0..64).all(|i| *mem.add(dest + i) == heap_src[i]) && *mem.add(dest + 64) == 0 + }); + ensure!(crate::VirtualFree(gpu, 0, 0x8000) != 0, "release the GPU view"); + ensure!(crate::VirtualFree(cpu, 0, 0x8000) != 0, "release the CPU view"); + ensure!(executed && kicked, "GPU-view copy at ExecuteCommandLists={executed}, KickoffX={kicked}"); // Continue recording on the same list and submit normally via Close + ExecuteCommandLists write32_bottom(l, at(0x404), 0x3333_4444, 0, 0); list.Close().map_err(e)?;