diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d809b1c2a2..ca01fd698c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -3789,7 +3789,7 @@ 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 } +pub(super) struct ReadyDownload { res: usize, generation: u64, target: usize, pages: Option>, format: u32, writes: Vec, ticket: PendingDownload } struct FenceDownloads { fence: ID3D12Fence, value: u64, downloads: Vec> } @@ -3868,7 +3868,7 @@ fn download_writes(res: usize, entry: &Entry, queue: WriterQueueId) -> Vec, device: ID3D12Device, source: ID3D12Resource, writes: Vec, plan: Option } +struct DownloadSnapshot { res: usize, generation: u64, target: usize, pages: Option>, format: u32, tex: Arc, device: ID3D12Device, source: ID3D12Resource, writes: Vec, plan: Option } pub(super) struct PreparedDownloads { id: WriterQueueId, snapshots: Vec } @@ -3892,7 +3892,7 @@ pub(super) unsafe fn prepare_downloads(queue: *mut c_void) -> PreparedDownloads 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, + Some(DownloadSnapshot { res, generation: entry.generation, target: entry.src, pages: if entry.paged { mapped_homes(entry.src, entry.tex.size() as usize) } else { None }, format: source.GetDesc().Format.0 as u32, tex: Arc::clone(&entry.tex), device, source, writes, plan: None }) }).collect() }; @@ -3944,7 +3944,7 @@ pub(super) unsafe fn submit_prepared_downloads(queue: *mut c_void, prepared: Pre 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 }); + ready.push(ReadyDownload { res: snapshot.res, generation: snapshot.generation, target: snapshot.target, pages: snapshot.pages, format: snapshot.format, writes: snapshot.writes, ticket: submitted.ticket }); } Ok(ready) } @@ -3986,7 +3986,16 @@ pub(super) unsafe fn tie_downloads(fence: *mut c_void, value: u64, downloads: Ve 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) }; + // (a texture over pages the title mapped: its bytes are where each page is kept, its own + // address is only reserved) + let current = match &download.pages { + Some(homes) => { + let mut bytes = vec![0u8; size]; + unsafe { texture_upload::PageMap::new(download.target, homes.clone()).copy(download.target, &mut bytes) }; + bytes + } + None => 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); @@ -3997,7 +4006,11 @@ fn publish_download(download: &ReadyDownload) -> Result { 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 written = match &download.pages { + Some(homes) => unsafe { write_changed_mapped_pages(download.target, homes, &mapped_homes(download.target, size).unwrap_or_default(), ¤t, &console) }, + None => unsafe { write_changed_pages(download.target, ¤t, &console) }, + }; + if !written { 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]; @@ -4036,24 +4049,46 @@ fn changed_page_runs(at: usize, old: &[u8], new: &[u8]) -> Vec<(usize, usize)> { runs } -/// 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. +/// Write changed 4 KiB pages without faulting if the title concurrently unmaps one. A changed +/// page that is committed must be writable; otherwise its fence remains hidden and retries. +/// A page the title has not committed (reserved or free) is left out: the title cannot read it, and +/// waiting for it held the fence back for good (a retail game's frame-pacing wait then never ended). +/// A mapped physical page that is only reserved until its first use (`kernelx::lazy`) is one the +/// title can read: it is committed first and written. /// Contiguous changed pages within a VM region are coalesced into one `WriteProcessMemory` call /// so publishing large GPU-written textures does not pay a per-4 KiB syscall and instruction-cache /// flush while holding `TEXTURES`. 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::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_FREE, MEM_RESERVE, PAGE_GUARD}; use windows_sys::Win32::System::Threading::GetCurrentProcess; if old.len() != new.len() { return false } let proc = GetCurrentProcess(); let mut region_end = 0usize; + // the end of the addresses whose lazy pages were committed already + let mut ensured = 0usize; for (mut offset, run_end) in changed_page_runs(at, old, new) { while offset < run_end { let Some(address) = at.checked_add(offset) else { return false }; if address >= region_end { 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 + let queried = VirtualQuery(address as *const c_void, &mut info, std::mem::size_of_val(&info)) != 0; + if queried && info.State == MEM_RESERVE && address >= ensured { + // (a kernel call does not fault a lazy page in: commit those of the run, ask again) + ensured = at.saturating_add(run_end); + crate::hle::kernelx::lazy::ensure(address, ensured - address); + continue; + } + if queried && (info.State == MEM_RESERVE || info.State == MEM_FREE) { + let skip_to = (info.BaseAddress as usize).saturating_add(info.RegionSize); + if skip_to <= address { + return false; + } + note_download_page_left_out("not committed", address); + offset = run_end.min(skip_to - at); + continue; + } + if !queried || info.State != MEM_COMMIT || info.Protect & 0xCC == 0 || info.Protect & PAGE_GUARD != 0 @@ -4079,6 +4114,48 @@ unsafe fn write_changed_pages(at: usize, old: &[u8], new: &[u8]) -> bool { true } +/// A download left bytes out at `at` (`why`): logged for the first two and then at powers of two. +fn note_download_page_left_out(why: &str, at: usize) { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a texture download left out a page at {at:#x} ({why}; {n} so far)"); + } +} + +/// Where each 64 KiB page of `[va, va + size)` is kept (`kernelx::mirrors::resolve`); None when +/// the title mapped none of them. +fn mapped_homes(va: usize, size: usize) -> Option> { + let mut at = Vec::new(); + crate::hle::kernelx::mirrors::resolve(va, size, &mut at)?; + Some(at) +} + +/// `write_changed_pages` for a texture at `at` over pages the title mapped: each 64 KiB page is +/// written where it is kept (`was`, the homes when the download was prepared). A page that shows +/// nothing takes no bytes, and neither does one whose home is another by `now`: the GPU wrote +/// what the earlier mapping showed, and those bytes must not reach the page mapped since. +unsafe fn write_changed_mapped_pages(at: usize, was: &[usize], now: &[usize], old: &[u8], new: &[u8]) -> bool { + const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; + if old.len() != new.len() { return false } + let first = at & !(PAGE - 1); + let mut done = 0; + while done < new.len() { + let a = at + done; + let (k, off) = ((a - first) / PAGE, a & (PAGE - 1)); + let n = (PAGE - off).min(new.len() - done); + let home = was.get(k).copied().unwrap_or(0); + // (bit 0: a page never named, kept at the CPU view's same offset) + if home != 0 && now.get(k) != Some(&home) { + note_download_page_left_out("mapped elsewhere since", a); + } else if home != 0 && !write_changed_pages((home & !1) + off, &old[done..done + n], &new[done..done + n]) { + return false; + } + done += n; + } + true +} + fn unschedule(download: &ReadyDownload) { unschedule_writes(download.res, download.generation, &download.writes); } @@ -7324,4 +7401,88 @@ pub(super) mod tests { VirtualFree(base as *mut c_void, 0, MEM_RELEASE); } } + + #[test] + fn write_changed_pages_leaves_out_pages_the_title_has_not_committed() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + unsafe { + let len = 4usize << 12; + let base = VirtualAlloc(std::ptr::null(), len, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + // Pages 0 and 3 committed, 1 and 2 only reserved (a sparse home not in use). + for page in [0usize, 3] { + assert_ne!(VirtualAlloc((base + (page << 12)) as *const c_void, 1 << 12, MEM_COMMIT, PAGE_READWRITE), std::ptr::null_mut()); + } + let old = vec![0u8; len]; + let new = vec![0x5au8; len]; + assert!(write_changed_pages(base, &old, &new), "reserved pages must not hold the download back"); + for page in [0usize, 3] { + let got = std::slice::from_raw_parts((base + (page << 12)) as *const u8, 1 << 12); + assert!(got.iter().all(|&b| b == 0x5a), "committed page {page} must be written"); + } + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A mapped physical page still reserved until its first use (`kernelx::lazy`) is memory the + /// title can read: a download commits it and writes it, where a plain reservation is left out. + #[test] + fn write_changed_pages_commits_a_lazy_page_and_writes_it() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; + unsafe { + let base = VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + // page 0 committed, page 1 lazy, page 2 a plain reservation + assert_ne!(VirtualAlloc(base as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE), std::ptr::null_mut()); + crate::hle::kernelx::lazy::mark(base + PAGE); + let old = vec![0u8; 3 * PAGE]; + let new = vec![0x5au8; 3 * PAGE]; + assert!(write_changed_pages(base, &old, &new)); + let got = std::slice::from_raw_parts(base as *const u8, 2 * PAGE); + assert!(got.iter().all(|&b| b == 0x5a), "the committed page and the lazy page hold the GPU's bytes"); + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(VirtualQuery((base + 2 * PAGE) as *const c_void, &mut m, std::mem::size_of_val(&m)), 0); + assert_eq!(m.State, MEM_RESERVE, "a plain reservation stays as it was"); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A download to a texture over pages the title mapped reaches each page where it is kept + /// (the texture's own address is only reserved), and not a page mapped there since. + #[test] + fn a_download_over_mapped_pages_is_written_where_they_are_kept() { + use crate::hle::kernelx::mirrors::PAGE; + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, PAGE_READWRITE}; + let _guard = TEST_LOCK.lock().unwrap(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let (cpu, gpu, pages, home) = paged_views(193 * PAGE, 2); + std::ptr::write_bytes(home as *mut u8, 0x5A, 2 * PAGE); + assert_eq!(VirtualAlloc(cpu as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE) as usize, cpu); + std::ptr::write_bytes(cpu as *mut u8, 0x77, PAGE); + // view page 0 never named, pool page 0 at view page 1, view page 2 unmapped + map_pages(gpu + PAGE, &[[0, 0, 1], [2, 0, 1]], home, 2); + let size = 3 * PAGE; + let was = mapped_homes(gpu, size).expect("a table"); + let mut old = vec![0u8; size]; + texture_upload::PageMap::new(gpu, was.clone()).copy(gpu, &mut old); + let new = vec![0xC3u8; size]; + let pool = |page: usize| std::slice::from_raw_parts((home + page * PAGE) as *const u8, PAGE); + // the view page shows pool page 1 by now: neither pool page takes the GPU's bytes + map_pages(gpu + PAGE, &[[0, 1, 1]], home, 2); + let now = mapped_homes(gpu, size).expect("a table"); + assert_ne!(was[1], now[1]); + assert!(write_changed_mapped_pages(gpu, &was, &now, &old, &new)); + assert!(pool(0).iter().chain(pool(1)).all(|&b| b == 0x5A), "a page mapped since is left alone"); + assert!(std::slice::from_raw_parts(cpu as *const u8, PAGE).iter().all(|&b| b == 0xC3), "a page never named: the CPU view"); + std::ptr::write_bytes(cpu as *mut u8, 0x77, PAGE); + // the mapping unchanged: the pool page takes them, the unmapped page holds nothing back + assert!(write_changed_mapped_pages(gpu, &was, &was, &old, &new)); + assert!(pool(0).iter().all(|&b| b == 0xC3), "the pool page where it is kept"); + assert!(pool(1).iter().all(|&b| b == 0x5A), "no other pool page"); + assert!(std::slice::from_raw_parts(cpu as *const u8, PAGE).iter().all(|&b| b == 0xC3)); + drop_paged_views(cpu, gpu, pages); + } + } }