diff --git a/crates/victory-gpu/src/alias.rs b/crates/victory-gpu/src/alias.rs index 078b5a93d..98ebd177f 100644 --- a/crates/victory-gpu/src/alias.rs +++ b/crates/victory-gpu/src/alias.rs @@ -24,7 +24,6 @@ use crate::host::host; use crate::watch::PAGE; use windows::Win32::Graphics::Direct3D12::ID3D12Resource; -#[cfg(any(test, feature = "diagnostics"))] use windows::Win32::Graphics::Direct3D12::*; #[cfg(target_arch = "x86_64")] @@ -360,7 +359,6 @@ fn supported() -> Option { /// CPU-visible backing for XMem physical pages. The placed buffer keeps a /// CPU mapping of the heap from which reserved resources can take tiles. -#[cfg(any(test, feature = "diagnostics"))] pub struct PhysicalHeap { backing: ID3D12Resource, // A placed buffer must keep its heap alive. @@ -369,7 +367,6 @@ pub struct PhysicalHeap { len: usize, } -#[cfg(any(test, feature = "diagnostics"))] impl PhysicalHeap { pub(crate) fn new(device: &ID3D12Device, len: usize) -> windows::core::Result { let desc = D3D12_HEAP_DESC { @@ -459,7 +456,6 @@ impl PhysicalHeap { } } -#[cfg(any(test, feature = "diagnostics"))] impl Drop for PhysicalHeap { fn drop(&mut self) { // SAFETY: unmapped once, while the placed buffer still owns the view. @@ -467,11 +463,61 @@ impl Drop for PhysicalHeap { } } -/// Allocates CPU-visible physical tiles for the Rosetta diagnostics trial. -#[cfg(feature = "diagnostics")] -pub fn physical_heap(len: usize) -> Option { +/// Whether the title's physical pages are GPU memory +/// (`VICTORY_PHYSICAL_TILES=1`, off by default; Rosetta and D3DMetal only): +/// each section of them is a CPU-visible heap, its title views remapped +/// onto it ([`PhysicalHeap::alias_view`]), and host copies of title buffers +/// on those pages read them in place (`crate::tiled`). +pub fn physical_tiles() -> bool { + #[cfg(test)] + if let Some(on) = TEST_PHYSICAL_TILES.with(std::cell::Cell::get) { + return on && supported().is_some(); + } static ENABLED: OnceLock = OnceLock::new(); - if !*ENABLED.get_or_init(|| crate::switch::on("VICTORY_PHYSICAL_TILES") && supported().is_some()) + *ENABLED.get_or_init(|| { + let on = crate::switch::on("VICTORY_PHYSICAL_TILES") && supported().is_some(); + if on { + tracing::info!("the title's physical pages are GPU memory, read in place (VICTORY_PHYSICAL_TILES=1)"); + } + on + }) +} + +#[cfg(test)] +thread_local! { + /// [`physical_tiles`] on this test's thread. + pub(crate) static TEST_PHYSICAL_TILES: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// One 64 KiB tile of a [`PhysicalHeap`]: a host copy's reserved buffer maps +/// it (`crate::tiled`), holding the heap while it does. +#[derive(Clone)] +pub struct Tile { + pub(crate) heap: ID3D12Heap, + pub(crate) index: u32, +} + +impl Tile { + /// Its 64 KiB tile in its heap. + pub fn index(&self) -> u32 { + self.index + } +} + +impl PhysicalHeap { + /// The tile at byte `offset` of the heap. + pub fn tile(&self, offset: usize) -> Option { + (offset.is_multiple_of(PAGE) && offset < self.len).then(|| Tile { + heap: self._heap.clone(), + index: (offset / PAGE) as u32, + }) + } +} + +/// CPU-visible GPU memory for a section of the title's physical pages, of +/// `len` bytes ([`physical_tiles`]); none when off or not made. +pub fn physical_heap(len: usize) -> Option { + if !physical_tiles() || len == 0 || !len.is_multiple_of(PAGE) { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 57489c474..a800d5e66 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3379,7 +3379,7 @@ impl Host { } /// The queue submissions go to now. - fn queue(&self) -> ID3D12CommandQueue { + pub(crate) fn queue(&self) -> ID3D12CommandQueue { self.queue.lock().unwrap_or_else(|e| e.into_inner()).clone() } @@ -8994,3 +8994,130 @@ mod waiting_on_tests { } } } + +/// `VICTORY_PHYSICAL_TILES=1`: a title buffer on physical pages that are GPU +/// memory is read in place (`crate::tiled`). +#[cfg(test)] +mod tiled_tests { + use crate::alias::{PhysicalHeap, Tile}; + use crate::backend::{HostGpu, HostMemory}; + use crate::watch::PAGE; + use std::sync::Mutex; + + /// What the test's "runtime" maps: page address and its tile. + static SHOWN: Mutex> = Mutex::new(Vec::new()); + + fn lookup(at: usize, len: usize, out: &mut Vec>) -> bool { + let shown = SHOWN.lock().unwrap(); + out.clear(); + out.extend((at / PAGE..(at + len).div_ceil(PAGE)).map(|page| { + shown.iter().find(|(a, _)| *a == page * PAGE).map(|(_, t)| t.clone()) + })); + true + } + + /// Title memory of four pages showing heap tiles 2, 0, 3, 1 in turn. + #[test] + fn a_buffer_on_gpu_physical_pages_is_read_and_written_in_place() { + let Some(host) = super::host() else { + return; // no host GPU here + }; + let _mode = super::flight::ModeGuard::new(false, false); + crate::alias::TEST_PHYSICAL_TILES.with(|c| c.set(Some(true))); + if !crate::alias::physical_tiles() { + crate::alias::TEST_PHYSICAL_TILES.with(|c| c.set(None)); + return; // not Rosetta and D3DMetal + } + crate::tiled::on_physical_tiles(lookup); + let heap = PhysicalHeap::new(&host.device, 4 * PAGE).expect("a CPU-visible heap"); + // SAFETY: a fresh reservation of four pages, never freed (its + // addresses stay the test's). + let at = unsafe { + windows_sys::Win32::System::Memory::VirtualAlloc( + std::ptr::null(), + 4 * PAGE, + windows_sys::Win32::System::Memory::MEM_RESERVE | windows_sys::Win32::System::Memory::MEM_COMMIT, + windows_sys::Win32::System::Memory::PAGE_READWRITE, + ) + } as usize; + assert_ne!(at, 0); + let order = [2usize, 0, 3, 1]; + for (k, &tile) in order.iter().enumerate() { + // SAFETY: our reservation's page and the heap's tile. + assert!(unsafe { heap.alias_view(at + k * PAGE, tile * PAGE, PAGE) }, "remap page {k}"); + SHOWN.lock().unwrap().push((at + k * PAGE, heap.tile(tile * PAGE).unwrap())); + } + // The title writes each page through its own address. + for k in 0..4 { + // SAFETY: mapped read-write. + unsafe { ((at + k * PAGE) as *mut u32).write_volatile(0x1000 + k as u32) }; + } + let resource = 0x7e57_0000_usize; + crate::shadow::register(resource, at as u64, (4 * PAGE) as u64); + let copy = crate::shadow::find(at as u64, (4 * PAGE) as u64).expect("a copy"); + assert!(copy.is_aliased(), "the copy reads the pages in place"); + + // The GPU reads what the title wrote, with no refresh. + let (out, out_ptr) = host.mapped_buffer(64, true).expect("readback"); + let read = |page: usize| { + // SAFETY: mapped readback memory, no copy into it in flight. + unsafe { out_ptr.cast::().write_volatile(0xDEAD_DEAD) }; + let list = host.new_list().unwrap(); + // SAFETY: open list, live buffers. + unsafe { list.list.CopyBufferRegion(&out, 0, ©.buffer, copy.offset((at + page * PAGE) as u64), 4) }; + list.keep(&out); + list.close(); + host.execute(&[&list]); + // SAFETY: the copy has run. + unsafe { out_ptr.cast::().read_volatile() } + }; + for k in 0..4 { + assert_eq!(read(k), 0x1000 + k as u32, "page {k} as the GPU reads it"); + } + // What the GPU writes the title reads at once. + let (src, src_ptr) = host.upload_buffer(64).expect("upload"); + // SAFETY: mapped upload memory. + unsafe { src_ptr.cast::().write_volatile(0xBEEF) }; + let list = host.new_list().unwrap(); + // SAFETY: open list, live buffers. + unsafe { list.list.CopyBufferRegion(©.buffer, copy.offset((at + 2 * PAGE + 8) as u64), &src, 0, 4) }; + list.keep(&src); + list.close(); + host.execute(&[&list]); + // SAFETY: mapped read-write. + assert_eq!(unsafe { ((at + 2 * PAGE + 8) as *const u32).read_volatile() }, 0xBEEF); + + // The title maps tile 3 at its second page as well: the copy follows. + // SAFETY: as above. + assert!(unsafe { heap.alias_view(at + PAGE, 3 * PAGE, PAGE) }); + crate::tiled::physical_retiled(at + PAGE, PAGE, &[heap.tile(3 * PAGE)]); + assert_eq!(read(1), 0x1002, "the second page shows tile 3 now"); + // Unmapped, it reads zeros (D3DMetal ignores null tile mappings: a + // tile of zeros stands in), and the other pages are as they were. + crate::tiled::physical_retiled(at + PAGE, PAGE, &[None]); + assert_eq!(read(1), 0, "an unmapped page reads zeros"); + assert_eq!([read(0), read(3)], [0x1000, 0x1003]); + + crate::shadow::unregister(resource, at as u64); + SHOWN.lock().unwrap().clear(); + crate::alias::TEST_PHYSICAL_TILES.with(|c| c.set(None)); + } + + /// A buffer with a page that is not GPU memory is copied as before. + #[test] + fn a_buffer_off_gpu_pages_is_copied() { + if super::host().is_none() { + return; + } + crate::alias::TEST_PHYSICAL_TILES.with(|c| c.set(Some(true))); + crate::tiled::on_physical_tiles(lookup); + let p = crate::watch::tests::pool(2); + crate::shadow::register(p, p as u64, (2 * PAGE) as u64); + let copy = crate::shadow::find(p as u64, (2 * PAGE) as u64).expect("a copy"); + assert!(!copy.is_aliased()); + crate::shadow::unregister(p, p as u64); + drop(copy); + crate::watch::tests::free(p); + crate::alias::TEST_PHYSICAL_TILES.with(|c| c.set(None)); + } +} diff --git a/crates/victory-gpu/src/host/flight.rs b/crates/victory-gpu/src/host/flight.rs index 6d166b3e1..9b84c6088 100644 --- a/crates/victory-gpu/src/host/flight.rs +++ b/crates/victory-gpu/src/host/flight.rs @@ -1966,7 +1966,9 @@ void main(uint3 id : SV_DispatchThreadID) { TEST_PAUSE_LANDING.store(true, Ordering::Release); host.execute_flight1(vec![quiet_copy(host, 0x1111_0001, &out1)], vec![]); assert!(host.attach_signal(f1, 1, false)); - assert_eq!(flights_in_air(host), 1); + // Another test's synchronous submission may land it at once: then + // this attempt does not take the path (`until_taken`). + let first_in_air = flights_in_air(host) == 1; // SAFETY: valid title buffer. unsafe { title_ptr.cast::().write_volatile(0x2222_0002) }; @@ -1981,7 +1983,10 @@ void main(uint3 id : SV_DispatchThreadID) { assert!(host.attach_signal(f2, 1, false)); let after = ahead_counts(); - let taken = after[0] - before[0] == 1 && after[1] - before[1] == 1 && flights_in_air(host) == 2; + let taken = first_in_air + && after[0] - before[0] == 1 + && after[1] - before[1] == 1 + && flights_in_air(host) == 2; TEST_PAUSE_LANDING.store(false, Ordering::Release); let start = Instant::now(); @@ -2342,11 +2347,18 @@ void main(uint3 id : SV_DispatchThreadID) { [Probe::Behind, Probe::RangesOnly, Probe::CleanKnown, Probe::Ceiling] .map(|p| after[slot(p)] - before[slot(p)]) }; - let [behind, ranges, clean, ceiling] = round(b, &sb); - assert_eq!((behind, ranges), (1, 1), "compared behind a flight with declared writes only"); + // Another test's flight landing between the two (the last landed is + // the process's) leaves a round uncompared: it runs again. + let compared = |refreshed: u64, shadow: &Arc| { + (0..20) + .map(|_| round(refreshed, shadow)) + .find(|counts| counts[0] == 1) + .expect("another test's flight landed between the two every time") + }; + let [_, ranges, clean, ceiling] = compared(b, &sb); + assert_eq!(ranges, 1, "compared behind a flight with declared writes only"); assert_eq!((clean, ceiling), (1, 1), "another copy: could go ahead"); - let [behind, _, clean, ceiling] = round(a, &sa); - assert_eq!(behind, 1); + let [_, _, clean, ceiling] = compared(a, &sa); assert_eq!((clean, ceiling), (0, 0), "the range it wrote: could not"); drop((sa, sb)); // SAFETY: the flights have landed. diff --git a/crates/victory-gpu/src/inplace_probe.rs b/crates/victory-gpu/src/inplace_probe.rs index 139c86c0f..1352d1bf4 100644 --- a/crates/victory-gpu/src/inplace_probe.rs +++ b/crates/victory-gpu/src/inplace_probe.rs @@ -872,6 +872,10 @@ fn inplace_probe_6_remap_cpu_visible_tiles() { D3D12_TILE_MAPPING_FLAG_NONE, ); } + // shortcut: under D3DMetal this passes without the null mapping taking + // effect: the tile keeps its heap tile, and the copy out of it reads + // what the fetch's fresh buffer held anyway, zeros (`crate::tiled` maps + // unmapped pages to a tile of zeros instead). let bytes = rig.fetch(&reserved, 0, K64).unwrap(); assert!(bytes.iter().all(|&byte| byte == 0), "null tile reads as zeros"); // SAFETY: null-mapping the GPU view leaves the CPU heap tile alive. diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 947f6f8bc..d02823f31 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -98,6 +98,8 @@ mod sampler; pub mod shader_cache; #[cfg(windows)] mod shadow; +#[cfg(windows)] +mod tiled; pub mod signature; mod switch; #[cfg(windows)] @@ -128,8 +130,10 @@ mod footprint_probe; pub use copystat::CountingAlloc; #[cfg(windows)] pub use alias::{Unaliased, alias_region, enabled as alias_buffers, note_unaliased, unalias_region}; -#[cfg(all(windows, feature = "diagnostics"))] -pub use alias::{PhysicalHeap, physical_heap}; +#[cfg(windows)] +pub use alias::{PhysicalHeap, Tile, physical_heap, physical_tiles}; +#[cfg(windows)] +pub use tiled::{on_physical_tiles, physical_retiled}; #[cfg(windows)] pub use host::{MeshSupport, host_mesh_support, on_failure}; #[cfg(windows)] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index fa21cfaee..33f82cbb3 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2329,16 +2329,25 @@ fn find_uncached(address: u64, end: u64) -> Option> { if let Some(shadow) = find_aliased(address, end) { return Some(shadow); } - { + let found = { let map = buffers_read(); let Some(key) = enclosing(&map, MAX_SPAN.load(Ordering::Relaxed), address, end) else { drop(map); return loose(address, end); }; - if let Some(shadow) = map.get(&key).and_then(|entry| entry.shadow.clone()) { - return Some(shadow); + match map.get(&key) { + Some(entry) => match &entry.shadow { + Some(shadow) => return Some(shadow.clone()), + None => Some((key, entry.end - key.0)), + }, + None => None, } - } + }; + // `VICTORY_PHYSICAL_TILES=1`: a buffer on the title's physical pages + // reads them in place. Asked without the buffers' lock: the runtime's + // lookup takes its own, which it holds while it tells the trackers of + // a mapping (and they may read the buffers). + let mut tiled = found.and_then(|(key, len)| Some((key, crate::tiled::make(key.0, len)?))); let mut map = buffers(); let key = enclosing(&map, MAX_SPAN.load(Ordering::Relaxed), address, end); let Some(key) = key else { @@ -2346,6 +2355,13 @@ fn find_uncached(address: u64, end: u64) -> Option> { return loose(address, end); }; let entry = map.get_mut(&key)?; + if entry.shadow.is_none() + && let Some((_, copy)) = tiled.take().filter(|(k, _)| *k == key) + { + entry.shadow = Some(copy); + released().remade(key.0); + changed(); + } if entry.shadow.is_none() { let len = entry.end - key.0; // Rounded up so that views ending in the buffer's last 256 bytes fit. diff --git a/crates/victory-gpu/src/tiled.rs b/crates/victory-gpu/src/tiled.rs new file mode 100644 index 000000000..845b1c1cb --- /dev/null +++ b/crates/victory-gpu/src/tiled.rs @@ -0,0 +1,238 @@ +//! Host copies that read the title's physical pages in place +//! (`VICTORY_PHYSICAL_TILES=1`, off by default). +//! +//! The title maps its physical pages (`XMemAllocatePhysicalPages`, +//! `XMemMapPhysicalPages`) into its buffers page by page. With the switch, +//! each section of those pages is a CPU-visible GPU heap +//! ([`crate::alias::PhysicalHeap`]) and the title's views of it are remapped +//! onto the heap, so the title's CPU writes land in GPU memory. A title +//! buffer whose pages all lie on such heaps then needs no copy: its host +//! copy is a reserved buffer whose 64 KiB tiles are those pages +//! (`UpdateTileMappings`), in the title's order, wherever they lie in the +//! heaps. The copy is zero-copy ([`Shadow::new_aliased`]): nothing is +//! refreshed into it, nothing copied back, and what shaders write the +//! title reads at once, as on the console. +//! +//! When the title maps other pages there, or unmaps them, the runtime +//! passes the new tiles ([`physical_retiled`]) and the copy's tiles follow +//! at once, on the host queue: work the GPU runs from then on reads the new +//! pages, as the console's GPU reads its page tables when it runs (a title +//! does not remap pages work in flight reads). +//! +//! The run on D3DMetal is the inplace probe's `remap_cpu_visible_tiles`: +//! reserved buffers over CPU-visible heap tiles in any order, remapped, +//! both ways coherent. + +use std::sync::{Arc, Mutex, OnceLock, Weak}; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::alias::Tile; +use crate::shadow::Shadow; +use crate::watch::PAGE; + +/// The runtime's lookup of the tiles showing title memory `[at, at + len)` +/// (page aligned), one per 64 KiB page in order, `None` where a page is not +/// on a GPU heap; `false` if it cannot tell. +pub type TileLookup = fn(usize, usize, &mut Vec>) -> bool; + +static LOOKUP: OnceLock = OnceLock::new(); + +/// Sets the runtime's [`TileLookup`]. +pub fn on_physical_tiles(lookup: TileLookup) { + let _ = LOOKUP.set(lookup); +} + +/// A tiled copy: its first title page (page number), its reserved buffer, +/// and the tiles its pages show now (held, so their heaps outlive the +/// mapping). +struct Tiled { + first: usize, + copy: Weak, + buffer: ID3D12Resource, + tiles: Vec>, +} + +static TILED: Mutex> = Mutex::new(Vec::new()); + +fn tiled() -> std::sync::MutexGuard<'static, Vec> { + TILED.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// A zero-copy host copy of title buffer `[start, start + len)` over its +/// physical pages, if every page of it is on a GPU heap; `None` otherwise +/// (it is copied as before). Call without the buffers' lock: the lookup +/// takes the runtime's. +pub(crate) fn make(start: u64, len: u64) -> Option> { + if len == 0 || !crate::alias::physical_tiles() { + return None; + } + let lookup = LOOKUP.get()?; + let first = start as usize / PAGE; + let pages = (start.checked_add(len)? as usize).div_ceil(PAGE) - first; + let mut tiles = Vec::with_capacity(pages); + if !lookup(first * PAGE, pages * PAGE, &mut tiles) + || tiles.len() != pages + || tiles.iter().any(Option::is_none) + { + return None; + } + let host = crate::host::host()?; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: (pages * PAGE) 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, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain creation with an output slot on this stack. + if let Err(error) = unsafe { + host.device + .CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + } { + tracing::warn!(%error, len, "no reserved buffer over physical pages; copying them"); + return None; + } + let buffer = buffer?; + map(&host.queue(), &buffer, 0, &tiles); + crate::host::name(&buffer, || format!("title buffer {start:#x}+{len:#x} on physical pages")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let base = start - (first * PAGE) as u64; + let copy = Shadow::new_aliased(buffer.clone(), start as *mut u8, gpu + base, start, len, base); + { + let mut list = tiled(); + list.retain(|t| t.copy.strong_count() > 0); + list.push(Tiled { + first, + copy: Arc::downgrade(©), + buffer, + tiles, + }); + } + static FIRST: std::sync::Once = std::sync::Once::new(); + FIRST.call_once(|| tracing::info!(start = format_args!("{start:#x}"), len, "first title buffer read on its physical pages in place")); + Some(copy) +} + +/// The title's memory `[at, at + len)` now shows `tiles` (one per page; `None` +/// unmapped, or not on a GPU heap): copies over it map them at once. +pub fn physical_retiled(at: usize, len: usize, tiles: &[Option]) { + let mut list = tiled(); + list.retain(|t| t.copy.strong_count() > 0); + if list.is_empty() { + return; + } + let Some(host) = crate::host::host() else { + return; + }; + let (from, to) = (at / PAGE, at.saturating_add(len).div_ceil(PAGE)); + let queue = host.queue(); + for t in list.iter_mut() { + let (a, b) = (from.max(t.first), to.min(t.first + t.tiles.len())); + if a >= b { + continue; + } + for page in a..b { + t.tiles[page - t.first] = tiles.get(page - from).cloned().flatten(); + } + if t.tiles[a - t.first..b - t.first].iter().any(Option::is_none) { + static WARNED: std::sync::Once = std::sync::Once::new(); + WARNED.call_once(|| { + tracing::warn!( + at = format_args!("{at:#x}"), + len, + "a title buffer read in place lost pages of a GPU heap: they read zeros" + ); + }); + } + map(&queue, &t.buffer, (a - t.first) as u32, &t.tiles[a - t.first..b - t.first]); + } +} + +/// A tile of zeros that unmapped pages show (one heap, made once). +fn zero_tile() -> Option { + static ZERO: OnceLock> = OnceLock::new(); + ZERO.get_or_init(|| { + let heap = crate::alias::PhysicalHeap::new(&crate::host::host()?.device, PAGE).ok()?; + // SAFETY: the heap's own CPU view of one page. + unsafe { (heap.cpu_address() as *mut u8).write_bytes(0, PAGE) }; + Some(heap) + }) + .as_ref()? + .tile(0) +} + +/// Maps `buffer`'s tiles from `first` on to `tiles` (zeros where `None`), in +/// runs of one heap's consecutive tiles. +fn map(queue: &ID3D12CommandQueue, buffer: &ID3D12Resource, first: u32, tiles: &[Option]) { + let mut k = 0; + while k < tiles.len() { + let mut n = 1; + match &tiles[k] { + Some(tile) => { + while tiles.get(k + n).is_some_and(|next| { + next.as_ref().is_some_and(|next| { + next.heap == tile.heap && next.index == tile.index + n as u32 + }) + }) { + n += 1; + } + let start = D3D12_TILED_RESOURCE_COORDINATE { X: first + k as u32, ..Default::default() }; + let size = D3D12_TILE_REGION_SIZE { NumTiles: n as u32, ..Default::default() }; + let flags = D3D12_TILE_RANGE_FLAG_NONE; + let count = n as u32; + // SAFETY: one region of our reserved buffer onto a live heap's tiles. + unsafe { + queue.UpdateTileMappings( + buffer, + 1, + Some(&start), + Some(&size), + &tile.heap, + 1, + Some(&flags), + Some(&tile.index), + Some(&count), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + } + } + None => { + // D3DMetal leaves a tile mapped as it was when asked to map + // it null (`a_buffer_on_gpu_physical_pages_is_read_and_written_in_place`): + // each goes to a tile of zeros of our own instead, as D3D12 + // reads a null tile. Shaders writing there (a title bug, as + // the memory is unmapped) can leave other bytes in it. + let Some(zero) = zero_tile() else { + k += 1; + continue; + }; + let start = D3D12_TILED_RESOURCE_COORDINATE { X: first + k as u32, ..Default::default() }; + let size = D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }; + let flags = D3D12_TILE_RANGE_FLAG_NONE; + // SAFETY: one tile of our reserved buffer onto the live zero heap. + unsafe { + queue.UpdateTileMappings( + buffer, + 1, + Some(&start), + Some(&size), + &zero.heap, + 1, + Some(&flags), + Some(&zero.index), + Some(&1), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + } + } + } + k += n; + } +} diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index 506c84b7f..d3e9931dd 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -25,6 +25,8 @@ extern "system" fn create_device( victory_gpu::on_failure(host_gpu_failed); #[cfg(windows)] victory_gpu::on_physical_runs(super::xmem::physical_runs); + #[cfg(windows)] + victory_gpu::on_physical_tiles(super::xmem::physical_tiles); device::create(adapter, parameters, iid, out) } diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index df1fa3357..8c75198f4 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -444,9 +444,10 @@ unsafe fn map_own_view(section: HANDLE, offset: u64, size: usize) -> MEMORY_MAPP struct Section { handle: HANDLE, size: usize, - /// Optional shared CPU/GPU backing. The file still supplies Wine's - /// placeholder-view metadata. - #[cfg(feature = "diagnostics")] + /// The pages as GPU memory (`VICTORY_PHYSICAL_TILES=1`): the title's + /// views are remapped onto it, and copies of title buffers on them read + /// it in place (`victory_gpu::physical_retiled`). The file still + /// supplies Wine's placeholder-view metadata. shared: Option, /// Our own view of the whole section, mapped the first time a /// DirectStorage request writes its pages and kept while the section @@ -510,7 +511,6 @@ impl Section { Section { handle, size, - #[cfg(feature = "diagnostics")] shared: victory_gpu::physical_heap(size), whole: OnceLock::new(), committed, @@ -520,7 +520,6 @@ impl Section { /// The address of our view of the whole section, mapped the first time; /// `None` if the host would not map it. fn whole(&self) -> Option { - #[cfg(feature = "diagnostics")] if let Some(shared) = &self.shared { return Some(shared.cpu_address()); } @@ -755,6 +754,20 @@ pub(crate) fn physical_runs(at: usize, len: usize) -> Option<(usize, usize, usiz (pages > 0).then_some((pages, runs, sections.len())) } +/// The tiles showing title memory `[at, at + len)` (page aligned), one a +/// page, for the GPU side's copies reading them in place +/// (`victory_gpu::on_physical_tiles`): `None` where a page shows no section +/// of GPU memory. +pub(crate) fn physical_tiles(at: usize, len: usize, out: &mut Vec>) -> bool { + let physical = physical(); + out.clear(); + out.extend((at / PAGE..at.saturating_add(len).div_ceil(PAGE)).map(|page| { + let slice = slice_at(&physical, page * PAGE)?; + slice.section.shared.as_ref()?.tile(slice.index * PAGE) + })); + true +} + /// The addresses of title views showing `pages` (page numbers): writes into /// them through our own views must be reported there. fn shown_at(pages: &[usize]) -> Vec { @@ -1443,7 +1456,6 @@ fn finish_map( #[cfg(test)] tests::MAPS.with(|m| m.set(m.get() + 1)); let mapped = slice.section.commit_shown(slice.index, base, len); - #[cfg(feature = "diagnostics")] let mapped = mapped && slice.section.shared.as_ref().is_none_or(|shared| { // SAFETY: this live view is ours. The slice will hold the @@ -1476,6 +1488,13 @@ fn finish_map( // Pages shown elsewhere already: guarded here too if they are there. victory_gpu::title_memory_aliased(at, &others); } + // Copies of title buffers reading these pages in place map them now. + if victory_gpu::physical_tiles() { + let tiles: Vec> = (0..len / PAGE) + .map(|k| slice.section.shared.as_ref()?.tile((slice.index + k) * PAGE)) + .collect(); + victory_gpu::physical_retiled(base, len, &tiles); + } physical.views.insert(base, (len, slice)); true } @@ -1616,6 +1635,9 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { continue; }; shown_mut().forget(at, size, &slice); + if victory_gpu::physical_tiles() { + victory_gpu::physical_retiled(at, size, &vec![None; size / PAGE]); + } let going = victory_gpu::title_memory_unmapping(at, size); // SAFETY: a view we mapped; it becomes a placeholder again. let gone = unsafe { @@ -1945,6 +1967,36 @@ mod tests { } } + /// `VICTORY_PHYSICAL_TILES=1`: mapped physical pages are GPU memory, and + /// the lookup names their tiles in the title's order; unmapped, none. + #[test] + fn physical_tiles_name_the_gpu_tiles_a_view_shows() { + let pages = allocate(2); + if page_table().pages[&pages[0]].section.shared.is_none() { + assert!(!victory_gpu::physical_tiles(), "the switch is on, the pages are not GPU memory"); + return; // VICTORY_PHYSICAL_TILES off, or not Rosetta and D3DMetal + } + let at = XMemVirtualAlloc(std::ptr::null_mut(), 2 * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!at.is_null()); + let order = [pages[1], pages[0]]; + assert_eq!(XMemMapPhysicalPages(at, 2, order.as_ptr()), at); + let mut tiles = Vec::new(); + assert!(physical_tiles(at as usize, 2 * PAGE, &mut tiles)); + let index = |k: usize| tiles[k].as_ref().map(victory_gpu::Tile::index); + let first = page_table().pages[&pages[0]].index as u32; + assert_eq!([index(0), index(1)], [Some(first + 1), Some(first)], "in the title's order"); + // The title's writes land in the GPU heap: its own view shows them. + // SAFETY: mapped read-write. + unsafe { at.cast::().write(0x5eed) }; + let whole = page_table().pages[&pages[1]].section.whole().unwrap(); + // SAFETY: the section's whole view, the heap's CPU address. + assert_eq!(unsafe { ((whole + (first as usize + 1) * PAGE) as *const u32).read() }, 0x5eed); + assert_eq!(XMemMapPhysicalPages(at, 2, std::ptr::null()), at); + assert!(physical_tiles(at as usize, 2 * PAGE, &mut tiles)); + assert!(tiles.iter().all(Option::is_none), "unmapped"); + assert_eq!(XMemFreePhysicalPages(2, pages.as_ptr()), 1); + } + #[test] fn physical_runs_count_pages_one_after_another_in_a_section() { let pages = allocate(4); @@ -2048,8 +2100,7 @@ mod tests { let mut n = 3; assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); assert_eq!(n, 3); - #[cfg(feature = "diagnostics")] - if std::env::var("VICTORY_PHYSICAL_TILES").as_deref() == Ok("1") { + if victory_gpu::physical_tiles() { let table = page_table(); assert!( table.pages[&pages[0]].section.shared.is_some(), @@ -2809,7 +2860,9 @@ mod tests { // the per-slice `View::map` fallback path as well. let fallback = unsafe { map_own_view(slice.section.handle, PAGE as u64, PAGE) }; assert!(!fallback.Value.is_null()); - if on_wine() { + // With `VICTORY_PHYSICAL_TILES=1` the whole view is the section's + // GPU heap, not a view of ours: no floor. + if on_wine() && slice.section.shared.is_none() { assert!( whole >= OWN_VIEW_FLOOR, "whole view {whole:#x} below {OWN_VIEW_FLOOR:#x}" diff --git a/docs/macos.md b/docs/macos.md index ab9cf72a8..5a45140f5 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -335,6 +335,7 @@ None of these changes the default, except `VICTORY_OUTPUT`, which sets the title | `VICTORY_ASYNC_SUBMIT=1`, `VICTORY_FLIGHT1=0\|1` | Opt-in. The title's `ExecuteCommandLists`, queue `Signal` and `Wait` only queue their work, and the `victory-submit` thread prepares and submits it to the host GPU, joining up to 64 ready lists into one submission; the title's fences move once the work ran, as without it. One host submission is in flight at a time and the next is prepared only once it has landed (host copies of title memory are read by the GPU in place), so what overlaps is the title's own CPU time with host work, not preparing with the GPU. PresentX and our own read-backs wait for the queued work; a `CopyPageMappingsBatchX` behind work its queue holds (or while a host submission is in flight) is queued in that queue's order instead, as on the console, and the title's thread goes on. `VICTORY_ASYNC_SUBMIT=1` turns `VICTORY_FLIGHT1` on unless it is `0`; `VICTORY_FLIGHT1=1` alone keeps the work on the title's thread but returns before the GPU is done. The frame report's "threads held by host GPU work" line then counts the title's calls queuing, and PresentX (`presents`) and our read-backs (`our syncs`) waiting for the worker; a line "host submissions in flight per frame" gives the worker's time (waiting for the last submission to land, preparing, launching) and the host GPU's idle time before each submission, with nothing to run or while it was prepared; a line "queued host work drained per frame" counts what still drains it (presents, page mappings done at once or queued, and our own host work by the line that called it). | | `VICTORY_PREP_AHEAD=1` | Opt-in, with `VICTORY_ASYNC_SUBMIT=1` (or `VICTORY_FLIGHT1=1`). The next host submission is prepared while the one before is still on the GPU, and launched behind it (two in flight), when the one in flight is *quiet at landing*: nothing of it goes back to title memory (no ranges shaders write, no write marks, no read-backs, no work after it or bottom-of-pipe writes) and it had no uploads. Its host copies are refreshed in place meanwhile: the title does not change memory submitted work reads until that work's fence moves, which is when it lands, so the GPU reads the same bytes. The one in flight lands first, as without the switch, for what needs it: the frame's eviction pass, a view remake, the shared barrier lists, a heap fill, title copies (done on the CPU while preparing, by the GPU on the console), and, before the new one launches, its write marks. A frame-report line counts the submissions prepared and launched behind one in flight, and why the others landed it first; the flight line's "host GPU idle … preparing" shows what is left. | | `VICTORY_VIEW_PROBE=1` | Off by default. The "heap slots made again" line also counts the views a sync creates whose descriptor (view and generation) an earlier sync already created: the most a cache of views across syncs could save. | +| `VICTORY_PHYSICAL_TILES=1` | Off by default; Rosetta and D3DMetal only. The title's physical pages (`XMemAllocatePhysicalPages`) are GPU memory: each section of them is a CPU-visible GPU heap, and its title views are remapped onto it. A title buffer whose pages all lie on such heaps is then read in place: its host copy is a reserved buffer whose 64 KiB tiles are those pages (`UpdateTileMappings`), with nothing refreshed into it or copied back, and what shaders write the title reads at once. When the title maps other pages there, the tiles follow. Unmapped pages show a tile of zeros, because D3DMetal ignores null tile mappings. A buffer whose pages are not all on GPU heaps when it is first used is copied as before. | | `VICTORY_SAME_COPIES=probe` / `skip` | Off by default. Each title copy between buffers (run on the CPU while preparing a submission) is first compared: its source's bytes against its destination's and against every host copy of the destination. With `probe` the copies whose bytes are all in place already are only counted; with `skip` they are left out, so their destination's host copies are not made due for a refresh again. Comparing costs about 4-5 times what copying warm memory does (benchmark `host::batch::same_copy_costs`: 8 µs against 2 µs for 64 KiB under Wine), so `skip` pays only where most copies are in place. The frame report's line "host preparing copies per frame" splits the preparing copies into title copies, fills of upload memory and refreshes of host copies, and shows how many title copies were compared and already in place. | | `VICTORY_PREP_AHEAD=ranges` | Opt-in, as `VICTORY_PREP_AHEAD=1`, and also behind a flight that is not quiet when what its landing writes is known before it runs: ranges its shaders declare (whole 64 KiB pages), write marks (bounded by every host copy owning mark bits) and bottom-of-pipe writes outside host copies. The preparation lands it first only where it would refresh those bytes, declare shader writes in a copy it writes, fill from them, or run host work. A flight with work after it, read-backs, table textures or uploads lands first, as with `=1`. Shortcut: a texture over memory the flight's shaders write can be brought up one submission late. The prep-ahead line counts the preparations behind such a flight and why they landed it ("what it writes", "CPU reads"). | | `VICTORY_READ_STATS=1` | Logs the requests and bytes read from each file, every 30 seconds, for the 30 most read. It shows which files a slow share serves most, so you can copy those to fast local storage. |