diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 302dcbe..c94146f 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -941,7 +941,8 @@ fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { /// Runs `fill` on the destination's first `len` bytes; `fill` returns how /// many it produced. GPU-visible destinations are host memory like the /// rest (GPU address = CPU address), so an address is written in place; -/// physical pages go through a buffer. +/// physical pages are too when they are consecutive pages of one +/// allocation, and otherwise go through a buffer. fn into_destination( request: &Request, len: usize, @@ -956,12 +957,22 @@ fn into_destination( let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::(), len) }; return fill(out).map(drop); } + let offset = (request.page_offset & 0xffff) as usize; + // SAFETY: the title passes a page number per 64 KiB of destination, + // which holds at least `len` bytes from `offset`. + let pages = unsafe { + std::slice::from_raw_parts( + request.destination.cast::(), + (offset + len).div_ceil(PAGE), + ) + }; + // Consecutive pages of one allocation (the usual case): written in + // place through one view. + if let Some(mut window) = super::xmem::page_window(pages, offset, len) { + return fill(window.bytes()).map(drop); + } let mut data = vec![0; len]; let n = fill(&mut data)?; - let offset = (request.page_offset & 0xffff) as usize; - let pages = (offset + n).div_ceil(PAGE); - // SAFETY: the title passes a page number per 64 KiB of destination. - let pages = unsafe { std::slice::from_raw_parts(request.destination.cast::(), pages) }; if super::xmem::write_physical(pages, offset, &data[..n]) { Ok(()) } else { @@ -1473,4 +1484,62 @@ mod tests { let seen = unsafe { std::slice::from_raw_parts(mapped.cast::().add(PAGE - 40), 100) }; assert_eq!(seen, plain); } + #[test] + fn zlib_into_pages_in_place_and_across_allocations() { + use crate::modules::xmem; + let allocate = |n: usize| { + let (mut pages, mut given) = (vec![0usize; n], n); + assert_eq!( + xmem::XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + pages + }; + let (a, b) = (allocate(3), allocate(1)); + let plain = pattern(2 * PAGE + 100); + let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + // One allocation's pages in order (one window), then pages of two + // (through a buffer), both from 50 bytes into the first. + let mut destinations = [a.clone(), vec![a[0], a[1], b[0]]]; + let (queue, array) = (new_queue(1), status_array(1)); + for pages in &mut destinations { + let mut r = request( + ZLIB | PAGE_DESTINATION | MEMORY_SOURCE, + pages.as_mut_ptr().cast(), + plain.len(), + packed.as_ptr().cast(), + 0, + packed.len(), + ); + r.page_offset = 50; + enqueue(queue, &r); + } + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + for pages in &destinations { + let mapped = xmem::XMemVirtualAlloc( + std::ptr::null_mut(), + 3 * PAGE, + 0x2000 | 0x2040_0000, // reserve, 64 KiB pages + 0, + 0x04, + ); + assert!(!mapped.is_null()); + assert_eq!( + xmem::XMemMapPhysicalPages(mapped, 3, pages.as_ptr()), + mapped + ); + // SAFETY: all three pages are mapped read-write. + let seen = unsafe { std::slice::from_raw_parts(mapped.cast::(), 3 * PAGE) }; + assert!(seen[..50].iter().all(|&b| b == 0)); + assert_eq!(seen[50..50 + plain.len()], plain); + assert_eq!( + xmem::XMemMapPhysicalPages(mapped, 3, std::ptr::null()), + mapped + ); + } + assert_eq!(xmem::XMemFreePhysicalPages(3, a.as_ptr()), 1); + assert_eq!(xmem::XMemFreePhysicalPages(1, b.as_ptr()), 1); + } } diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index bcd3222..15f8368 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -441,53 +441,130 @@ pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> B 1 } -/// Copies `data` into physical pages, from `offset` bytes into the first, -/// whether or not they are mapped anywhere (DirectStorage destinations). -/// False if a page is unknown or the host fails. -pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool { - use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile}; - let mut done = 0; - while done < data.len() { - let (page, within) = ((offset + done) / PAGE, (offset + done) % PAGE); - let Some(slice) = pages - .get(page) - .and_then(|p| physical().pages.get(p).cloned()) - else { - return false; - }; - let at = (slice.index * PAGE) as u64; - // SAFETY: one page of a section we own, mapped for the copy only. - let view = unsafe { +/// A view of our own on consecutive slices of one section, committed and +/// writable, unmapped when dropped. +struct View { + at: MEMORY_MAPPED_VIEW_ADDRESS, + len: usize, +} + +impl View { + /// Maps `n` slices from `slice` on. + fn map(slice: &Slice, n: usize) -> Option { + use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile}; + let (offset, len) = ((slice.index * PAGE) as u64, n * PAGE); + // SAFETY: slices of a section we own; the view is ours until dropped. + let at = unsafe { MapViewOfFile( slice.section.0, FILE_MAP_WRITE, - (at >> 32) as u32, - at as u32, - PAGE, + (offset >> 32) as u32, + offset as u32, + len, ) }; - if view.Value.is_null() { + if at.Value.is_null() { + return None; + } + let view = View { at, len }; + commit(at.Value as usize, len).then_some(view) + } + + fn bytes(&mut self) -> &mut [u8] { + // SAFETY: the view holds `len` committed read-write bytes, ours + // alone while `self` lives (other views of the slices only alias + // them, as the console's do). + unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) } + } +} + +impl Drop for View { + fn drop(&mut self) { + use windows_sys::Win32::System::Memory::UnmapViewOfFile; + // SAFETY: our view. + unsafe { UnmapViewOfFile(self.at) }; + } +} + +/// The pages behind bytes `[offset, offset + len)` of `pages` (64 KiB +/// each), as runs of consecutive slices of one section: each run's first +/// slice and its length in pages. One look at the page table, which the +/// title's own mapping calls share with every DirectStorage worker. `None` +/// if a page is unknown or `pages` ends early. +fn runs(pages: &[usize], offset: usize, len: usize) -> Option> { + let end = offset.checked_add(len)?; + let pages = pages.get(offset / PAGE..end.div_ceil(PAGE))?; + let physical = physical(); + let mut runs: Vec<(Slice, usize)> = Vec::new(); + for page in pages { + let slice = physical.pages.get(page)?; + match runs.last_mut() { + Some((first, n)) + if Arc::ptr_eq(&first.section, &slice.section) + && slice.index == first.index + *n => + { + *n += 1; + } + _ => runs.push((slice.clone(), 1)), + } + } + Some(runs) +} + +/// Copies `data` into physical pages, from `offset` bytes into the first, +/// whether or not they are mapped anywhere (DirectStorage destinations). +/// One view per run of consecutive pages, not one per page: each view +/// costs a map, a commit and an unmap (which flushes every core's TLB). +/// False if a page is unknown or the host fails. +pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool { + let Some(runs) = runs(pages, offset, data.len()) else { + return false; + }; + let (mut within, mut done) = (offset % PAGE, 0); + for (slice, n) in &runs { + let Some(mut view) = View::map(slice, *n) else { return false; - } - if !commit(view.Value as usize, PAGE) { - // SAFETY: our view. - unsafe { UnmapViewOfFile(view) }; - return false; - } - let n = (PAGE - within).min(data.len() - done); - // SAFETY: the view holds `PAGE` bytes; `within + n <= PAGE`. - unsafe { - view.Value - .cast::() - .add(within) - .copy_from_nonoverlapping(data[done..].as_ptr(), n); - UnmapViewOfFile(view); - } - done += n; + }; + let k = (n * PAGE - within).min(data.len() - done); + view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]); + (within, done) = (0, done + k); } true } +/// Bytes `[offset, offset + len)` of physical pages, writable in place +/// until dropped: DirectStorage decodes into it instead of a buffer it +/// would then copy. +pub(crate) struct PageWindow { + view: View, + within: usize, + len: usize, +} + +impl PageWindow { + pub(crate) fn bytes(&mut self) -> &mut [u8] { + let (within, len) = (self.within, self.len); + &mut self.view.bytes()[within..within + len] + } +} + +/// A window on bytes `[offset, offset + len)` of `pages` when they are +/// consecutive pages of one allocation (how titles usually hand them out); +/// `None` otherwise (pages of several allocations, out of order, or +/// unknown, or a host failure), which `write_physical` then handles or +/// reports. +pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option { + let runs = runs(pages, offset, len)?; + let [(slice, n)] = runs.as_slice() else { + return None; + }; + Some(PageWindow { + view: View::map(slice, *n)?, + within: offset % PAGE, + len, + }) +} + /// Maps `n` pages at `address`, in place of what is mapped there; null /// `pages` unmaps. Returns `address`, or null if a page or the host fails. pub extern "system" fn XMemMapPhysicalPages( @@ -953,4 +1030,90 @@ mod tests { assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); assert_eq!(XMemIsToolsMemAvailable(), 0); } + /// `n` pages of one new allocation. + fn allocate(n: usize) -> Vec { + let (mut pages, mut given) = (vec![0; n], n); + assert_eq!( + XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + assert_eq!(given, n); + pages + } + + /// The bytes of one page, through a view of our own. + fn page_bytes(page: usize) -> Vec { + let slice = physical().pages.get(&page).cloned().expect("known page"); + View::map(&slice, 1).expect("mapped").bytes().to_vec() + } + + #[test] + fn runs_group_consecutive_pages_of_one_allocation() { + let (a, b) = (allocate(3), allocate(1)); + let lengths = |pages: &[usize], offset, len| { + runs(pages, offset, len).map(|r| r.iter().map(|&(_, n)| n).collect::>()) + }; + assert_eq!(lengths(&a, 0, 3 * PAGE), Some(vec![3])); + // Only the pages the bytes reach. + assert_eq!(lengths(&a, PAGE + 5, 10), Some(vec![1])); + assert_eq!(lengths(&a, PAGE - 1, 2), Some(vec![2])); + assert_eq!(lengths(&a, 0, 0), Some(vec![])); + // Out of order, or across allocations: one run each. + assert_eq!( + lengths(&[a[0], a[2], a[1]], 0, 3 * PAGE), + Some(vec![1, 1, 1]) + ); + assert_eq!(lengths(&[a[1], a[2], b[0]], 0, 3 * PAGE), Some(vec![2, 1])); + // A slice that follows on in another section starts a run. + assert_eq!(lengths(&[b[0], a[1]], 0, 2 * PAGE), Some(vec![1, 1])); + // Too few pages for the bytes, or an unknown one. + assert_eq!(lengths(&a, 0, 3 * PAGE + 1), None); + assert_eq!(lengths(&[a[0], 0x10], 0, 2 * PAGE), None); + assert_eq!(lengths(&a, usize::MAX, 2), None); + assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); + } + + #[test] + fn writes_cross_runs_and_allocations() { + let (a, b) = (allocate(2), allocate(1)); + let pages = [a[0], a[1], b[0]]; + let data: Vec = (0..2 * PAGE + 64).map(|i| (i * 7 % 251) as u8).collect(); + let offset = PAGE - 32; + // Past the third page: the second run is too short. + assert!(!write_physical(&pages, offset, &data)); + assert!(write_physical(&pages, offset, &data[..2 * PAGE])); + let seen: Vec = pages.iter().flat_map(|&p| page_bytes(p)).collect(); + assert!(seen[..offset].iter().all(|&b| b == 0), "before the offset"); + assert_eq!(seen[offset..offset + 2 * PAGE], data[..2 * PAGE]); + assert!(seen[offset + 2 * PAGE..].iter().all(|&b| b == 0), "after"); + assert!( + !write_physical(&[a[0], 0x10], 0, &data[..PAGE + 1]), + "unknown page" + ); + assert_eq!(XMemFreePhysicalPages(2, a.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); + } + + #[test] + fn page_windows_cover_one_run_in_place() { + let (a, b) = (allocate(3), allocate(1)); + let mut window = page_window(&a, PAGE + 3, PAGE).expect("one run"); + assert_eq!(window.bytes().len(), PAGE); + window.bytes().fill(0x5a); + drop(window); + let (second, third) = (page_bytes(a[1]), page_bytes(a[2])); + assert!(second[..3].iter().all(|&b| b == 0)); + assert!(second[3..].iter().all(|&b| b == 0x5a)); + assert!(third[..3].iter().all(|&b| b == 0x5a)); + assert!(third[3..].iter().all(|&b| b == 0)); + // Several runs, or an unknown page: no window. + assert!(page_window(&[a[0], b[0]], 0, PAGE + 1).is_none()); + assert!(page_window(&[a[1], a[0]], 0, PAGE + 1).is_none()); + assert!(page_window(&[0x10], 0, 1).is_none()); + // One page of several is still one run. + assert!(page_window(&[a[0], b[0]], 0, PAGE).is_some()); + assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); + } }