From 9075710d14a294e645a9a2d2b6f1b2e7c1f82154 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 23:33:12 -0600 Subject: [PATCH] Renderer port 1: the title's 32-bit graphics heap used in place (VICTORY_PORT_CONSTANTS=1, off by default) The title's routine at image+0x1e86440 reserves 185 MB of graphics memory below 4 GiB, splits it into five pieces, takes all their physical pages in one XMemAllocatePhysicalPages and maps them in order: one stretch of one section. Its 174 MB buffer at 0x34e10000 (the ring of constants, and what the skinning passes write through one view of all of it) had a host copy in the card's memory, ~17 MB a frame sent up in ~600 pieces, shader writes fetched back and compared, and ~6,000 constant fills a frame. With the switch the stretch is mapped once more at an address of ours and opened as a host heap there (OpenExistingHeapFromAddress1); title buffers and windows in it are buffers placed in that heap, the existing in-place form of a host copy: nothing tracked, sent up, fetched back or compared. The title's own views stay free to change; when it maps other pages there the region is forgotten. A line on the frame-rate report counts the CPU fills and buffer copies of ours that still read or write it. Replay (play-1125-0127, heap in the PC's memory): the title's own work +~3 ms on the card; the 30 ms added there are our compare passes, which do not run over memory in place. Ported from Belobug/VIctory-Belobug-AMD 86dc109 (author: local); conflict with heap_marks in host.rs kept both. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 3 + crates/victory-gpu/src/inplace.rs | 76 +++++- crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/port.rs | 401 ++++++++++++++++++++++++++++++ crates/victory-gpu/src/shadow.rs | 8 +- 5 files changed, 484 insertions(+), 6 deletions(-) create mode 100644 crates/victory-gpu/src/port.rs diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 90590dc..2427053 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3820,6 +3820,7 @@ fn late_line(frames: f64) { ); } card_steps::log(frames); + crate::port::log(frames); crate::picked::log(frames); #[cfg(feature = "diagnostics")] log_blame(frames); @@ -7730,6 +7731,7 @@ impl HostList { if crate::heap_marks::on() && crate::descriptor::in_shader_heap(dst, len) { crate::heap_marks::prep_wrote(); } + crate::port::copied(dst, src, len); copy_mapped(dst as *mut u8, src as *const u8, len, true); // With the submission's one asking: the journal learns it. crate::watch::wrote(dst, len); @@ -7745,6 +7747,7 @@ impl HostList { { copies += 1; } + crate::port::filled(src, len); if wide_fills() { batch.fills.push((dst, src, len)); bytes += len as u64; diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 28f570e..4bb00c4 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -167,6 +167,14 @@ pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option { } } +/// Something placed elsewhere (`crate::port`) in the same form: counted as +/// [`place_for`] counts, so that [`gone`] takes it off again. +pub(crate) fn counted(window: bool, bytes: u64) { + let at = if window { 0 } else { 2 }; + STATS[at].fetch_add(1, Ordering::Relaxed); + STATS[at + 1].fetch_add(bytes, Ordering::Relaxed); +} + /// What [`place_for`] gave is gone. pub(crate) fn gone(window: bool, bytes: u64) { let at = if window { 0 } else { 2 }; @@ -181,6 +189,8 @@ pub(crate) fn gone(window: bool, bytes: u64) { /// the runtime to call before the title's own `VirtualFree` once it takes /// that call over. pub fn title_memory_freeing(at: usize, len: usize) { + // Renderer port 1's regions there: no longer what the title shows. + crate::port::forget(at, len); if STATS[0].load(Ordering::Relaxed) + STATS[2].load(Ordering::Relaxed) == 0 { return; } @@ -525,6 +535,40 @@ pub(crate) fn cover(at: usize, len: usize) -> Cover { cover_in(&views().views, at, len) } +/// The whole stretch of views around `[at, at + len)` that follow one +/// another in memory and in one section alike, if the range is one run of a +/// section ([`Cover::Run`]): its first address, its bytes, the section and +/// the offset of its first byte in it. +pub(crate) fn stretch(at: usize, len: usize) -> Option<(usize, usize, usize, u64)> { + let v = views(); + stretch_in(&v.views, at, len) +} + +fn stretch_in(views: &BTreeMap, at: usize, len: usize) -> Option<(usize, usize, usize, u64)> { + let Cover::Run(section, offset) = cover_in(views, at, len) else { + return None; + }; + // Every view of the stretch has the same address less section offset. + let delta = at as i128 - offset as i128; + let follows = |a: usize, s: usize, o: u64| s == section && a as i128 - o as i128 == delta; + let (&first, &(n, _, _)) = views.range(..=at).next_back()?; + let mut start = first; + for (&a, &(n, s, o)) in views.range(..first).rev() { + if a + n != start || !follows(a, s, o) { + break; + } + start = a; + } + let mut stop = first + n; + for (&a, &(n, s, o)) in views.range(first + 1..) { + if a != stop || !follows(a, s, o) { + break; + } + stop = a + n; + } + Some((start, stop - start, section, (start as i128 - delta) as u64)) +} + /// Another address of the title memory `[at, at + len)`, if it is a view of /// the title's pages, all of it one run of a section: in a view of ours of /// the whole section, which is never guarded (`crate::watch`) nor changed. @@ -619,7 +663,7 @@ fn hr(result: &windows::core::Result) -> String { /// A queue, a list and a fence of the probe's own on `device`: nothing of /// the host's submissions is touched. -struct Rig { +pub(crate) struct Rig { device: ID3D12Device, queue: ID3D12CommandQueue, allocator: ID3D12CommandAllocator, @@ -639,7 +683,7 @@ impl Drop for Rig { } impl Rig { - fn new(device: &ID3D12Device) -> windows::core::Result { + pub(crate) fn new(device: &ID3D12Device) -> windows::core::Result { // SAFETY: plain creation of objects of our own. unsafe { let queue: ID3D12CommandQueue = @@ -684,7 +728,7 @@ impl Rig { } /// What the GPU reads of `size` bytes of `resource` from `offset`. - fn fetch(&mut self, resource: &ID3D12Resource, offset: u64, size: usize) -> windows::core::Result> { + pub(crate) fn fetch(&mut self, resource: &ID3D12Resource, offset: u64, size: usize) -> windows::core::Result> { let back = self.committed(D3D12_HEAP_TYPE_READBACK, size as u64, D3D12_RESOURCE_STATE_COPY_DEST)?; // SAFETY: two live buffers, the range inside both. self.run(|list| unsafe { list.CopyBufferRegion(&back, 0, resource, offset, size as u64) })?; @@ -699,7 +743,7 @@ impl Rig { } /// The GPU writes `bytes` at `offset` of `resource` (a copy). - fn store(&mut self, resource: &ID3D12Resource, offset: u64, bytes: &[u8]) -> windows::core::Result<()> { + pub(crate) fn store(&mut self, resource: &ID3D12Resource, offset: u64, bytes: &[u8]) -> windows::core::Result<()> { let up = self.committed(D3D12_HEAP_TYPE_UPLOAD, bytes.len() as u64, D3D12_RESOURCE_STATE_GENERIC_READ)?; let mut data = std::ptr::null_mut(); // SAFETY: the mapping holds the buffer's bytes until unmapped. @@ -1266,7 +1310,7 @@ pub(crate) fn tick() { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; /// Views as the runtime tells them: a range inside one view, or over @@ -1319,6 +1363,28 @@ mod tests { assert_eq!(cover_in(&views, at - K64, 2 * K64), Cover::None); } + /// The stretch around a run: views on both sides that follow in memory + /// and in the section, up to a view from elsewhere or a gap. + #[test] + fn a_stretch_is_the_views_around_a_run_that_follow_in_the_section() { + let mut views = BTreeMap::new(); + let at = 0x7_2000_0000usize; + // From elsewhere in the section, just below. + views.insert(at - K64, (K64, 9, 40 * K64 as u64)); + for (k, n) in [(0usize, 2usize), (2, 3), (5, 1)] { + views.insert(at + k * K64, (n * K64, 9, ((10 + k) * K64) as u64)); + } + // Next in memory, of another section; then a gap. + views.insert(at + 6 * K64, (K64, 8, 16 * K64 as u64)); + views.insert(at + 8 * K64, (K64, 9, 18 * K64 as u64)); + let whole = Some((at, 6 * K64, 9, 10 * K64 as u64)); + assert_eq!(stretch_in(&views, at + 3 * K64 + 5, 10), whole); + assert_eq!(stretch_in(&views, at, 6 * K64), whole); + assert_eq!(stretch_in(&views, at + 5 * K64, 2 * K64), None, "into the other section"); + assert_eq!(stretch_in(&views, at + 6 * K64, K64), Some((at + 6 * K64, K64, 8, 16 * K64 as u64))); + assert_eq!(stretch_in(&views, at + 7 * K64, K64), None, "the gap"); + } + /// What the runtime forgets when memory is mapped anew. #[test] fn remapped_memory_forgets_its_views() { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index e678935..ae08b6e 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -48,6 +48,8 @@ mod indirect; #[cfg(windows)] mod inplace; #[cfg(windows)] +mod port; +#[cfg(windows)] mod land; pub mod list; pub mod object; diff --git a/crates/victory-gpu/src/port.rs b/crates/victory-gpu/src/port.rs new file mode 100644 index 0000000..22edcf3 --- /dev/null +++ b/crates/victory-gpu/src/port.rs @@ -0,0 +1,401 @@ +//! Renderer port #1: the title's 32-bit graphics heap as the card's own +//! memory (`VICTORY_PORT_CONSTANTS`, off by default). +//! +//! What the title does (game_scarlett_master.exe, the routine at image +//! +0x1e86440, reached at its start): one `XMemVirtualAlloc` of the five +//! sizes it is given together (kind 0x42000: a reservation of 64 KiB +//! pages, flags 7: graphics memory below 4 GiB, 185 MB at 0x34310000 in +//! every run so far), split into five placeholders (`VirtualFree` with +//! `MEM_PRESERVE_PLACEHOLDER`), each turned into graphics memory of its own +//! protection (`XMemVirtualAlloc`, kind 0x20406000, flags 0x27); then ONE +//! `XMemAllocatePhysicalPages` for all their pages and five +//! `XMemMapPhysicalPages`, in order, each from the next page of that one +//! array. `xmem` makes one section of all the pages, so the whole +//! reservation is one stretch of one section: views that follow one +//! another in memory and in the section alike. The title's 174 MB buffer at +//! 0x34e10000 (where its ring of constants lies, and what the skinning +//! passes write through one view of all of it) is in it; it is never +//! tile-mapped (`CopyPageMappings` maps the GPU heap's pages, not these). +//! +//! What the layer did with it: a host copy in the card's memory, the title's +//! writes found and sent up (17 MB a frame in ~600 pieces), what shaders +//! wrote fetched back and merged, and every constant buffer read out of it +//! (~6,000 fills a frame) either waited for flights or done on the card +//! from the copy. +//! +//! What is done here instead: the stretch is mapped once more, at an +//! address of ours (a view of the same section: the same physical pages), +//! and opened as a host heap there (`OpenExistingHeapFromAddress1`); title +//! buffers and windows of title memory in it are buffers placed in that +//! heap ([`crate::shadow::Shadow`]'s in-place form): the card reads and +//! writes the title's bytes where the title wrote them. Nothing is tracked, +//! sent up, fetched back or compared for it, and no compare or hash pass +//! of ours ever runs over it (they are for copies in the card's memory: +//! one such pass over memory shared with the PC removed the device on +//! another tree). No tile mapping is ever made into this heap (that removes +//! the device). +//! +//! Why our own view: a heap opened from an address holds the pages it was +//! opened on: the title could not unmap, decommit or protect them while it +//! stands. Opened on our view, the title's own views stay free to change. +//! When the title maps other pages at such an address, what is in place +//! there is let go (`crate::inplace::title_memory_freeing`) and the region +//! forgotten; the view of ours stays (shortcut: it is never unmapped, a +//! few hundred MB of address space at most). +//! +//! What it assumes: the CPU steps of ours that read this memory at +//! submission (fills of constant buffers, the title's buffer copies done on +//! the CPU) read what the title's CPU wrote, not what a submission still in +//! the air writes there: in place nothing tells the flights' writes, so +//! nothing waits for them. The title's constants are its CPU's; how many +//! such steps there are is on the frame-rate line ([`log`]). + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows_sys::Win32::System::Memory as mem; + +use crate::inplace::{Placed, cover, stretch}; + +const K64: u64 = 64 << 10; + +/// The ported memory lies below this: the title's graphics memory for +/// 32-bit addresses, which only that heap is. +const LOW: u64 = 1 << 32; + +/// The most bytes of one region: its pages are locked into the PC's memory +/// while the heap stands. +const MOST: u64 = 512 << 20; + +/// `VICTORY_PORT_CONSTANTS`: `1` turns renderer port #1 on (title buffers +/// and windows of title memory in the title's 32-bit graphics memory, view +/// memory that is one stretch of a section, used in place); unset or +/// anything else: off, everything as before. +pub(crate) fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + // Read once, here: the switch of renderer port #1. + *ON.get_or_init(|| std::env::var("VICTORY_PORT_CONSTANTS").is_ok_and(|v| v.trim() == "1")) +} + +/// A stretch of title memory opened as a heap through a view of ours. +struct Region { + start: u64, + end: u64, + heap: ID3D12Heap, +} + +// SAFETY: D3D12 heaps are free-threaded. +unsafe impl Send for Region {} + +static REGIONS: Mutex> = Mutex::new(Vec::new()); + +/// The lowest start and highest end of every region (both 0: none), for a +/// quick look on the paths that run thousands of times a frame. +static BOUNDS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// Since the start: regions opened, their bytes; title buffers and windows +/// placed; refused because the memory is not one stretch of a section, +/// not committed, refused by the host; regions forgotten because the title +/// mapped other pages there. Then, since the last line: fills read out of +/// ported memory on the CPU, their bytes, buffer copies on the CPU that +/// touch it, their bytes. +static STATS: [AtomicU64; 13] = [const { AtomicU64::new(0) }; 13]; + +/// Whether `[at, at + len)` may be ported: in the title's 32-bit graphics +/// memory. +pub(crate) fn wanted(at: u64, len: u64) -> bool { + on() && at.checked_add(len).is_some_and(|end| end <= LOW && len > 0) +} + +/// Title memory `[start, start + len)` in place, if [`wanted`] and the +/// memory is one stretch of a section: a buffer placed in the region's +/// heap. `None` leaves the caller to do what it did before. +pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option { + if !wanted(start, len) { + return None; + } + let host = crate::host::host()?; + match place_in(&host.device, start, len) { + Ok(placed) => { + crate::inplace::counted(window, len); + let n = STATS[2].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 32 || n.is_power_of_two() { + tracing::info!( + start = format_args!("{start:#x}"), + len, + window, + "renderer port 1: title memory in place, read and written by the card where the title has it" + ); + } + Some(placed) + } + Err((at, why)) => { + let n = STATS[at].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + tracing::warn!(start = format_args!("{start:#x}"), len, window, why, "renderer port 1: title memory not in place, a copy as before"); + } + None + } + } +} + +/// [`place_for`]'s work: the region holding the pages of `[start, start + +/// len)`, opened if none does, and a buffer placed in it. `Err` with the +/// statistic to count and why. +pub(crate) fn place_in(device: &ID3D12Device, start: u64, len: u64) -> Result { + let at = start & !(K64 - 1); + let end = (start + len.max(1)).next_multiple_of(K64); + let mut regions = REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + let i = match regions.iter().position(|r| r.start <= at && end <= r.end) { + Some(i) => i, + None => { + let region = open_region(device, at, end)?; + regions.push(region); + let n = regions.len() - 1; + let r = ®ions[n]; + STATS[0].fetch_add(1, Ordering::Relaxed); + STATS[1].fetch_add(r.end - r.start, Ordering::Relaxed); + bounds(®ions); + n + } + }; + let region = ®ions[i]; + let buffer = crate::inplace::place(device, ®ion.heap, at - region.start, end - at).map_err(|e| (6, format!("no buffer placed in the region: {e}")))?; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() } + (start - at); + Ok(Placed { buffer, heap: region.heap.clone(), gpu, bias: start - at }) +} + +/// Opens the stretch around `[at, end)` (64 KiB aligned) as a heap through +/// a view of ours of the same pages. +fn open_region(device: &ID3D12Device, at: u64, end: u64) -> Result { + let Some((first, bytes, section, offset)) = stretch(at as usize, (end - at) as usize) else { + return Err((3, format!("not one stretch of a section: {:?}", cover(at as usize, (end - at) as usize)))); + }; + // The whole stretch, kept to what may be ported: the next buffer in it + // finds the region made. + let (mut first, mut bytes, mut offset) = (first as u64, bytes as u64, offset); + if first < LOW && first + bytes > LOW { + bytes = LOW.saturating_sub(first); + } + if bytes > MOST { + // Only what was asked for. + offset += at - first; + (first, bytes) = (at, end - at); + } + if bytes > MOST { + return Err((3, format!("{bytes:#x} bytes, over the most of a region"))); + } + if first > at || first + bytes < end || offset % K64 != 0 { + return Err((3, format!("the stretch {first:#x}+{bytes:#x} does not hold it"))); + } + // SAFETY: the section of a view the title has; the runtime keeps its + // handle open while a view of it is there, and the range is inside it. + let view = unsafe { mem::MapViewOfFile(section as _, mem::FILE_MAP_WRITE, (offset >> 32) as u32, offset as u32, bytes as usize) }.Value as usize; + if view == 0 { + return Err((5, format!("no view of the stretch: {}", std::io::Error::last_os_error()))); + } + let unmap = || { + // SAFETY: our own view, nothing opened on it. + unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) }; + }; + if !committed(view, bytes as usize) { + unmap(); + return Err((4, "pages of the stretch are not committed".to_owned())); + } + match crate::inplace::open(device, crate::inplace::From::Part(view, bytes as usize)) { + Ok(heap) => { + tracing::info!( + start = format_args!("{first:#x}"), + bytes, + section = format_args!("{section:#x}"), + offset = format_args!("{offset:#x}"), + view = format_args!("{view:#x}"), + "renderer port 1: a stretch of the title's graphics memory opened as a host heap through a view of ours" + ); + // shortcut: the view stays mapped for good (the heap holds its + // pages while anything names it). + Ok(Region { start: first, end: first + bytes, heap }) + } + Err(e) => { + unmap(); + Err((5, format!("refused by the host: {e}"))) + } + } +} + +/// Whether every page of `[at, at + len)` is committed. +fn committed(at: usize, len: usize) -> bool { + let mut here = at; + while here < at + len { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + if unsafe { mem::VirtualQuery(here as *const _, &mut info, size_of_val(&info)) } == 0 || info.State != mem::MEM_COMMIT { + return false; + } + here = (info.BaseAddress as usize).saturating_add(info.RegionSize); + } + true +} + +fn bounds(regions: &[Region]) { + let lo = regions.iter().map(|r| r.start).min().unwrap_or(0); + let hi = regions.iter().map(|r| r.end).max().unwrap_or(0); + BOUNDS[0].store(lo, Ordering::Relaxed); + BOUNDS[1].store(hi, Ordering::Relaxed); +} + +/// The title maps other pages at `[at, at + len)`: the regions over it are +/// forgotten (what is placed in them is let go by the caller). +pub(crate) fn forget(at: usize, len: usize) { + let (at, end) = (at as u64, (at as u64).saturating_add(len as u64)); + if BOUNDS[1].load(Ordering::Relaxed) <= at || BOUNDS[0].load(Ordering::Relaxed) >= end { + return; + } + let mut regions = REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + let before = regions.len(); + regions.retain(|r| r.end <= at || r.start >= end); + STATS[7].fetch_add((before - regions.len()) as u64, Ordering::Relaxed); + bounds(®ions); +} + +/// Whether `[at, at + len)` touches ported memory (a quick look). +fn touches(at: usize, len: usize) -> bool { + let hi = BOUNDS[1].load(Ordering::Relaxed); + hi != 0 && (at as u64) < hi && (at as u64).saturating_add(len as u64) > BOUNDS[0].load(Ordering::Relaxed) +} + +/// A fill of upload memory read `len` bytes at `src` on the CPU. +pub(crate) fn filled(src: usize, len: usize) { + if touches(src, len) { + STATS[9].fetch_add(1, Ordering::Relaxed); + STATS[10].fetch_add(len as u64, Ordering::Relaxed); + } +} + +/// A title buffer copy was done on the CPU. +pub(crate) fn copied(dst: usize, src: usize, len: usize) { + if touches(dst, len) || touches(src, len) { + STATS[11].fetch_add(1, Ordering::Relaxed); + STATS[12].fetch_add(len as u64, Ordering::Relaxed); + } +} + +/// For the frame-rate line: what is in place, and what of ours read or +/// wrote it on the CPU per frame. +pub(crate) fn log(frames: f64) { + if !on() { + return; + } + let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + let per: Vec = STATS[9..].iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "renderer port 1 (VICTORY_PORT_CONSTANTS=1): {} regions of the title's graphics memory in place ({} MB), {} title buffers and windows placed in them \ + (no host copy, nothing sent up or fetched back for them); per frame on the CPU: {:.0} fills read out of them ({:.1} KB), {:.1} buffer copies \ + touching them ({:.1} KB); since the start refused: {} not one stretch of a section, {} not committed, {} by the host, {} no buffer; {} regions \ + forgotten (other pages mapped there)", + s[0], + s[1] >> 20, + s[2], + per[0], + per[1] / 1024.0, + per[2], + per[3] / 1024.0, + s[3], + s[4], + s[5], + s[6], + s[7], + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Only the title's 32-bit memory is asked for. + #[test] + fn only_memory_below_4_gib_is_wanted_with_the_switch() { + // The switch is read once from the environment; tests do not set + // it, so nothing is wanted. + if !on() { + assert!(!wanted(0x3431_0000, 0x1000)); + } + let low = |at: u64, len: u64| at.checked_add(len).is_some_and(|end| end <= LOW && len > 0); + assert!(low(0x34e1_0000, 0xae0_0000)); + assert!(!low(0xffff_0000, 0x2_0000)); + assert!(!low(0xe1c80_0000, 0x1000)); + assert!(!low(u64::MAX, 2)); + } + + /// A stretch of a reserved section, mapped as `xmem` maps physical + /// pages (views of consecutive pages in turn, committed), is opened + /// through a view of ours: the card reads the bytes the title's views + /// show, at the buffer's offset, and its writes show in them; a second + /// buffer in the stretch is placed in the same region. + #[test] + fn warp_a_stretch_of_a_reserved_section_is_used_in_place_through_a_view_of_ours() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = crate::inplace::tests::warp() else { return }; + if windows::core::Interface::cast::(&device).is_err() { + return; + } + const K: usize = 64 << 10; + // SAFETY (the whole test): the section, placeholder and views made + // here. + unsafe { + let process = windows_sys::Win32::System::Threading::GetCurrentProcess(); + let section = mem::CreateFileMappingW( + windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE, + std::ptr::null(), + mem::PAGE_READWRITE | mem::SEC_RESERVE, + 0, + 8 * K as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let hole = mem::VirtualAlloc2(process, std::ptr::null(), 8 * K, mem::MEM_RESERVE | mem::MEM_RESERVE_PLACEHOLDER, mem::PAGE_NOACCESS, std::ptr::null_mut(), 0) + .cast::(); + assert!(!hole.is_null()); + // Two views, pages 0..3 and 3..8 of the section, in turn. + mem::VirtualFree(hole.cast(), 3 * K, mem::MEM_RELEASE | mem::MEM_PRESERVE_PLACEHOLDER); + let mut views = Vec::new(); + for (page, n) in [(0usize, 3usize), (3, 5)] { + let view = mem::MapViewOfFile3(section, process, hole.add(page * K).cast(), (page * K) as u64, n * K, mem::MEM_REPLACE_PLACEHOLDER, mem::PAGE_READWRITE, std::ptr::null_mut(), 0); + assert!(!view.Value.is_null(), "{}", std::io::Error::last_os_error()); + assert!(!mem::VirtualAlloc(view.Value, n * K, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null()); + crate::inplace::title_memory_view(view.Value as usize, n * K, section as usize, (page * K) as u64); + views.push(view); + } + let base = hole as u64; + let (start, len) = (base + K as u64 + 0x40, 5 * K as u64); + let placed = place_in(&device, start, len).unwrap_or_else(|e| panic!("not placed: {e:?}")); + assert_eq!(placed.bias, 0x40); + let mut rig = crate::inplace::Rig::new(&device).unwrap(); + for (i, b) in std::slice::from_raw_parts_mut(start as *mut u8, len as usize).iter_mut().enumerate() { + *b = (i * 7 + 3) as u8; + } + let got = rig.fetch(&placed.buffer, placed.bias, len as usize).unwrap(); + assert!(got == std::slice::from_raw_parts(start as *const u8, len as usize), "the card reads the title's bytes, across both views"); + rig.store(&placed.buffer, placed.bias + 3 * K as u64, &[0x5a; 256]).unwrap(); + assert!(std::slice::from_raw_parts((start + 3 * K as u64) as *const u8, 256).iter().all(|&b| b == 0x5a), "the card's write shows in the title's view"); + // Another buffer in the same stretch: the same region. + let regions = REGIONS.lock().unwrap().len(); + let second = place_in(&device, base + 6 * K as u64, 100).unwrap_or_else(|e| panic!("not placed: {e:?}")); + assert_eq!(REGIONS.lock().unwrap().len(), regions, "one region for the stretch"); + assert_eq!(second.bias, 0); + // The title's views may change under the heap. + drop((placed, second)); + forget(base as usize, 8 * K); + for view in views { + assert!(mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER) != 0, "the title's own view can be unmapped"); + } + crate::inplace::views_gone(base as usize, 8 * K); + mem::VirtualFree(hole.cast(), 0, mem::MEM_RELEASE); + mem::VirtualFree(hole.add(3 * K).cast(), 0, mem::MEM_RELEASE); + windows_sys::Win32::Foundation::CloseHandle(section); + } + } +} diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index cde6ec0..18bdfa2 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -5217,6 +5217,12 @@ fn lookup(address: u64, len: u64, any: bool) -> Option> { // memory. Not the big ones `cards` puts in the card's memory: those // are read too often to stay in the PC's. let big = cards() && (size >= card_limits().0 || card_all()); + // Renderer port 1 (`crate::port`, `VICTORY_PORT_CONSTANTS=1`): the + // title's 32-bit graphics heap in place, big or not. + if let Some(placed) = crate::port::place_for(key.0, len, false) { + entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); + return entry.shadow.clone(); + } if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) { entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); return entry.shadow.clone(); @@ -5549,7 +5555,7 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option