diff --git a/README.md b/README.md index ad80ede978..d0f6e963bc 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif | **Pipelines** | ✅ | PSOs from console shaders: VS+PS, CS, MS+PS, VS+GS+PS; root signature with the shaders' static samplers; non-blocking creation – a pipeline whose shaders are not compiled yet gets a stand-in at once and is built in the background | GPU tests drawing the game's own VS / PS pairs, also built in the background | | **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers, clears, copies) | the game's BVH builder and FSR 4 record and run through XCL | | **D3D12.X graphics** | ✅ | device, resources and heaps (also placed in title memory), pipelines; the title's graphics command lists – draws, indirect draws, graphics root arguments, barriers, copies, clears – and command lists recorded by console code, replayed; `PresentX` and frame pacing into an XCL window | Minecraft Preview plays its worlds (millions of draws, none skipped); Fortnite and XDefiant draw their screens | -| **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes, the 6 3D thick modes, linear), mip chains with mip tail, arrays, cubes and 3D textures → PC textures | 912 / 912 entries detiled in the tested retail archive; GPU upload bit exact in test fixtures | +| **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes, the 6 3D thick modes, linear), mip chains with mip tail, arrays, cubes and 3D textures → PC textures; supported GPU-written title subresources copy back before their writer queue's title fence becomes visible | 912 / 912 entries detiled in the tested retail archive; GPU upload bit exact in test fixtures | | **Ray tracing** | ✅ | BLAS / TLAS built on the GPU by the game's own XboxBvhBuilder; RDNA2 BVH node format; BVH intersection instructions emulated in shaders | GPU traversal = brute force reference; the game's builder output checked on the GPU | | **Upscaling** | ✅ | the game's AMD FSR 4 console DLL (`amd_fidelityfx_upscaler_xbox.dll`): context, the 29 pipelines in the console driver's own container (FSPX) translated, a frame's 20 passes recorded and run on the GPU | end-to-end with the real DLL: a 1280×720 → 1920×1080 frame on an RX 9070, the input's gradient in the output | diff --git a/crates/xcl/src/hle/d3d12x/fence_x.rs b/crates/xcl/src/hle/d3d12x/fence_x.rs index f6ca932d71..babd5744fb 100644 --- a/crates/xcl/src/hle/d3d12x/fence_x.rs +++ b/crates/xcl/src/hle/d3d12x/fence_x.rs @@ -56,7 +56,9 @@ impl FenceTable { return; } if let Some(v) = unsafe { borrowed(fence, |f| f.GetCompletedValue()) } { - mirror.cell.0.store(v, Ordering::Release); + if super::title_textures::complete_fence_downloads(fence, v) { + mirror.cell.0.store(v, Ordering::Release); + } } } @@ -153,6 +155,7 @@ fn event() -> usize { let e = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) as usize; let spawned = std::thread::Builder::new().name("xcl-fences".into()).spawn(move || loop { th::WaitForSingleObject(e as _, th::INFINITE); + super::title_textures::poll_fence_downloads(); table().refresh(); }); if let Err(err) = spawned { @@ -162,6 +165,10 @@ fn event() -> usize { }) } +pub(super) fn wake_event() -> HANDLE { + HANDLE(event() as *mut c_void) +} + unsafe fn borrowed(fence: usize, f: impl FnOnce(&ID3D12Fence) -> R) -> Option { let p = fence as *mut c_void; ID3D12Fence::from_raw_borrowed(&p).map(f) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 70cacdb6a8..4cd9d5dc74 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1141,7 +1141,7 @@ fn new_queue_id(raw: usize) -> super::title_textures::WriterQueueId { super::title_textures::WriterQueueId { raw, generation } } -fn queue_identity(raw: usize) -> Option { +pub(super) fn queue_identity(raw: usize) -> Option { LIVE_QUEUES.lock().unwrap().iter().find(|q| q.queue == raw).map(|q| q.id) } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4eeed195de..3558b6c134 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -694,6 +694,14 @@ pub(crate) unsafe fn native_queue_wait(queue: &ID3D12CommandQueue, fence: &ID3D1 }) } +pub(crate) unsafe fn native_fence_completed(fence: &ID3D12Fence) -> u64 { + let raw = fence.as_raw(); + let slot = std::mem::offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / std::mem::size_of::(); + type F = unsafe extern "system" fn(*mut c_void) -> u64; + let f: F = std::mem::transmute(if is_ext(vt(raw) as usize) { orig_fn(raw, slot) } else { *vt(raw).add(slot) }); + f(raw) +} + #[cfg(test)] pub(super) fn register_test_queue_vtable(ext: usize, add: bool) { let mut tables = EXTS.lock().unwrap(); @@ -3043,7 +3051,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { Kind::PipelineState => v.push(("Release", pso_release as usize)), Kind::DescriptorHeap => v.push(("Release", heap_release as usize)), Kind::Heap => v.push(("Release", mem_heap_release as usize)), - Kind::Fence => v.push(("Signal", fence_signal as usize)), + Kind::Fence => v.extend_from_slice(&[("GetCompletedValue", fence_completed as usize), ("Signal", fence_signal as usize)]), _ => {} } v @@ -8830,21 +8838,40 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a let older = if shifted && slot >= 16 { slot - 2 } else if shifted { usize::MAX } else { slot }; let pc = |s: usize| orig_fn(this, s); match older { - // Signal / Wait take a fence: anything else is not one of them - 14 | 15 if is_fence(a1) => super::queue_submit::with(this as usize, || { - if older == 14 { + // Signal takes a fence: prepare outside the turn, then validate/insert atomically with it. + 14 if is_fence(a1) => loop { + let prepared = super::title_textures::prepare_downloads(this); + let attempt = super::queue_submit::with(this as usize, || { + let downloads = match super::title_textures::submit_prepared_downloads(this, prepared) { + Ok(downloads) => downloads, + Err(super::title_textures::SubmitDownloadsError::Stale) => return Err(None), + Err(super::title_textures::SubmitDownloadsError::Failed(error)) => return Err(Some(error)), + }; 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); - if hr >= 0 { - if older == 14 { + super::title_textures::tie_downloads(a1 as *mut c_void, a2 as u64, downloads); + let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(PC_SIGNAL)); + let hr = f(this, a1, a2); + if hr >= 0 { super::fence_x::note_queue_signal(a1, a2 as u64); super::list_x::note_title_queue_signal(this as usize, a1, a2 as u64); - } else { - super::fence_x::note_queue_wait(a1, a2 as u64); - super::list_x::note_title_queue_wait(this as usize, a1, a2 as u64); } + Ok(hr as u32 as usize) + }); + match attempt { + Ok(hr) => break hr, + Err(None) => continue, + Err(Some(error)) => { + crate::xlog_warn!("D3D12.X: {error}; title queue Signal not submitted"); + break crate::util::E_FAIL as u32 as usize; + } + } + }, + 15 if is_fence(a1) => super::queue_submit::with(this as usize, || { + let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(PC_WAIT)); + let hr = f(this, a1, a2); + if hr >= 0 { + super::fence_x::note_queue_wait(a1, a2 as u64); + super::list_x::note_title_queue_wait(this as usize, a1, a2 as u64); } hr as u32 as usize }), @@ -8927,22 +8954,39 @@ queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, /// nothing left Fortnite's render fences pending: its render thread waited, textures were /// never released, and the garbage collector ended the game after 10 s.) unsafe extern "system" fn q_signal_x(this: *mut c_void, fence: *mut c_void, value: u64, _flags: u32) -> HRESULT { - super::queue_submit::with(this as usize, || q_signal_x_serialized(this, fence, value)) + loop { + let prepared = super::title_textures::prepare_downloads(this); + match super::queue_submit::with(this as usize, || q_signal_x_serialized(this, fence, value, prepared)) { + Ok(hr) => return hr, + Err(super::title_textures::SubmitDownloadsError::Stale) => continue, + Err(super::title_textures::SubmitDownloadsError::Failed(error)) => { + crate::xlog_warn!("D3D12.X: {error}; title queue SignalX not submitted"); + return crate::util::E_FAIL; + } + } + } } -unsafe fn q_signal_x_serialized(this: *mut c_void, fence: *mut c_void, value: u64) -> HRESULT { +unsafe fn q_signal_x_serialized(this: *mut c_void, fence: *mut c_void, value: u64, prepared: super::title_textures::PreparedDownloads) -> Result { const PC_SIGNAL: usize = 14; + let downloads = super::title_textures::submit_prepared_downloads(this, prepared)?; super::list_x::break_cycles_before_title_signal(this as usize, fence as usize, value); + super::title_textures::tie_downloads(fence, value, downloads); 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); 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); } - hr + Ok(hr) } /// Fence::Signal (CPU) +unsafe extern "system" fn fence_completed(this: *mut c_void) -> u64 { + let f: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(orig_fn(this, slot_of(this, "GetCompletedValue"))); + super::title_textures::safe_fence_value(this as usize, f(this)) +} + unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT { let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Signal"))); let hr = f(this, value); @@ -9603,7 +9647,7 @@ mod readback_routing_tests { mod queue_tests { use super::*; use std::mem::{offset_of, size_of}; - use windows::Win32::Graphics::Direct3D12::ID3D12Fence_Vtbl; + use windows::Win32::Graphics::Direct3D12::{ID3D12CommandQueue_Vtbl, ID3D12Fence_Vtbl}; // a fake adopted queue: the extension vtable's word before slot 0 points at the PC table unsafe extern "system" fn get_desc(_: *mut c_void, out: usize) -> usize { @@ -9647,8 +9691,10 @@ mod queue_tests { let mut pc = [0usize; 32]; pc[14] = signal as usize; pc[18] = get_desc as usize; - let ext = [pc.as_ptr() as usize, 0]; - let vtbl = ext.as_ptr() as usize + 8; + let mut ext = [0usize; 1 + size_of::() / SLOT]; + ext[0] = pc.as_ptr() as usize; + ext[1 + offset_of!(ID3D12CommandQueue_Vtbl, GetDesc) / SLOT] = get_desc as usize; + let vtbl = unsafe { ext.as_ptr().add(1) } as usize; let mut obj = [vtbl]; let this = obj.as_mut_ptr() as *mut c_void; // A valid minimal ID3D12Fence COM object while registered: if a parallel test inspects diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index a06e1146bf..6373f5907c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -19,9 +19,9 @@ //! transitions of these textures are captured in each physical command-list segment's immutable //! submission effects and applied in submission order – per subresource once one is named. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::ffi::c_void; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use windows::core::Interface; @@ -2080,7 +2080,7 @@ pub(super) struct PendingDownload { impl Drop for PendingDownload { fn drop(&mut self) { let done = self.fence_value.is_some_and(|v| { - let got = unsafe { self.fence.GetCompletedValue() }; + let got = unsafe { super::real::native_fence_completed(&self.fence) }; got != u64::MAX && got >= v }); if !done { @@ -2095,7 +2095,7 @@ impl Drop for PendingDownload { impl PendingDownload { pub fn is_complete(&self) -> bool { self.fence_value.is_some_and(|v| { - let got = unsafe { self.fence.GetCompletedValue() }; + let got = unsafe { super::real::native_fence_completed(&self.fence) }; got != u64::MAX && got >= v }) } @@ -2124,6 +2124,10 @@ impl PendingDownload { pub fn footprints(&self) -> &[DownloadSubresource] { &self.footprints } pub fn layout(&self) -> &xg::Texture { &self.tex } + + fn arm(&self, event: windows::Win32::Foundation::HANDLE) { + if let Some(value) = self.fence_value { unsafe { let _ = self.fence.SetEventOnCompletion(value, event); } } + } } #[allow(dead_code)] @@ -2163,6 +2167,273 @@ impl TextureDownloadPlan { } } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DownloadWrite { subresource: u32, state: D3D12_RESOURCE_STATES, writer: GpuWriter } + +pub(super) struct ReadyDownload { res: usize, generation: u64, target: usize, format: u32, writes: Vec, ticket: PendingDownload } + +struct FenceDownloads { fence: ID3D12Fence, value: u64, downloads: Vec> } + +static FENCE_DOWNLOADS: Mutex> = Mutex::new(Vec::new()); +static DOWNLOADS_PENDING: AtomicBool = AtomicBool::new(false); +static SCHEDULED_DOWNLOADS: Mutex> = Mutex::new(BTreeSet::new()); +static SAFE_FENCE_VALUES: Mutex> = Mutex::new(BTreeMap::new()); + +fn writer_at(entry: &Entry, subresource: usize) -> Option { + match entry.gpu_writers.as_slice() { + [] => None, [writer] => *writer, writers => writers.get(subresource).copied().flatten(), + } +} + +fn download_writes(res: usize, entry: &Entry, queue: WriterQueueId) -> Vec { + let n = subresource_count(&entry.tex); + let scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + (0..n).filter_map(|subresource| { + let writer = writer_at(entry, subresource)?; + (writer.queue == queue && !scheduled.contains(&(res, entry.generation, writer.queue.generation, subresource as u32, writer.epoch))) + .then(|| DownloadWrite { subresource: subresource as u32, state: if entry.states.len() == n { entry.states[subresource] } else { entry.states[0] }, writer }) + }).collect() +} + +struct DownloadSnapshot { res: usize, generation: u64, target: usize, format: u32, tex: Arc, device: ID3D12Device, source: ID3D12Resource, writes: Vec, plan: Option } + +pub(super) struct PreparedDownloads { id: WriterQueueId, snapshots: Vec } + +pub(super) enum SubmitDownloadsError { Stale, Failed(String) } + +fn download_current(entry: &Entry, generation: u64, target: usize, writes: &[DownloadWrite]) -> bool { + entry.generation == generation && entry.src == target && writes.iter().all(|w| writer_at(entry, w.subresource as usize) == Some(w.writer)) +} + +/// Build readback lists outside the queue turn. The state is validated again at insertion. +/// Writes owned by another queue are left for a signal on that exact queue. +pub(super) unsafe fn prepare_downloads(queue: *mut c_void) -> PreparedDownloads { + let id = super::list_x::queue_identity(queue as usize).unwrap_or(WriterQueueId { raw: queue as usize, generation: 0 }); + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return PreparedDownloads { id, snapshots: Vec::new() } }; + let queue_type = q.GetDesc().Type; + if !download_queue_type_supported(queue_type) { return PreparedDownloads { id, snapshots: Vec::new() } } + let candidates: Vec = { + let table = TEXTURES.lock().unwrap(); + table.by_res.iter().filter_map(|(&res, entry)| { + let writes = download_writes(res, entry, id); + if writes.is_empty() { return None } + let source = ID3D12Resource::from_raw_borrowed(&(res as *mut c_void))?.clone(); + let device = ID3D12Device::from_raw_borrowed(&(entry.device as *mut c_void))?.clone(); + Some(DownloadSnapshot { res, generation: entry.generation, target: entry.src, format: source.GetDesc().Format.0 as u32, + tex: Arc::clone(&entry.tex), device, source, writes, plan: None }) + }).collect() + }; + let mut snapshots = Vec::new(); + for mut snapshot in candidates { + let selected: Vec<_> = snapshot.writes.iter().map(|w| (w.subresource, w.state)).collect(); + let Ok(plan) = prepare_texture_download(&snapshot.device, &snapshot.source, queue_type, Arc::clone(&snapshot.tex), snapshot.format, &selected) else { continue }; + snapshot.plan = Some(plan); + snapshots.push(snapshot); + } + PreparedDownloads { id, snapshots } +} + +/// Validate and insert prepared lists while the caller owns `queue`'s turn. A stale snapshot +/// submits nothing, so the caller can rebuild outside the turn and retry. +pub(super) unsafe fn submit_prepared_downloads(queue: *mut c_void, prepared: PreparedDownloads) -> Result, SubmitDownloadsError> { + if prepared.snapshots.is_empty() { return Ok(Vec::new()) } + if super::list_x::queue_identity(queue as usize) != Some(prepared.id) { return Err(SubmitDownloadsError::Stale) } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return Ok(Vec::new()) }; + let table = TEXTURES.lock().unwrap(); + let mut scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + let valid = prepared.snapshots.iter().all(|snapshot| { + table.by_res.get(&snapshot.res).is_some_and(|entry| { + entry.generation == snapshot.generation + && entry.src == snapshot.target + && snapshot.writes.iter().all(|w| { + !scheduled.contains(&(snapshot.res, snapshot.generation, w.writer.queue.generation, w.subresource, w.writer.epoch)) + && + writer_at(entry, w.subresource as usize) == Some(w.writer) + && (if entry.states.len() == subresource_count(&entry.tex) { + entry.states[w.subresource as usize] + } else { + entry.states[0] + }) == w.state + }) + }) + }); + if !valid { return Err(SubmitDownloadsError::Stale) } + let keys: Vec<_> = prepared.snapshots.iter().flat_map(|snapshot| snapshot.writes.iter().map(|write| { + (snapshot.res, snapshot.generation, write.writer.queue.generation, write.subresource, write.writer.epoch) + })).collect(); + for &key in &keys { scheduled.insert(key); } + drop(scheduled); + drop(table); + let mut ready = Vec::new(); + for snapshot in prepared.snapshots { + let submitted = match snapshot.plan.unwrap().submit(q) { + Ok(submitted) => submitted, + Err(error) => { rollback_reservations(&keys); return Err(SubmitDownloadsError::Failed(error)) } + }; + if let Some(error) = submitted.signal_error { rollback_reservations(&keys); return Err(SubmitDownloadsError::Failed(format!("texture download completion signal failed: {error}"))) } + ready.push(ReadyDownload { res: snapshot.res, generation: snapshot.generation, target: snapshot.target, format: snapshot.format, writes: snapshot.writes, ticket: submitted.ticket }); + } + Ok(ready) +} + +fn rollback_reservations(keys: &[(usize, u64, u64, u32, u64)]) { + let mut scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + for key in keys { scheduled.remove(key); } +} + +/// Tie already-submitted readbacks to the title fence queued immediately after them. +pub(super) unsafe fn tie_downloads(fence: *mut c_void, value: u64, downloads: Vec) { + if downloads.is_empty() { return } + let Some(fence) = ID3D12Fence::from_raw_borrowed(&fence).cloned() else { return }; + SAFE_FENCE_VALUES.lock().unwrap().insert(fence.as_raw() as usize, super::real::native_fence_completed(&fence)); + let event = super::fence_x::wake_event(); + for download in &downloads { download.ticket.arm(event); } + { + let mut scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + for download in &downloads { for write in &download.writes { + scheduled.insert((download.res, download.generation, write.writer.queue.generation, write.subresource, write.writer.epoch)); + } } + } + FENCE_DOWNLOADS.lock().unwrap().push(FenceDownloads { fence: fence.clone(), value, downloads: downloads.into_iter().map(Some).collect() }); + DOWNLOADS_PENDING.store(true, Ordering::Release); + let _ = fence.SetEventOnCompletion(value, event); +} + +fn publish_download(download: &ReadyDownload) -> Result { + let Some(readback) = (unsafe { download.ticket.readback_bytes()? }) else { return Ok(false) }; + let size = usize::try_from(download.ticket.layout().size()).map_err(|_| "texture download destination is too large")?; + let current = unsafe { with_title_bytes(download.target, size, <[u8]>::to_vec) }; + let mut console = Vec::new(); + console.try_reserve_exact(size).map_err(|_| "cannot allocate texture download destination")?; + console.extend_from_slice(¤t); + for (write, footprint) in download.writes.iter().zip(download.ticket.footprints()) { + reverse_layout_subresource(download.ticket.layout(), download.format, write.subresource, footprint.footprint, &readback, &mut console) + .map_err(|e| format!("cannot reverse texture download layout: {e:?}"))?; + } + let mut table = TEXTURES.lock().unwrap(); + let Some(entry) = table.by_res.get_mut(&download.res) else { return Ok(true) }; + if !download_current(entry, download.generation, download.target, &download.writes) { return Ok(true) } + if !unsafe { write_changed_pages(download.target, ¤t, &console) } { return Ok(false) } + let n = subresource_count(&entry.tex); + if entry.gpu_writers.len() != n { + entry.gpu_writers = vec![entry.gpu_writers.first().copied().flatten(); n]; + } + for write in &download.writes { + let slot = &mut entry.gpu_writers[write.subresource as usize]; + if *slot == Some(write.writer) { *slot = None; } + } + if entry.gpu_writers.iter().all(Option::is_none) { + entry.gpu_writers.clear(); + entry.gpu_written = false; + } + Ok(true) +} + +/// Write changed 4 KiB pages without faulting if the title concurrently unmaps one. Every +/// changed page must be committed and writable; otherwise its fence remains hidden and retries. +unsafe fn write_changed_pages(at: usize, old: &[u8], new: &[u8]) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_GUARD}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + if old.len() != new.len() { return false } + let mut offset = 0; + while offset < new.len() { + let end = (((at + offset) & !4095) + 4096).saturating_sub(at).min(new.len()); + if old[offset..end] == new[offset..end] { offset = end; continue } + let address = at + offset; + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(address as *const c_void, &mut info, std::mem::size_of_val(&info)) == 0 + || info.State != MEM_COMMIT + || info.Protect & 0xCC == 0 + || info.Protect & PAGE_GUARD != 0 + || (info.BaseAddress as usize).saturating_add(info.RegionSize) < at + end + { + return false; + } + let mut written = 0; + if WriteProcessMemory(GetCurrentProcess(), address as *const c_void, new[offset..end].as_ptr() as *const c_void, end - offset, &mut written) == 0 + || written != end - offset { + return false; + } + offset = end; + } + true +} + +fn unschedule(download: &ReadyDownload) { + unschedule_writes(download.res, download.generation, &download.writes); +} + +fn unschedule_writes(res: usize, generation: u64, writes: &[DownloadWrite]) { + let mut scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + for write in writes { scheduled.remove(&(res, generation, write.writer.queue.generation, write.subresource, write.writer.epoch)); } +} + +fn batch_ready(blocked: &mut bool, target: u64, completed: u64) -> bool { + if *blocked || target > completed { *blocked = true; false } else { true } +} + +/// Apply every completed download through `value`. False withholds the title's mirrored fence +/// value until a transiently unavailable readback or destination can be retried. +pub(super) fn complete_fence_downloads(fence: usize, value: u64) -> bool { + if !DOWNLOADS_PENDING.load(Ordering::Acquire) { return true } + let mut batches = FENCE_DOWNLOADS.lock().unwrap(); + let mut ok = true; + let mut blocked = false; + for batch in batches.iter_mut().filter(|b| b.fence.as_raw() as usize == fence) { + if !batch_ready(&mut blocked, batch.value, value) { ok &= batch.value > value; continue } + for download in &mut batch.downloads { + let Some(ready) = download.as_ref() else { continue }; + match publish_download(ready) { + Ok(true) => { + unschedule(ready); + *download = None; + } + Ok(false) => { + ok = false; + blocked = true; + } + Err(error) => { + crate::xlog_warn!("D3D12.X: {error}; holding title fence {fence:#x} at {value:#x}"); + ok = false; + blocked = true; + } + } + } + blocked |= batch.downloads.iter().any(Option::is_some); + } + batches.retain(|batch| batch.downloads.iter().any(Option::is_some)); + DOWNLOADS_PENDING.store(!batches.is_empty(), Ordering::Release); + if ok { + SAFE_FENCE_VALUES.lock().unwrap().entry(fence).and_modify(|safe| *safe = (*safe).max(value)).or_insert(value); + } + ok +} + +pub(super) fn safe_fence_value(fence: usize, native: u64) -> u64 { + if !DOWNLOADS_PENDING.load(Ordering::Acquire) { return native } + if native != u64::MAX && complete_fence_downloads(fence, native) { + native + } else { + SAFE_FENCE_VALUES.lock().unwrap().get(&fence).copied().unwrap_or(0) + } +} + +/// Poll pending title fences even when a title never requested a completed-value mirror. +pub(super) fn poll_fence_downloads() { + if !DOWNLOADS_PENDING.load(Ordering::Acquire) { return } + let pending: Vec<_> = { + let batches = FENCE_DOWNLOADS.lock().unwrap(); + batches.iter().map(|batch| batch.fence.clone()).collect() + }; + for fence in pending { + let value = unsafe { super::real::native_fence_completed(&fence) }; + if value != u64::MAX { + let _ = complete_fence_downloads(fence.as_raw() as usize, value); + } + } +} + fn download_queue_type_supported(ty: D3D12_COMMAND_LIST_TYPE) -> bool { matches!(ty, D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE) } @@ -2772,8 +3043,24 @@ mod tests { let last = e.gpu_writers[4].unwrap(); assert_eq!(last.queue, q2); assert!(last.epoch > first_epoch); + let q1_writes = download_writes(res, e, q1); + let q2_writes = download_writes(res, e, q2); + assert_eq!(q1_writes.iter().map(|w| w.subresource).collect::>(), [2]); + assert_eq!(q2_writes.iter().map(|w| w.subresource).collect::>(), [4]); + let key = (res, generation, q1.generation, 2, first_epoch); + SCHEDULED_DOWNLOADS.lock().unwrap().insert(key); + assert!(download_writes(res, e, q1).is_empty(), "an in-flight epoch is not downloaded twice"); + SCHEDULED_DOWNLOADS.lock().unwrap().remove(&key); } + let stale = download_writes(res, &TEXTURES.lock().unwrap().by_res[&res], q1); + let key = (res, generation, q1.generation, 2, first_epoch); + SCHEDULED_DOWNLOADS.lock().unwrap().insert(key); + publish_gpu_writes(q2, &[GpuWrite { res, generation, subresource: 2 }]); + assert!(!download_current(&TEXTURES.lock().unwrap().by_res[&res], generation, 0x7E57_1000_0000, &stale)); + unschedule_writes(res, generation, &stale); + assert!(!SCHEDULED_DOWNLOADS.lock().unwrap().contains(&key)); + // Reusing the resource address creates another registration generation: a captured // effect from the old object must not mark it. { @@ -2787,6 +3074,23 @@ mod tests { TEXTURES.lock().unwrap().remove(res); } + #[test] + fn fence_download_batches_preserve_insertion_order() { + let mut blocked = false; + assert!(!batch_ready(&mut blocked, 20, 10)); + assert!(!batch_ready(&mut blocked, 5, 10), "later eligible batch passed an earlier one"); + blocked = true; + assert!(!batch_ready(&mut blocked, 10, 10), "later batch passed an incomplete one"); + } + + #[test] + fn download_reservation_rollback_clears_every_key() { + let keys = [(0xBAD0, 1, 2, 3, 4), (0xBAD1, 5, 6, 7, 8)]; + SCHEDULED_DOWNLOADS.lock().unwrap().extend(keys); + rollback_reservations(&keys); + assert!(keys.iter().all(|key| !SCHEDULED_DOWNLOADS.lock().unwrap().contains(key))); + } + /// A texture kept in step: the title's transitions count once their list is submitted, in /// submission order, each time it is; a Reset forgets them; other resources are not noted. #[test]