From 12b078ee3aa93b033ac8301050a1332d9da3eeb5 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 22:09:38 -0600 Subject: [PATCH 1/2] Views guarded while they are mapped stay writable; tests take turns on WARP The runtime maps a view and then tells the write watch. A refresh on another thread could guard the new blocks in between, and the telling then forgot them and left them read-only: the title's next write to one was an access violation nobody takes. Told of a new view, the watch now gives the write access back; before an unmapping it only forgets, as before. The test binary's random crashes were d3d10warp.dll's own, with two tests on the software adapter at once: they take turns now. The watch's tests forget their guards before their memory is freed (another test's memory could get the address and inherit them), and three more are no longer tied to other tests' memory, the adapter's other work or a busy PC's timing. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/frame.rs | 36 ++++++--- crates/victory-gpu/src/indirect.rs | 17 +++- crates/victory-gpu/src/inplace.rs | 13 ++- crates/victory-gpu/src/lib.rs | 3 +- crates/victory-gpu/src/watch.rs | 108 +++++++++++++++++++++---- crates/victory-hle/src/modules/xmem.rs | 2 +- 6 files changed, 146 insertions(+), 33 deletions(-) diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 798b760..7863e22 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -208,7 +208,8 @@ mod tests { let mut second = 0; assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK); assert!(second > first); - assert!(before.elapsed() <= Duration::from_millis(50)); + // At the tick, not at the time-out (a busy PC may wake it late). + assert!(before.elapsed() <= Duration::from_millis(500)); assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT); // Tokens count frames, a frame started early on a time-out too. let mut early = 0; @@ -226,18 +227,29 @@ mod tests { // origin poll that times out (and starts the frame), then a // blocking flip wait. Each flip takes its own tick. const FLIP: u32 = 2; - assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK); + // (The ticks are far apart, and it may take a few tries: a busy PC + // wakes a wait tens of milliseconds late at times.) + assert_eq!(set_interval(null, null, 60_000, 3, 0), S_OK); let mut token = 0; - let flips: Vec = (0..4) - .map(|_| { - let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); - assert_eq!( - wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), - S_OK - ); - LAST[2].load(Ordering::Relaxed) - }) - .collect(); + let mut four = || -> Vec { + (0..4) + .map(|_| { + let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); + assert_eq!( + wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), + S_OK + ); + LAST[2].load(Ordering::Relaxed) + }) + .collect() + }; + let mut flips = four(); + for _ in 0..10 { + if flips.windows(2).all(|w| w[1] == w[0] + 1) { + break; + } + flips = four(); + } assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}"); // Even when a flip wait begins on the tick another just ended on. let (tick, _) = next_tick(FLIP); diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index af7f010..b8128ea 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -491,7 +491,7 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; @@ -521,10 +521,24 @@ void main() { event: HANDLE, clamp: Clamp, worker: Clamp, + /// Last, so given up last. + _turn: std::sync::MutexGuard<'static, ()>, + } + + /// The software adapter is one test's at a time. Two tests that compile + /// and run shaders on it at once (it is one device for the process) make + /// `d3d10warp.dll` (10.0.26100) crash now and then: access violations in + /// its own shader compiler, on its own worker threads, in 12% of runs of + /// all tests and 3% of runs of these alone on two threads; none in 100 + /// runs one after the other. + pub(crate) fn warp_turn() -> std::sync::MutexGuard<'static, ()> { + static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + TURN.lock().unwrap_or_else(|e| e.into_inner()) } impl WarpHarness { fn new() -> Option { + let turn = warp_turn(); // SAFETY: plain DXGI WARP query and D3D12 test harness setup. unsafe { let factory: IDXGIFactory4 = @@ -563,6 +577,7 @@ void main() { event, clamp, worker, + _turn: turn, }) } } diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 25461df..bcafed8 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -1099,6 +1099,7 @@ mod tests { /// driver is what a run with `VICTORY_INPLACE_PROBE=1` adds. #[test] fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() { + let _turn = crate::indirect::tests::warp_turn(); let Some(device) = warp() else { return }; if device.cast::().is_err() { eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened"); @@ -1122,6 +1123,7 @@ mod tests { /// whole is turned down without asking the host. #[test] fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() { + let _turn = crate::indirect::tests::warp_turn(); let Some(device) = warp() else { return }; if device.cast::().is_err() { return; @@ -1142,7 +1144,16 @@ mod tests { assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); drop(placed); // Half of it decommitted: turned down, the host not asked. - assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0); + // The heap lets go of the pages a moment after its last + // reference, if the adapter is busy with other tests' work. + let gone = (0..500).any(|_| { + let done = mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(gone, "the heap keeps the pages"); assert!(matches!(place_part(&device, start, len), Err(None))); mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 2ecf3ab..ab6102e 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -68,5 +68,6 @@ pub use host::on_failure; pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; #[cfg(windows)] pub use watch::{ - title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write, + title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping, + writing as kernel_will_write, }; diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 27774d6..74b0d80 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -732,10 +732,38 @@ pub fn title_memory_reading_now() -> Option { } } -/// The runtime mapped or unmapped title memory `[at, at + len)`: what it -/// shows is new and read-write, so it is no longer guarded (nor known -/// unmapped). +/// The runtime mapped title memory `[at, at + len)`: what it shows is new, +/// so it is no longer guarded (nor known unmapped), and read-write. +/// +/// The view is there before we are told of it, and a copy's refresh on +/// another thread may have guarded its blocks in between (it finds blocks +/// it knew absent committed, and holds [`GUARDS`], which we wait for). +/// Forgetting such a block and leaving it read-only would make the title's +/// next write to it an access violation nobody takes (`on_write` finds it +/// neither guarded nor writable) and a kernel read into it fail, so the +/// write access is given back. pub fn title_memory_remapped(at: usize, len: usize) { + open(&mut title_memory_changed(at, len), at, at.saturating_add(len)); +} + +/// The runtime is about to unmap title memory `[at, at + len)`: it is +/// nothing of ours any more. Its protection goes with it. +pub fn title_memory_unmapping(at: usize, len: usize) { + let mut g = title_memory_changed(at, len); + let blocks: Vec = g + .protected + .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) + .copied() + .collect(); + for block in blocks { + g.protected.remove(&block); + g.clean.remove(&block); + } +} + +/// Tells what keeps track of what title memory shows; the guards, with no +/// block of the range known unmapped. +fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, Guards> { // A placed texture there arrives, goes or changes with no descriptor // written. crate::descriptor::host::remapped(at, len); @@ -745,15 +773,11 @@ pub fn title_memory_remapped(at: usize, len: usize) { crate::inplace::title_memory_freeing(at, len); let mut g = guards(); let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK); - let absent: Vec = g.absent.range(range.clone()).copied().collect(); + let absent: Vec = g.absent.range(range).copied().collect(); for block in absent { g.absent.remove(&block); } - let blocks: Vec = g.protected.range(range).copied().collect(); - for block in blocks { - g.protected.remove(&block); - g.clean.remove(&block); - } + g } /// Registers the handler that takes writes to guarded blocks, once, ahead @@ -843,16 +867,18 @@ mod tests { } as usize; assert_ne!(p, 0); let (start, end) = (p, p + 4 * PAGE); - let (_, before) = writes(start, end, false).expect("watched"); - assert!(before.is_empty()); + // The journal may hold pages of another test's memory that was here. + let (none, before) = writes(start, end, false).expect("watched"); + assert!(before.iter().all(|&(_, w)| w < none), "{before:?}"); // SAFETY: committed pages of ours. unsafe { ((p + PAGE + 8) as *mut u8).write(1) }; let (now, after) = writes(start, end, false).expect("watched"); - assert_eq!(after, [(p / PAGE + 1, now)]); + let new = |w: Vec<(usize, u64)>| w.into_iter().filter(|w| w.1 > none).collect::>(); + assert_eq!(new(after), [(p / PAGE + 1, now)]); // Another asker after the kernel's bit was cleared still sees it. let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched"); assert!(later > now); - assert_eq!(again, [(p / PAGE + 1, now)]); + assert_eq!(new(again), [(p / PAGE + 1, now)]); let mut plain = vec![0u8; PAGE]; assert!( writes( @@ -911,6 +937,9 @@ mod tests { guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()) ); + // Before the view goes, as the runtime does: the address may be + // another test's the moment it is free. + title_memory_unmapping(view, 2 * BLOCK); // SAFETY: our view. unsafe { UnmapViewOfFile( @@ -919,7 +948,52 @@ mod tests { }, ) }; - title_memory_remapped(view, 2 * BLOCK); + } + + /// The runtime maps a view and then tells us; a copy's refresh on another + /// thread can guard it in between. Told, it is the title's to write: a + /// block left read-only and forgotten would be an access violation in + /// title code. + #[test] + fn a_block_guarded_before_we_were_told_of_its_view_can_be_written() { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile, + }; + // SAFETY: a pagefile section of two blocks, mapped read-write; the + // view holds it. + let view = unsafe { + let section = CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK); + CloseHandle(section); + view + }; + let at = view.Value as usize; + assert_ne!(at, 0); + // The refresh, then the runtime's word. + assert!(guard(at, at + 2 * BLOCK).is_some()); + assert!(!writable(at) && !writable(at + BLOCK)); + title_memory_remapped(at, 2 * BLOCK); + assert!(writable(at) && writable(at + BLOCK)); + // SAFETY: inside the view; a fault would end the process. + unsafe { ((at + 8) as *mut u8).write_volatile(1) }; + // Looked at again as new, and guarded again. + assert_eq!( + guard(at, at + 2 * BLOCK), + Some((at / PAGE..at / PAGE + 2).collect()) + ); + assert!(!writable(at)); + title_memory_unmapping(at, 2 * BLOCK); + // SAFETY: our view. + unsafe { UnmapViewOfFile(view) }; } #[test] @@ -934,7 +1008,7 @@ mod tests { struct View(MEMORY_MAPPED_VIEW_ADDRESS); impl Drop for View { fn drop(&mut self) { - title_memory_remapped(self.0.Value as usize, SIZE); + title_memory_unmapping(self.0.Value as usize, SIZE); // SAFETY: our view is still mapped. unsafe { UnmapViewOfFile(self.0) }; } @@ -1060,6 +1134,7 @@ mod tests { let mut local = [0u8; 16]; let at = local.as_mut_ptr() as usize; assert!(!is_view(at, at + local.len())); + title_memory_unmapping(p, 3 * BLOCK); // SAFETY: our views and placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); @@ -1069,7 +1144,6 @@ mod tests { } windows_sys::Win32::Foundation::CloseHandle(section); } - title_memory_remapped(p, 3 * BLOCK); } /// Blocks of a placeholder between views are reported once, then not @@ -1144,6 +1218,7 @@ mod tests { title_memory_remapped(p + BLOCK, BLOCK); assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + title_memory_unmapping(p, 3 * BLOCK); // SAFETY: our views and placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); @@ -1153,7 +1228,6 @@ mod tests { } windows_sys::Win32::Foundation::CloseHandle(section); } - title_memory_remapped(p, 3 * BLOCK); } /// A write or mapping that runs past the end of the address space (a diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index fe5b4c5..56d56ca 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -1028,7 +1028,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { continue; }; physical.forget_view(at, size, &slice); - victory_gpu::title_memory_remapped(at, size); + victory_gpu::title_memory_unmapping(at, size); // SAFETY: a view we mapped; it becomes a placeholder again. unsafe { UnmapViewOfFile2( From 8a475da9cf74dcb60cab56a9d1506fea1caf6091 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:10:44 -0600 Subject: [PATCH 2/2] Kernel reads, remapped views, freed memory and lost writes of title memory - What the kernel is writing (file reads) is not guarded by a refresh before the call is done (`kernel_writing`): the read would have failed. - A title thread that uses a page while the runtime remaps another page of the same view waits for that in the fault handler; it faulted on a page the title never gave up. - Blocks being unmapped are not guarded again, memory the title frees leaves no notes of its blocks (its VirtualFree is taken over), and other memory at an address once guarded or absent keeps its protection. - The second part of a submission's one asking has a number of its own. - What shaders wrote waits for a change of mapping instead of being lost; what could not be written is counted and said; zeros into title memory that went are no fault. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 53 +- crates/victory-gpu/src/land.rs | 22 +- crates/victory-gpu/src/land/tests.rs | 37 ++ crates/victory-gpu/src/lib.rs | 4 +- crates/victory-gpu/src/shadow.rs | 39 +- crates/victory-gpu/src/watch.rs | 573 ++++++++++++++++++++- crates/victory-hle/src/modules/dstorage.rs | 6 +- crates/victory-hle/src/modules/files.rs | 31 +- crates/victory-hle/src/modules/xmem.rs | 70 ++- 9 files changed, 803 insertions(+), 32 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index eeeae77..35093b0 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -704,6 +704,22 @@ fn warp_adapter() -> windows::core::Result { #[cfg(test)] mod tests { + /// Zeros for a title destination that went meanwhile are no fault. + #[test] + fn zeros_where_nothing_is_are_lost() { + use windows_sys::Win32::System::Memory::*; + // SAFETY: a reservation of ours, its first page committed. + unsafe { + let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null()); + at.write_bytes(7, 4096); + super::zero(at, 4096); + assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0)); + super::zero(at.add(4096), 4096); + VirtualFree(at.cast(), 0, MEM_RELEASE); + } + } + #[test] fn sparse_copies_preserve_islands_and_observe_remaps() { use windows_sys::Win32::System::Memory::*; @@ -6407,7 +6423,10 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b } #[cfg(feature = "diagnostics")] let moved = std::time::Instant::now(); - let whole = read(src, dst, len); + let since = crate::watch::changes(); + // (A title destination that is away only while the runtime changes a + // mapping beside it is written when that is done.) + let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len)); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64); if whole { @@ -6417,6 +6436,7 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b // not all mapped. Then the destination stays as it is (the kernel may // have written its first pages). if title_dst && !ask_first && !crate::texture::committed(dst, len) { + crate::watch::lost("a copy of the title's", dst as usize, len); return; } #[cfg(feature = "diagnostics")] @@ -6476,14 +6496,29 @@ fn read_pieces(src: *const u8, dst: *mut u8, len: usize) { if !read(at as *const u8, to, n) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Unmapped, n as u64); - // SAFETY: inside the destination, which is mapped. - unsafe { to.write_bytes(0, n) }; + zero(to, n); } }); } }); } +/// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the +/// destination of a title's copy), which can go between the question whether +/// it is there and this. +fn zero(to: *mut u8, n: usize) { + static ZEROS: [u8; 4096] = [0; 4096]; + if n <= ZEROS.len() && crate::safecopy::on() { + // SAFETY: a destination that is not there fails the copy. + if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } { + crate::watch::lost("zeros", to as usize, n); + } + return; + } + // SAFETY: inside the destination, which is mapped. + unsafe { to.write_bytes(0, n) }; +} + /// Reads title memory at `src` into `dst`; false if a page of it is not /// readable. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool { @@ -6537,6 +6572,7 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; let direct = direct_writes(); + let since = crate::watch::changes(); let write = |at: usize, n: usize| { let from = src.wrapping_add(at - dst as usize); if crate::safecopy::on() { @@ -6563,7 +6599,16 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { for_pieces(dst as usize, len, 64 << 10, |at, n| { if !write(at, n) { for_pieces(at, n, 4 << 10, |at, n| { - write(at, n); + if write(at, n) { + return; + } + // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a + // refresh guarded the block again since the caller opened + // it; and any where the runtime was changing a mapping. + crate::watch::writing(at, n); + if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) { + crate::watch::lost("a host copy's bytes", at, n); + } }); } }); diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 67ae9cd..c8cfc26 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -499,6 +499,7 @@ unsafe fn piece_at( spent(stat::NOTES, opening); } let into = beside.unwrap_or(title); + let since = crate::watch::changes(); let (mut pages, mut new_pages, mut blocks, mut dwords, mut missing) = (0, 0u64, 0, 0, 0); let mut span: Option<(usize, usize)> = None; for_pages(title, parts, |from, n| { @@ -508,7 +509,26 @@ unsafe fn piece_at( } // SAFETY: the caller's; title memory, by an address that shows it // (`beside`) or the title's own. - let done = unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) }; + let merge = |take| unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) }; + let mut done = merge(take && beside.is_some()); + if !done.there && beside.is_none() { + // Away only while the runtime changes a mapping beside it: the + // rest of it when that is done. What is still not there then is + // taken as the caller says. + let mut put = done.dwords; + let again = crate::watch::again_after_change(since, || { + done = merge(false); + put += done.dwords; + done.there + }); + if !again && take { + done = merge(true); + put += done.dwords; + } + done.dwords = put; + // (What was new to the first try was new.) + done.new = done.new.max(1); + } blocks += done.new; dwords += done.dwords; missing += u64::from(!done.there); diff --git a/crates/victory-gpu/src/land/tests.rs b/crates/victory-gpu/src/land/tests.rs index f2fef9f..64eef53 100644 --- a/crates/victory-gpu/src/land/tests.rs +++ b/crates/victory-gpu/src/land/tests.rs @@ -213,6 +213,43 @@ fn a_piece_lands_what_the_card_wrote_in_its_parts() { } } +/// A piece whose title memory is away only while the runtime changes a +/// mapping lands when that is done; where it stays away the copy's CPU side +/// takes the card's bytes (`take`) or not. +#[test] +fn a_piece_waits_for_a_change_of_mapping() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, VirtualAlloc, VirtualFree}; + assert!(crate::safecopy::on()); + // SAFETY: a reservation of ours, nothing of it committed. + let at = unsafe { VirtualAlloc(std::ptr::null(), BLOCK, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert_ne!(at, 0); + let now = [9u8; 100]; + for take in [true, false] { + let mut held = [0u8; 100]; + // SAFETY: arrays of 100 bytes. + let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], take, &mut Notes::default()) }; + assert_eq!((put, held), (0, [if take { 9 } else { 0 }; 100])); + } + let (began, wait) = std::sync::mpsc::channel(); + let change = std::thread::spawn(move || { + let _changing = crate::watch::title_memory_remapping(); + began.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + // SAFETY: the reservation's first page. + assert!(!unsafe { VirtualAlloc(at as _, PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + }); + wait.recv().unwrap(); + let mut held = [0u8; 100]; + // SAFETY: as above. + let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], true, &mut Notes::default()) }; + change.join().unwrap(); + assert_eq!((put, held), (100, now)); + // SAFETY: committed by now. + assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 100) }, now); + // SAFETY: our reservation. + unsafe { VirtualFree(at as _, 0, MEM_RELEASE) }; +} + /// Landings on several threads beside title threads that write the same /// blocks (other dwords) and a thread that refreshes a copy, guarding what /// it takes: no write of the title's is lost or undone, all the card wrote diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index faabc53..d32be35 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -70,6 +70,6 @@ pub use host::on_failure; pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] pub use watch::{ - title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping, - writing as kernel_will_write, + kernel_writing, title_memory_freed, title_memory_reading, title_memory_remapped, title_memory_remapping, + title_memory_unmapping, writing as kernel_will_write, }; diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 091c5ed..d70895d 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1561,6 +1561,7 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { if crate::safecopy::on() { PUT[0].fetch_add(1, Ordering::Relaxed); PUT[2].fetch_add(merged.len() as u64, Ordering::Relaxed); + let since = crate::watch::changes(); // SAFETY: title memory; a page of it that is not there fails the // put, and the rest is put page by page. if unsafe { crate::safecopy::put_changed(at as *mut u8, title, merged) } { @@ -1569,8 +1570,14 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { let mut from = 0; while from < merged.len() { let n = (4096 - (at + from) % 4096).min(merged.len() - from); + let (was, now) = (&title[from..from + n], &merged[from..from + n]); // SAFETY: as above. - unsafe { crate::safecopy::put_changed((at + from) as *mut u8, &title[from..from + n], &merged[from..from + n]) }; + let put = || unsafe { crate::safecopy::put_changed((at + from) as *mut u8, was, now) }; + // A page that is away only while the runtime changes a mapping + // beside it gets its bytes when that is done. + if !put() && !crate::watch::again_after_change(since, put) { + crate::watch::lost("what shaders wrote", at + from, n); + } from += n; } return merged.len(); @@ -1614,7 +1621,35 @@ pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, ti #[cfg(test)] mod merge_tests { - use super::{changed_runs, dword_runs}; + use super::{changed_runs, dword_runs, put_changed}; + + /// What shaders wrote reaches a page that is away only while the runtime + /// changes a mapping; a page that stays away loses it, and nothing else. + #[test] + fn a_put_waits_for_a_change_of_mapping() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + // SAFETY: a reservation of ours, nothing of it committed. + let at = unsafe { VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert_ne!(at, 0); + put_changed(at, &[0; 64], &[3; 64]); + let (began, wait) = std::sync::mpsc::channel(); + let change = std::thread::spawn(move || { + let _changing = crate::watch::title_memory_remapping(); + began.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + // SAFETY: the reservation's first page. + assert!(!unsafe { VirtualAlloc(at as _, 4096, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + }); + wait.recv().unwrap(); + put_changed(at, &[0; 64], &[1; 64]); + change.join().unwrap(); + // SAFETY: committed by now. + assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 64) }, [1; 64]); + // SAFETY: our reservation. + unsafe { VirtualFree(at as _, 0, MEM_RELEASE) }; + } /// Whole dwords around every changed byte and no other, whatever the /// alignment; small gaps joined only when asked. diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index dfae9f4..f6ef170 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -279,13 +279,15 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { } ask_once_end(); ask_ahead(ranges); + ask_rest(ranges); +} + +/// [`ask_once`] after its [`ask_ahead`]: what that left to `writes`, and the +/// asking stands. +fn ask_rest(ranges: &[(usize, usize)]) { let _all = Asking::hold_all(); let mut ahead = { let mut j = journal_mut(); - if j.ahead.is_empty() { - // `ask_ahead` asked nothing (fewer than two ranges). - j.ahead_asked = next_asking(); - } std::mem::take(&mut j.ahead) }; // `ask_ahead` leaves a range that lies alone to `writes`, which asks @@ -307,7 +309,12 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { } } let mut j = journal_mut(); - let now = j.ahead_asked; + // A number of its own, and the one this asking stands under: between + // the two parts another thread may have asked about a range of the + // second, copied it, and the title written it since. Under the first + // part's number that write was older than the copy, and never copied. + let now = next_asking(); + j.ahead_asked = now; j.written.extend(written.into_iter().map(|page| (page, now))); j.kept = !ahead.is_empty(); j.ahead = ahead; @@ -622,12 +629,30 @@ struct Guards { /// Blocks already copied as zeros. While they remain wholly uncommitted, /// the copy can skip hundreds of MB of failing kernel reads per world frame. absent: BTreeSet, + /// Blocks that were absent and turned out to be other memory than views + /// when something was there again: never guarded, copied every time. + foreign: BTreeSet, + /// Blocks (first, past the last) the kernel writes now + /// ([`kernel_writing`]), and blocks the runtime has unmapped in a change + /// not yet done ([`title_memory_unmapping`]). Not in the sets above, and + /// left as they are by [`guard`], which reports them written. + kernel: Vec<(usize, usize)>, + changing: Vec<(usize, usize)>, +} + +impl Guards { + fn left_alone(&self, block: usize) -> bool { + self.kernel.iter().chain(&self.changing).any(|&(first, last)| (first..last).contains(&block)) + } } static GUARDS: Mutex = Mutex::new(Guards { protected: BTreeSet::new(), clean: BTreeSet::new(), absent: BTreeSet::new(), + foreign: BTreeSet::new(), + kernel: Vec::new(), + changing: Vec::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { @@ -795,6 +820,11 @@ fn guard(start: usize, end: usize) -> Option> { open = block >= uncommitted_until; if open { g.absent.remove(&block); + // The hole may have been given up, and its address be the + // title's heap's, or code's, now: not ours to guard. + if !is_view(block * BLOCK, (block + 1) * BLOCK) { + g.foreign.insert(block); + } } } if open { @@ -802,7 +832,7 @@ fn guard(start: usize, end: usize) -> Option> { if g.protected.contains(&block) { // Written through the runtime, still read-only. g.clean.insert(block); - } else { + } else if !g.foreign.contains(&block) && !g.left_alone(block) { run.get_or_insert(block); continue; } @@ -862,13 +892,13 @@ fn is_view(start: usize, end: usize) -> bool { /// block by block if they span views, leaving out any that fail, and /// noting those not committed (unmapped) absent. fn protect(g: &mut Guards, from: usize, to: usize) { - use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; + use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; let set = |from: usize, to: usize| { let mut old = 0; #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); // SAFETY: title view memory; only its protection changes. - let done = unsafe { + let mut done = unsafe { VirtualProtect( (from * BLOCK) as *const _, (to - from) * BLOCK, @@ -876,6 +906,13 @@ fn protect(g: &mut Guards, from: usize, to: usize) { &mut old, ) != 0 }; + if done && !matches!(old, PAGE_READWRITE | PAGE_READONLY) { + // What is there is not for us to guard (code, or memory the + // title protects itself): as it was. + // SAFETY: as above. + unsafe { VirtualProtect((from * BLOCK) as *const _, (to - from) * BLOCK, old, &mut old) }; + done = false; + } #[cfg(feature = "diagnostics")] { tally(5, (to - from) as u64); @@ -919,7 +956,7 @@ fn uncommitted_end(block: usize) -> usize { /// Gives write access back to the guarded blocks of `[start, end)` and /// notes them written; true if any was guarded. fn open(g: &mut Guards, start: usize, end: usize) -> bool { - use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; let blocks: Vec = g .protected .range(start / BLOCK..end.div_ceil(BLOCK)) @@ -934,7 +971,15 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { PUBLISHED.clear(block); let mut old = 0; // SAFETY: a block we made read-only. - unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; + unsafe { + if VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) != 0 + && !matches!(old, PAGE_READONLY | PAGE_READWRITE) + { + // Not what we left there: the address is other memory's + // (code's, say), which keeps its protection. + VirtualProtect((block * BLOCK) as *const _, BLOCK, old, &mut old); + } + } } #[cfg(feature = "diagnostics")] if !blocks.is_empty() { @@ -961,6 +1006,41 @@ pub fn writing(at: usize, len: usize) { crate::descriptor::host::remapped(at, len); } +/// The kernel writes title memory `[at, at + len)` until what this returns +/// is dropped ([`kernel_writing`]). +pub struct KernelWrite(usize, usize); + +/// The runtime is about to have the kernel write title memory +/// `[at, at + len)` (a file read): its guarded blocks are opened, as by +/// [`writing`], and no refresh guards them again before what this returns is +/// dropped, at the end of that call. One that did would make the kernel's +/// write fail (the kernel does not fault into our handler): a read cut +/// short, which the title takes for what the file holds. +pub fn kernel_writing(at: usize, len: usize) -> KernelWrite { + let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); + { + let mut g = guards_timed(); + open(&mut g, at, at.saturating_add(len)); + if len != 0 { + g.kernel.push((first, last)); + } + } + crate::descriptor::host::remapped(at, len); + KernelWrite(first, if len == 0 { first } else { last }) +} + +impl Drop for KernelWrite { + fn drop(&mut self) { + if self.0 == self.1 { + return; + } + let mut g = guards(); + if let Some(i) = g.kernel.iter().position(|&r| r == (self.0, self.1)) { + g.kernel.swap_remove(i); + } + } +} + /// Held shared by a read of title memory in place, and alone by the runtime /// while it changes what title memory shows. /// @@ -980,12 +1060,149 @@ static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(()); /// ([`title_memory_remapping`]). pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>); +impl Drop for Remapping { + fn drop(&mut self) { + // The change is done: what is there now may be guarded. + if CHANGING.replace((false, false)).1 { + guards().changing.clear(); + } + CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } +} + +/// How often the runtime began or ended a change of what title memory +/// shows: odd while one is under way. +static CHANGES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +thread_local! { + /// This thread holds [`Remapping`]; and put blocks in + /// [`Guards::changing`]. + static CHANGING: std::cell::Cell<(bool, bool)> = const { std::cell::Cell::new((false, false)) }; +} + +/// For [`again_after_change`]: to be asked before what may fail. +pub(crate) fn changes() -> u64 { + CHANGES.load(std::sync::atomic::Ordering::SeqCst) +} + +/// `f` failed to read or write title memory, at some time since [`changes`] +/// said `since`. If the runtime changed a mapping in that time, the pages +/// may have been away for that moment only ([`MAPPING`]): again, when the +/// change is done. Whether `f` did it. +pub(crate) fn again_after_change(since: u64, mut f: impl FnMut() -> bool) -> bool { + let mut since = since; + for _ in 0..4 { + let now = change_done(); + if now == since { + return false; + } + since = now; + if f() { + return true; + } + } + false +} + +/// [`changes`], when no change is under way (or one has been for a second). +fn change_done() -> u64 { + let mut tries = 0; + let mut started = None; + loop { + let now = changes(); + if now.is_multiple_of(2) { + return now; + } + tries += 1; + if tries < 100 { + std::hint::spin_loop(); + continue; + } + if started.get_or_insert_with(std::time::Instant::now).elapsed().as_secs() >= 1 { + return now; + } + // SAFETY: gives the processor to another thread. + unsafe { windows_sys::Win32::System::Threading::Sleep(u32::from(tries > 200)) }; + } +} + +/// Faults of title threads that met a change of mapping and went on after +/// it ([`came_back`]). +static MET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A title thread's access to `at` (`write`: a write) faulted. Whether it +/// can be made now: if a change of mapping is under way, after it. +/// +/// The console changes one page's mapping and no other's. Here the rest of +/// a view is unmapped and mapped again ([`MAPPING`]), and a title thread that +/// uses a page of it just then, which the title never gave up, faulted +/// ("reserved, never committed", or read-only for the moment between our +/// forgetting a guarded block and its unmapping). It waits here instead. +/// Memory that is not there with no change under way is not waited for. +fn came_back(at: usize, write: bool) -> bool { + let there = || { + if !write { + return readable_view(at); + } + // (A refresh may have guarded the page that came back.) + open(&mut guards(), at, at + 1) || writable(at) + }; + let before = changes(); + if there() || again_after_change(before, there) { + MET.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + false +} + +/// Whether `at` is in a committed page of a view that can be read. +fn readable_view(at: usize) -> bool { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_READONLY, PAGE_READWRITE, VirtualQuery, + }; + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + n != 0 + && info.State == MEM_COMMIT + && info.Type == MEM_MAPPED + && matches!(info.Protect, PAGE_READONLY | PAGE_READWRITE) +} + +/// Title memory that could not be written with what was to go there (what a +/// shader wrote, a title's copy): counted, and said at the 1st, 2nd, 4th, 8th +/// and so on. A page the title unmapped loses nothing by it; a page that is +/// there does. +pub(crate) fn lost(what: &'static str, at: usize, len: usize) { + static LOST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = LOST.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() { + let there = writable(at); + tracing::warn!(n, what, at = format_args!("{at:#x}"), len, there, "title memory not written"); + } +} + + /// The runtime is about to map, unmap or move physical pages of title /// memory: until what it returns is dropped, no read of title memory in /// place is under way and none begins ([`title_memory_reading`]). Taken /// around the whole change, the unmapping and the mapping again. pub fn title_memory_remapping() -> Remapping { - Remapping(MAPPING.write().unwrap_or_else(|e| e.into_inner())) + // For the title's own threads ([`came_back`]). + install(); + let met = MET.load(std::sync::atomic::Ordering::Relaxed); + if met != 0 { + static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if met >= 2 * SAID.load(std::sync::atomic::Ordering::Relaxed) { + SAID.store(met, std::sync::atomic::Ordering::Relaxed); + tracing::info!(met, "accesses of title threads that waited for a change of mapping"); + } + } + let changing = MAPPING.write().unwrap_or_else(|e| e.into_inner()); + CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + CHANGING.set((true, false)); + Remapping(changing) } /// What a read of title memory in place holds ([`title_memory_reading`]). @@ -1025,9 +1242,20 @@ pub fn title_memory_remapped(at: usize, len: usize) { } /// The runtime is about to unmap title memory `[at, at + len)`: it is -/// nothing of ours any more. Its protection goes with it. +/// nothing of ours any more. Its protection goes with it. Until the change +/// is done ([`Remapping`]) no refresh guards what is there: one that did +/// before the unmapping would leave the address guarded, clean and known by +/// its bits ([`PUBLISHED`]) with no view behind it. pub fn title_memory_unmapping(at: usize, len: usize) { let mut g = title_memory_changed(at, len); + if CHANGING.get().0 && len != 0 { + CHANGING.set((true, true)); + let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); + match g.changing.last_mut() { + Some(before) if before.1 == first => before.1 = last, + _ => g.changing.push((first, last)), + } + } let blocks: Vec = g .protected .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) @@ -1040,6 +1268,58 @@ pub fn title_memory_unmapping(at: usize, len: usize) { } } +/// The title is about to free or decommit memory of its own, +/// `[at, at + len)`, or with no length the whole allocation at `at`: what +/// was noted of its blocks (guarded, clean, absent) would be taken for true +/// of the next memory at the address. +pub fn title_memory_freed(at: usize, len: usize) { + let mut g = guards(); + let first = at / BLOCK; + let noted = [&g.protected, &g.absent, &g.foreign].map(|set| set.range(first..).next()); + let Some(noted) = noted.into_iter().flatten().min().copied() else { + return; + }; + let end = if len != 0 { + at.saturating_add(len).div_ceil(BLOCK) + } else { + allocation_end(at, noted * BLOCK).div_ceil(BLOCK) + }; + if noted >= end { + return; + } + let absent: Vec = g.absent.range(first..end).copied().collect(); + for block in absent { + g.absent.remove(&block); + } + let foreign: Vec = g.foreign.range(first..end).copied().collect(); + for block in foreign { + g.foreign.remove(&block); + } + // (Memory that is still a view is not freed by that call, which fails: + // it must not stay read-only.) + open(&mut g, at, end * BLOCK); +} + +/// The end of the allocation at `at`, if `inside` lies in it; else `at`. +fn allocation_end(at: usize, inside: usize) -> usize { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + let ask = |address: usize| { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(address as *const _, &mut info, size_of_val(&info)) }; + (n != 0 && info.AllocationBase as usize == at) + .then(|| (info.BaseAddress as usize).saturating_add(info.RegionSize)) + }; + let mut end = at; + let mut next = ask(inside.max(at)); + while let Some(to) = next { + end = to; + next = ask(to); + } + end +} + /// Tells what keeps track of what title memory shows; the guards, with no /// block of the range known unmapped. fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, Guards> { @@ -1052,10 +1332,14 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, crate::inplace::title_memory_freeing(at, len); let mut g = guards(); let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK); - let absent: Vec = g.absent.range(range).copied().collect(); + let absent: Vec = g.absent.range(range.clone()).copied().collect(); for block in absent { g.absent.remove(&block); } + let foreign: Vec = g.foreign.range(range).copied().collect(); + for block in foreign { + g.foreign.remove(&block); + } g } @@ -1070,6 +1354,7 @@ pub(crate) fn install() { unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 { // SAFETY: the system passes the exception being dispatched. let r = unsafe { &*(*info).ExceptionRecord }; + const READ: usize = 0; const WRITE: usize = 1; // A fault of our own copies (`crate::safecopy`): whatever it is, if // it is not a block we guard, the copy fails and goes on from there. @@ -1085,6 +1370,13 @@ pub(crate) fn install() { { return match ours { Some(exit) => fail(exit), + None if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS + && r.NumberParameters >= 2 + && r.ExceptionInformation[0] == READ + && came_back(r.ExceptionInformation[1], false) => + { + EXCEPTION_CONTINUE_EXECUTION + } None => EXCEPTION_CONTINUE_SEARCH, }; } @@ -1101,8 +1393,11 @@ pub(crate) fn install() { if writable(at) { return EXCEPTION_CONTINUE_EXECUTION; } + // (The runtime wants the guards to end a change.) + drop(g); match ours { Some(exit) => fail(exit), + None if came_back(at, true) => EXCEPTION_CONTINUE_EXECUTION, None => EXCEPTION_CONTINUE_SEARCH, } } @@ -1229,6 +1524,255 @@ mod tests { }; } + /// A placeholder of `blocks` blocks, each its own. + fn placeholder(blocks: usize) -> usize { + use windows_sys::Win32::System::Memory::{ + MEM_PRESERVE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder, split. + unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + blocks * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + for block in 0..blocks - 1 { + assert_ne!( + VirtualFree((p + block * BLOCK) as *mut _, BLOCK, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), + 0 + ); + } + p + } + } + + /// Private memory of `protect` in place of the placeholder of one block. + fn private_at(at: usize, protect: u32) { + use windows_sys::Win32::System::Memory::{MEM_REPLACE_PLACEHOLDER, VirtualAlloc2}; + // SAFETY: our placeholder. + let got = unsafe { + VirtualAlloc2( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + at as *const _, + BLOCK, + MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, + protect, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(got as usize, at); + } + + fn protection(at: usize) -> u32 { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + // SAFETY: plain data the query fills in. + unsafe { + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(at as *const _, &mut info, size_of_val(&info)); + info.Protect + } + } + + /// A refresh between the opening of a kernel read's destination and the + /// read itself leaves it open: the read lands, and is seen. + #[test] + fn a_refresh_leaves_open_what_the_kernel_is_writing() { + use std::io::{Read, Seek, Write}; + use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile}; + // SAFETY: a pagefile section of two blocks, mapped read-write. + let view = unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK) + }; + let at = view.Value as usize; + assert_ne!(at, 0); + let pages = |block: usize| at / PAGE + block..at / PAGE + block + 1; + assert!(writes(at, at + 2 * BLOCK, true).is_some()); + assert!(published(at, at + 2 * BLOCK) || !light()); + let mut file = tempfile::tempfile().unwrap(); + file.write_all(b"from the disk").unwrap(); + file.rewind().unwrap(); + let writing = kernel_writing(at + 100, 13); + // The refresh: the block being written is new to it every time, and + // stays open; the other is as it was. + for _ in 0..2 { + assert_eq!(guard(at, at + 2 * BLOCK), Some(pages(0).collect())); + let (now, found) = writes(at, at + BLOCK, true).expect("a view"); + assert!(found.contains(&(at / PAGE, now))); + assert!(writable(at) && !writable(at + BLOCK)); + assert!(!published(at, at + BLOCK)); + } + // SAFETY: 13 bytes of our view, nothing else refers to them. + let into = unsafe { std::slice::from_raw_parts_mut((at + 100) as *mut u8, 13) }; + assert_eq!(file.read(into).expect("the kernel's write lands"), 13); + assert_eq!(into, b"from the disk"); + drop(writing); + // Seen by the next refresh, and guarded again. + assert_eq!(guard(at, at + 2 * BLOCK), Some(pages(0).collect())); + assert!(!writable(at)); + assert_eq!(guard(at, at + 2 * BLOCK), Some(Vec::new())); + title_memory_unmapping(at, 2 * BLOCK); + // SAFETY: our view. + unsafe { UnmapViewOfFile(view) }; + } + + /// A refresh during a change of mapping guards nothing the runtime has + /// begun to unmap: no note of it stays behind. + #[test] + fn nothing_is_guarded_between_our_forgetting_it_and_its_unmapping() { + use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile}; + // SAFETY: a pagefile section of a block, mapped read-write. + let view = unsafe { + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null()); + assert!(!section.is_null()); + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, BLOCK) + }; + let at = view.Value as usize; + assert_ne!(at, 0); + assert!(writes(at, at + BLOCK, true).is_some()); + let changing = title_memory_remapping(); + title_memory_unmapping(at, BLOCK); + assert!(writes(at, at + BLOCK, true).is_some()); + { + let g = guards(); + assert!(!g.protected.contains(&(at / BLOCK)) && !g.clean.contains(&(at / BLOCK))); + } + assert!(!published(at, at + BLOCK)); + // SAFETY: our view. + unsafe { UnmapViewOfFile(view) }; + drop(changing); + assert!(!guards().left_alone(at / BLOCK)); + } + + /// Memory at an address where blocks were guarded or absent is not + /// taken for them: code stays code, private memory is not guarded. + #[test] + fn other_memory_at_a_guarded_address_keeps_its_protection() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, MapViewOfFile3, PAGE_EXECUTE_READ, + PAGE_EXECUTE_READWRITE, UnmapViewOfFile2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let p = placeholder(3); + // SAFETY: a section's block in place of the first placeholder. + let view = unsafe { + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null()); + assert!(!section.is_null()); + MapViewOfFile3( + section, + GetCurrentProcess(), + p as *const _, + 0, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p); + // One block guarded, two absent. + assert_eq!(guard(p, p + 3 * BLOCK).map(|w| w.len()), Some(3)); + // Not told of what comes: the view goes, code is there; and private + // memory in the holes. + // SAFETY: our view. + assert_ne!(unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }, 0); + private_at(p, PAGE_EXECUTE_READ); + private_at(p + BLOCK, PAGE_READWRITE); + private_at(p + 2 * BLOCK, PAGE_EXECUTE_READWRITE); + let as_made = || { + assert_eq!(protection(p), PAGE_EXECUTE_READ); + assert_eq!(protection(p + BLOCK), PAGE_READWRITE); + assert_eq!(protection(p + 2 * BLOCK), PAGE_EXECUTE_READWRITE); + }; + let holes = [p / PAGE + 1, p / PAGE + 2]; + for _ in 0..2 { + let written = guard(p, p + 3 * BLOCK).expect("as a view"); + assert!(holes.iter().all(|page| written.contains(page)), "copied every time"); + as_made(); + } + writing(p, BLOCK); + as_made(); + title_memory_unmapping(p, 3 * BLOCK); + // SAFETY: our allocations. + unsafe { + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + } + } + + /// Memory the title frees leaves no note of its blocks, whether it names + /// its length or the allocation. + #[test] + fn freed_memory_leaves_no_notes() { + let p = placeholder(3); + let noted = |block: usize| { + let g = guards(); + let block = p / BLOCK + block; + g.protected.contains(&block) || g.clean.contains(&block) || g.absent.contains(&block) + }; + assert!(guard(p, p + 3 * BLOCK).is_some()); + assert!(noted(0) && noted(1) && noted(2)); + // The middle allocation. + title_memory_freed(p + BLOCK, 0); + assert!(noted(0) && !noted(1) && noted(2)); + title_memory_freed(p, BLOCK); + assert!(!noted(0) && noted(2)); + // Nothing noted there: nothing to do, and nothing beside it. + title_memory_freed(p + BLOCK, 0); + assert!(noted(2)); + title_memory_freed(p + 2 * BLOCK, 0); + assert!(!noted(2)); + // SAFETY: our placeholders. + unsafe { + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + } + } + + /// A write between another thread's asking about a range and the second + /// part of a submission's one asking is later than what that thread + /// copied. + #[test] + fn the_rest_of_the_one_asking_has_a_number_of_its_own() { + // SAFETY: a fresh write-watched allocation, freed at the end. + let p = unsafe { + VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + } as usize; + assert_ne!(p, 0); + // One range: `ask_ahead` leaves it. + let ranges = [(p, p + 4 * PAGE)]; + ask_ahead(&ranges); + let (copied, _) = writes(p, p + 4 * PAGE, false).expect("watched"); + // SAFETY: committed pages of ours. + unsafe { ((p + PAGE) as *mut u8).write_volatile(1) }; + ask_rest(&ranges); + let last = journal().written.get(&(p / PAGE + 1)).copied(); + ask_once_end(); + assert!(last.is_some_and(|last| last > copied), "{last:?} is not after {copied}"); + // SAFETY: our allocation. + unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; + } + /// The runtime maps a view and then tells us; a copy's refresh on another /// thread can guard it in between. Told, it is the title's to write: a /// block left read-only and forgotten would be an access violation in @@ -1663,7 +2207,8 @@ mod many_askers_tests { // or past the guard. let word = at + page * PAGE + t * 8; // SAFETY (both): as above. - let reading = (next(3) == 0).then(super::title_memory_reading_now).flatten(); + // (Waited for: other tests hold changes of mapping.) + let reading = (next(3) == 0).then(super::title_memory_reading); let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8)); if let Some(to) = beside { unsafe { (to as *mut u64).write_volatile(2) }; diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 87e635e..384a29a 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -1035,12 +1035,14 @@ fn into_destination( ) -> Result<(), HRESULT> { if request.options & PAGE_DESTINATION == 0 { // Raw reads land through the kernel, which does not fault into the - // GPU side's guard on title buffers; open them first. - victory_gpu::kernel_will_write(request.destination as usize, len); + // GPU side's guard on title buffers; open them first, and until the + // bytes are there. + let writing = victory_gpu::kernel_writing(request.destination as usize, len); // SAFETY: the title's destination holds `destination_size` bytes, at // least `len`, and nothing else writes it until completion. let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::(), len) }; let filled = fill(out).map(drop); + drop(writing); // Again now that the bytes are there: a texture looked at in between // was uploaded without them (`xmem::pages_written`). if super::xmem::stream_notice() { diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index 902c4a9..446263f 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -519,7 +519,7 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi // fail there instead of faulting into its handler; the title's // synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned // destinations and retry a failed `ReadFile` forever. So the destination -// is opened first. +// is opened first, and not guarded again before the call is done. pub extern "system" fn ReadFile( file: *mut c_void, @@ -528,15 +528,36 @@ pub extern "system" fn ReadFile( read: *mut u32, overlapped: *mut c_void, ) -> i32 { - victory_gpu::kernel_will_write(buffer as usize, len as usize); - host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)( + let writing = victory_gpu::kernel_writing(buffer as usize, len as usize); + let done = host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)( file, buffer, len, read, overlapped, - ) + ); + // The call's error is the title's to ask for. + // SAFETY: plain calls. + let error = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + // shortcut: a read that goes on after the call (overlapped) is written + // into pages the kernel has locked by now: it lands all the same, but a + // refresh that guards its blocks before it does will not see it. + if done == 0 && error == windows_sys::Win32::Foundation::ERROR_IO_PENDING { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::info!(len, "ReadFile: a read of the title's goes on after the call")); + } + if done == 0 && error == windows_sys::Win32::Foundation::ERROR_NOACCESS { + static FAILED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = FAILED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::warn!(n, buffer = format_args!("{buffer:p}"), len, "ReadFile: the title's buffer could not be written"); + } + } + drop(writing); + // SAFETY: as above. + unsafe { windows_sys::Win32::Foundation::SetLastError(error) }; + done } /// The host CRT reads large requests straight into the caller's buffer. pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize { - victory_gpu::kernel_will_write(buffer as usize, size.saturating_mul(count)); + let _writing = victory_gpu::kernel_writing(buffer as usize, size.saturating_mul(count)); host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)( buffer, size, count, stream, ) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 36dd2bd..f078dd1 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -1136,11 +1136,24 @@ pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL { moved.into() } +/// The title's own `VirtualFree`. What the GPU side noted of the memory goes +/// first: the address may be other memory's the moment it is free. +extern "system" fn title_virtual_free(address: *mut c_void, size: usize, kind: u32) -> BOOL { + const MEM_COALESCE_PLACEHOLDERS: u32 = 1; + // Splitting and joining placeholders changes nothing they show. + if kind & (MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS) == 0 { + victory_gpu::title_memory_freed(address as usize, size); + } + // SAFETY: the title's own arguments. + unsafe { VirtualFree(address, size, kind) } +} + pub(crate) fn module() -> HleModule { HleModule { name: "xmem", - dlls: &["xmem.dll"], + dlls: &["xmem.dll", "kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-*"], exports: vec![ + crate::HleExport { name: "VirtualFree", address: title_virtual_free as *const () as usize }, hle_export!(XMemAlloc), hle_export!(XMemFree), hle_export!(XMemAllocDefault), @@ -1383,7 +1396,9 @@ mod tests { let stop = stop.clone(); std::thread::spawn(move || { let mut reads = 0u64; - while !stop.load(Ordering::Relaxed) { + // (Once at least: the mapping thread may be done before this + // one's first turn.) + while reads == 0 || !stop.load(Ordering::Relaxed) { let _reading = victory_gpu::title_memory_reading(); // SAFETY: the page is mapped whenever no change of // mapping is under way, and none is while `_reading` @@ -1405,6 +1420,57 @@ mod tests { assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); } + /// A title thread that reads and writes a page of a view while other + /// pages of the view are unmapped and mapped again, as the console lets + /// it: the page was never given up. + #[test] + fn a_title_thread_goes_on_using_the_rest_of_a_view() { + use std::sync::atomic::{AtomicBool, Ordering}; + let pages = allocate(4); + for _ in 0..200 { + // A new reservation each time: the pieces of a view cut up stay + // cut up. + let a = XMemVirtualAlloc( + std::ptr::null_mut(), + 4 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ); + assert!(!a.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 4, pages.as_ptr()), a); + let (first, stop) = (a as usize, AtomicBool::new(false)); + // SAFETY: mapped read-write. + unsafe { (first as *mut u64).write_volatile(0) }; + std::thread::scope(|s| { + let title = s.spawn(|| { + let mut n = 0u64; + // SAFETY (the block): the first page is the title's all + // the time; a fault would end the process. + unsafe { + while !stop.load(Ordering::Relaxed) { + assert_eq!((first as *const u64).read_volatile(), n); + n += 1; + (first as *mut u64).write_volatile(n); + } + } + n + }); + // SAFETY: as above. + while !title.is_finished() && unsafe { (first as *const u64).read_volatile() } < 100 {} + for page in [3, 2, 1] { + let at = a.wrapping_byte_add(page * PAGE); + assert_eq!(XMemMapPhysicalPages(at, 1, std::ptr::null()), at); + assert_eq!(XMemMapPhysicalPages(at, 1, pages[page..].as_ptr()), at); + } + stop.store(true, Ordering::Relaxed); + assert!(title.join().expect("the title's thread never faulted") > 0); + }); + assert_eq!(XMemMapPhysicalPages(a, 4, std::ptr::null()), a); + } + assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); + } + #[test] fn mapping_no_pages_changes_nothing() { let pages = allocate(2);