From 90c59251c383f07be1b2bf92b841e4d57b21b528 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:45:09 -0600 Subject: [PATCH 1/4] Look-first stubs for moves and vector stores (VICTORY_WRITE_SITES); descriptors copied onto themselves are not written (VICTORY_SAME_RECORDS=0: they are); of tracked pages the parts written are taken (VICTORY_TAKE_PARTS=0: pages); waits for the trackers' locks and the heap sync's parts counted Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/copystat.rs | 10 +- crates/victory-gpu/src/descriptor.rs | 50 ++++- crates/victory-gpu/src/titlewrite.rs | 30 ++- crates/victory-gpu/src/titlewrite/decode.rs | 73 +++++-- crates/victory-gpu/src/watch.rs | 124 +++++++++-- crates/victory-loader/src/write_sites.rs | 226 +++++++++++++++++++- 6 files changed, 465 insertions(+), 48 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 65f5a32..3bbb9dd 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -1210,11 +1210,15 @@ pub(crate) fn log(frames: f64) { "guards over several views of a page, since the start: {together} blocks guarded with their other views, \ {written} views opened by a write through another, {mapped} ranges opened because a view of them was mapped" ); - let [copies, blocks, opened, stores, unknown, full, stayed, copied_same] = - [0, 1, 2, 3, 4, 5, 6, 7].map(|n| crate::titlewrite::DONE[n].load(std::sync::atomic::Ordering::Relaxed)); + tracing::info!( + "waits for the write trackers' locks per frame, all threads (number, time): {}", + crate::watch::lock_waits(frames as f64) + ); + let [copies, blocks, opened, stores, unknown, full, stayed, copied_same, records] = + [0, 1, 2, 3, 4, 5, 6, 7, 8].map(|n| crate::titlewrite::DONE[n].load(std::sync::atomic::Ordering::Relaxed)); tracing::info!( "the title's writes beside the guards, since the start: {copies} copies (VICTORY_COPY_BESIDE=1), {blocks} blocks, {opened} opened; \ - {stores} stores (VICTORY_STORE_BESIDE=1), {unknown} not understood, {full} blocks opened for too many; left out for changing nothing: {stayed} stores, {copied_same} parts of copies; \ + {stores} stores (VICTORY_STORE_BESIDE=1), {unknown} not understood, {full} blocks opened for too many; left out for changing nothing: {stayed} stores, {copied_same} parts of copies, {records} copies of descriptors; \ the busiest stores (left out/changed): {}", crate::titlewrite::busiest() ); diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 47f9852..a6e74ce 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -301,6 +301,9 @@ pub(crate) fn sync_heaps() { } let started = std::time::Instant::now(); let (mut pages, mut looked, mut mirrored, mut tabled, mut later) = (0u64, 0u64, 0u64, 0u64, 0u64); + let (mut views, mut bytes) = (0u64, 0u64); + let mut spent = [0u64; 4]; + let since = |at: std::time::Instant| at.elapsed().as_nanos() as u64; let mut page_bytes: Vec = Vec::new(); let mut changed: Vec = Vec::new(); let mut wait: Vec = Vec::new(); @@ -336,7 +339,10 @@ pub(crate) fn sync_heaps() { mirrored += before.len() as u64 - of_tables; // Those of the changed pages, made together at the end. let mut make: Vec = Vec::new(); - for (range_from, range_end) in written.take(start as usize, end as usize) { + let began = std::time::Instant::now(); + let taken = written.take(start as usize, end as usize); + spent[0] += since(began); + for (range_from, range_end) in taken { let mut page = range_from & !(crate::watch::PAGE - 1); while page < range_end { let from = page.max(range_from); @@ -345,8 +351,13 @@ pub(crate) fn sync_heaps() { // copy: a page the title unmaps meanwhile fails the read // where 2,048 reads in place would fault. page_bytes.resize(to - from, 0); - if crate::host::read_into(from as *const u8, &mut page_bytes) { + let began = std::time::Instant::now(); + let there = crate::host::read_into(from as *const u8, &mut page_bytes); + spent[1] += since(began); + if there { pages += 1; + views += u64::from(crate::watch::guarded(from, to)); + bytes += (to - from) as u64; let slots = changed_slots(from, to, start as usize, step, mirrored_count); // A record that straddles the range's ends is left // to the range that holds its first byte. @@ -360,7 +371,9 @@ pub(crate) fn sync_heaps() { // Only the records that are not the ones last seen // there (`HostHeap::copied_changes`). changed.clear(); + let began = std::time::Instant::now(); host.copied_changes(first as u32, &records[..(count * step) as usize], step as usize, &mut changed); + spent[2] += since(began); for &index in &changed { let at = (u64::from(index) - first) as usize * step as usize; let word = |n: usize| { @@ -393,11 +406,13 @@ pub(crate) fn sync_heaps() { page += crate::watch::PAGE; } } + let began = std::time::Instant::now(); crate::land::each_view(make.len().div_ceil(SYNC_AT_A_TIME), &|n| { for &index in make.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() { host.mirror(index, start + u64::from(index) * step, false); } }); + spent[3] += since(began); if !wait.is_empty() { host.copied_wait(frame, std::mem::take(&mut wait)); } @@ -407,6 +422,10 @@ pub(crate) fn sync_heaps() { for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, micros, tabled, later]) { count.fetch_add(n, Relaxed); } + let [taking, reading, comparing, making] = spent; + for (count, n) in SYNC_SPLIT.iter().zip([views, bytes, taking, reading, comparing, making]) { + count.fetch_add(n, Relaxed); + } } /// Records [`sync_heaps`] gives a thread at a time. @@ -422,6 +441,12 @@ const SYNC_AT_A_TIME: usize = 256; #[cfg(windows)] pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 7] = [const { std::sync::atomic::AtomicU64::new(0) }; 7]; +/// The same, of [`SYNCED`]'s pages: those in view memory that was guarded; +/// bytes read; nanoseconds asking what was written, reading it, comparing it +/// with what was last seen, making views. +#[cfg(windows)] +static SYNC_SPLIT: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + /// With the frame line: what [`sync_heaps`] did per frame over `frames`. /// Nothing while no heap page changed. #[cfg(windows)] @@ -436,20 +461,27 @@ pub(crate) fn sync_line(frames: f64) { ); } let [pages, looked, mirrored, micros, tabled, later, waited] = [0, 1, 2, 3, 4, 5, 6].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + let split = [0, 1, 2, 3, 4, 5].map(|i| SYNC_SPLIT[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64); if pages == 0 { return; } tracing::info!( "descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \ {:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.1} new ones of \ - draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for)", + draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for); {:.1} of the pages guarded views, {:.1} MB read; {:.2} ms asking, {:.2} reading, {:.2} comparing, {:.2} making", pages as f64 / frames, looked as f64 / frames, mirrored as f64 / frames, tabled as f64 / frames, later as f64 / frames, micros as f64 / 1000.0 / frames, - waited as f64 / 1000.0 / frames + waited as f64 / 1000.0 / frames, + split[0] / frames, + split[1] / (1 << 20) as f64 / frames, + split[2] / 1e6 / frames, + split[3] / 1e6 / frames, + split[4] / 1e6 / frames, + split[5] / 1e6 / frames ); } @@ -1249,7 +1281,15 @@ pub(crate) extern "system" fn copy_simple(_: This, count: u32, dst: u64, src: u6 let len = u64::from(count) * step; if dst != 0 && src != 0 { // SAFETY: both ranges are descriptor slots the title owns. - unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) }; + #[cfg(windows)] + unsafe { + crate::titlewrite::put(dst as *mut u8, src as *const u8, len as usize) + }; + // SAFETY: as above. + #[cfg(not(windows))] + unsafe { + std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) + }; #[cfg(windows)] for i in 0..u64::from(count) { mirror(dst + i * step); diff --git a/crates/victory-gpu/src/titlewrite.rs b/crates/victory-gpu/src/titlewrite.rs index 1a551c5..946fa88 100644 --- a/crates/victory-gpu/src/titlewrite.rs +++ b/crates/victory-gpu/src/titlewrite.rs @@ -33,8 +33,8 @@ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; /// the guards, blocks they did so in, blocks they opened instead; stores done /// beside the guards, faulting stores not understood, and blocks opened /// because too many came; stores and parts of copies that left the memory as -/// it was, and were not made. -pub(crate) static DONE: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; +/// it was, and were not made; descriptors copied onto themselves. +pub(crate) static DONE: [AtomicU64; 9] = [const { AtomicU64::new(0) }; 9]; fn add(what: usize) { DONE[what].fetch_add(1, Relaxed); @@ -172,6 +172,28 @@ unsafe extern "system-unwind" fn set(to: *mut u8, byte: i32, n: usize) -> *mut u to } +/// Bytes of the title's that we put into its memory for it (a descriptor it +/// has copied): as a copy of its own, but what is there already is never +/// written (`VICTORY_SAME_RECORDS=0`: always). +/// +/// # Safety +/// `[from, from + n)` and `[to, to + n)` are the title's. +pub(crate) unsafe fn put(to: *mut u8, from: *const u8, n: usize) { + // SAFETY: by the caller. + unsafe { + let there = || std::slice::from_raw_parts(to.cast_const(), n) == std::slice::from_raw_parts(from, n); + if crate::toggled!("VICTORY_SAME_RECORDS") && there() { + add(8); + return; + } + if n == 0 || !copies_on() || !crate::watch::guards_any(to as usize, n) || overlap(to as usize, from as usize, n) { + std::ptr::copy(from, to, n); + return; + } + in_pieces(to as usize, n, |_, _, _| false, |at, offset, len| std::ptr::copy_nonoverlapping(from.add(offset), at as *mut u8, len)); + } +} + /// Whether the two ranges meet, if only in a block (of which only one might /// be written at another address). fn overlap(to: usize, from: usize, n: usize) -> bool { @@ -257,9 +279,9 @@ fn learn(rip: usize, same: bool, can_look: bool) { return; }; use std::io::Write; - let line = format!("{image} {offset:x} or\n"); + let line = format!("{image} {offset:x}\n"); let known = std::fs::read_to_string(&file).unwrap_or_default(); - if known.lines().any(|l| l == line.trim_end()) { + if known.lines().any(|l| l.starts_with(line.trim_end())) { return; } if let Ok(mut file) = std::fs::OpenOptions::new().append(true).create(true).open(&file) { diff --git a/crates/victory-gpu/src/titlewrite/decode.rs b/crates/victory-gpu/src/titlewrite/decode.rs index e83f5b6..11343c9 100644 --- a/crates/victory-gpu/src/titlewrite/decode.rs +++ b/crates/victory-gpu/src/titlewrite/decode.rs @@ -1,7 +1,7 @@ //! The stores of x86-64 code that [`super::store`] does in the title's place: //! moves from a register or a constant, arithmetic of those with memory -//! (locked or not), exchanges, and the 4, 8 and 16 byte stores of the vector -//! registers. Everything else is `None`. +//! (locked or not), exchanges, and the 4, 8, 16 and 32 byte stores of the +//! vector registers. Everything else is `None`. use std::sync::atomic::{AtomicU8, AtomicU16, AtomicU32, AtomicU64, Ordering::SeqCst}; use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT; @@ -18,7 +18,7 @@ enum Alu { #[derive(Clone, Copy, PartialEq, Debug)] enum Op { /// These bytes (the low `size` of them). - Put([u8; 16]), + Put([u8; 32]), /// With a value; `keeps` carry (`inc`, `dec`). Alu { alu: Alu, with: u64, keeps: bool }, /// With a register, which gets what was there. @@ -116,6 +116,27 @@ fn mask(size: usize) -> u64 { if size >= 8 { u64::MAX } else { (1 << (size * 8)) - 1 } } +/// The upper half of vector register `reg`, where the context has it; nothing +/// in it if the thread used none. +fn upper(c: &CONTEXT, reg: usize) -> Option<[u8; 16]> { + use windows_sys::Win32::System::Diagnostics::Debug::{GetXStateFeaturesMask, LocateXStateFeature}; + const AVX: u32 = 2; + let mut mask = 0; + // SAFETY: a context as the system passes it to a handler (the calls + // change nothing of it). + unsafe { + if GetXStateFeaturesMask(c, &mut mask) == 0 { + return None; + } + if mask >> AVX & 1 == 0 { + return Some([0; 16]); + } + let mut len = 0; + let at = LocateXStateFeature(c, AVX, &mut len) as *const [u8; 16]; + (!at.is_null() && len as usize >= 16 * 16).then(|| at.add(reg).read_unaligned()) + } +} + /// The store at the start of `code`, which the registers are those of. pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { let mut at = 0; @@ -124,7 +145,7 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { at += 1; byte }; - let (mut locked, mut narrow, mut repeat) = (false, false, 0u8); + let (mut locked, mut narrow, mut repeat, mut long) = (false, false, 0u8, false); let mut byte = next()?; loop { match byte { @@ -160,10 +181,10 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { _ => None, }; if let Some(b) = vector { - // (No 32 byte ones: they fill memory.) - if b & 4 != 0 || narrow || repeat != 0 || locked { + if narrow || repeat != 0 || locked { return None; } + long = b & 4 != 0; // (A store has no third register.) if b >> 3 & 15 != 15 { return None; @@ -223,7 +244,7 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { 4 }; let put = |value: u64| { - let mut bytes = [0; 16]; + let mut bytes = [0; 32]; bytes[..8].copy_from_slice(&value.to_le_bytes()); Op::Put(bytes) }; @@ -231,9 +252,9 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { let vector_bytes = || { // SAFETY: the registers, whichever way they are named. let x = unsafe { &c.Anonymous.FltSave }.XmmRegisters[reg]; - let mut bytes = [0; 16]; + let mut bytes = [0; 32]; bytes[..8].copy_from_slice(&x.Low.to_le_bytes()); - bytes[8..].copy_from_slice(&x.High.to_le_bytes()); + bytes[8..16].copy_from_slice(&x.High.to_le_bytes()); bytes }; let alu_of = |kind: u8| match kind { @@ -244,14 +265,21 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { 6 => Some(Alu::Xor), _ => None, }; - let (op, size) = if two { + let (op, size) = if long { + if !matches!((byte, narrow, repeat), (0x11 | 0x29, _, 0) | (0x7f, true, 0) | (0x7f, false, 0xf3) | (0xe7, true, 0)) { + return None; + } + let mut bytes = vector_bytes(); + bytes[16..].copy_from_slice(&upper(c, reg)?); + (Op::Put(bytes), 32) + } else if two { match (byte, narrow, repeat) { (0x11, _, 0) | (0x29, _, 0) | (0x7f, true, 0) | (0x7f, false, 0xf3) | (0xe7, true, 0) => (Op::Put(vector_bytes()), 16), (0x11, false, 0xf3) => (Op::Put(vector_bytes()), 4), (0x11, false, 0xf2) | (0x13, _, 0) | (0xd6, true, 0) => (Op::Put(vector_bytes()), 8), (0x17, _, 0) => { let mut bytes = vector_bytes(); - bytes.copy_within(8.., 0); + bytes.copy_within(8..16, 0); (Op::Put(bytes), 8) } (0x7e, true, 0) => (Op::Put(vector_bytes()), if wide { 8 } else { 4 }), @@ -393,7 +421,7 @@ impl Store { return None; } let mut there = [0u8; 32]; - // SAFETY: by the caller. + // SAFETY: by the caller (32 bytes at the most). unsafe { std::ptr::copy_nonoverlapping(self.at as *const u8, there.as_mut_ptr(), self.size) }; match self.op { Op::Put(bytes) => Some((there[..self.size] == bytes[..self.size], c.EFlags)), @@ -406,12 +434,18 @@ impl Store { } } - /// Whether the loader can make it look before it writes - /// (`victory_loader::write_sites`): an `or` of a byte with a constant, of - /// the five bytes a jump needs. + /// Whether the loader may make it look before it writes + /// (`victory_loader::write_sites`, which looks itself): an `or` of a byte + /// with a constant, a move of 4 bytes or more; of the five bytes a jump + /// needs. pub(super) fn can_look(&self, code: &[u8]) -> bool { let at = usize::from(code[0] & 0xf0 == 0x40); - self.len >= 5 && code[at] == 0x80 && matches!(self.op, Op::Alu { alu: Alu::Or, .. }) + self.len >= 5 + && match self.op { + Op::Alu { alu: Alu::Or, .. } => code[at] == 0x80, + Op::Put(_) => matches!(code[0], 0xc4 | 0xc5) && self.size >= 16 || matches!(code[at], 0x89 | 0xc7), + _ => false, + } } /// Does it, with `to` for the address, and gives the registers what the @@ -428,7 +462,7 @@ impl Store { // As one, for those the processor stores as one. // SAFETY (all): by the caller, aligned where it must be. unsafe { - let low = u64::from_le_bytes(bytes[..8].try_into().expect("eight bytes")); + let low = u64::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]]); match size { 1 => (to as *mut u8).write_volatile(bytes[0]), 2 if to.is_multiple_of(2) => (to as *mut u16).write_volatile(low as u16), @@ -526,9 +560,8 @@ mod tests { assert_eq!(decoded(&[0x0f, 0x13, 0x00]), Some((0, 8, 3))); assert_eq!(decoded(&[0xc5, 0xf9, 0xd6, 0x00]), Some((0, 8, 4))); assert_eq!(decoded(&[0x66, 0x0f, 0x7e, 0x00]), Some((0, 4, 4))); - // Not stores of these: a 32 byte one, a load, a register's, a string - // instruction, a thread's own memory, a compare, adc. - assert_eq!(decoded(&[0xc5, 0xfc, 0x11, 0x04, 0x31]), None); + // Not stores of these: a load, a register's, a string instruction, a + // thread's own memory, a compare, adc. assert_eq!(decoded(&[0x48, 0x8b, 0x13]), None); assert_eq!(decoded(&[0x48, 0x89, 0xd3]), None); assert_eq!(decoded(&[0xf3, 0xa4]), None); diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 62fb034..d08825a 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -151,11 +151,48 @@ static JOURNAL: RwLock = RwLock::new(Journal { }); fn journal() -> std::sync::RwLockReadGuard<'static, Journal> { - JOURNAL.read().unwrap_or_else(|e| e.into_inner()) + if let Ok(j) = JOURNAL.try_read() { + return j; + } + waited(1, || JOURNAL.read().unwrap_or_else(|e| e.into_inner())) } fn journal_mut() -> std::sync::RwLockWriteGuard<'static, Journal> { - JOURNAL.write().unwrap_or_else(|e| e.into_inner()) + if let Ok(j) = JOURNAL.try_write() { + return j; + } + waited(2, || JOURNAL.write().unwrap_or_else(|e| e.into_inner())) +} + +/// Since the last line: waits and nanoseconds of waiting, of all threads, for +/// the ranges held ([`ASKING`]), the journal to read it, the journal to note +/// in it, and the guards (faults of the title's among them). +#[cfg(feature = "diagnostics")] +static WAITS: [[std::sync::atomic::AtomicU64; 2]; 4] = [const { [const { std::sync::atomic::AtomicU64::new(0) }; 2] }; 4]; + +#[cfg(feature = "diagnostics")] +fn waited(what: usize, f: impl FnOnce() -> T) -> T { + use std::sync::atomic::Ordering::Relaxed; + let began = std::time::Instant::now(); + let got = f(); + WAITS[what][0].fetch_add(1, Relaxed); + WAITS[what][1].fetch_add(began.elapsed().as_nanos() as u64, Relaxed); + got +} + +#[cfg(not(feature = "diagnostics"))] +fn waited(_: usize, f: impl FnOnce() -> T) -> T { + f() +} + +/// [`WAITS`], taken, for the log: per frame. +#[cfg(feature = "diagnostics")] +pub(crate) fn lock_waits(frames: f64) -> String { + let of = |what: usize| { + let [n, ns] = [0, 1].map(|i| WAITS[what][i].swap(0, std::sync::atomic::Ordering::Relaxed)); + format!("{:.0} {:.2} ms", n as f64 / frames, ns as f64 / 1e6 / frames) + }; + format!("ranges held {}, journal read {}, journal noted in {}, guards {}", of(0), of(1), of(2), of(3)) } /// The page ranges some thread is asking about: asking forgets what it @@ -170,8 +207,14 @@ struct Asking(usize, usize); impl Asking { fn hold(first: usize, last: usize) -> Asking { let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner()); - while held.iter().any(|&(a, b)| a < last && first < b) { - held = ASKING.1.wait(held).unwrap_or_else(|e| e.into_inner()); + if held.iter().any(|&(a, b)| a < last && first < b) { + held = waited(0, || { + let mut held = held; + while held.iter().any(|&(a, b)| a < last && first < b) { + held = ASKING.1.wait(held).unwrap_or_else(|e| e.into_inner()); + } + held + }); } held.push((first, last)); Asking(first, last) @@ -725,13 +768,10 @@ impl Tracked { return Vec::new(); }; let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner()); - let mut ranges: Vec<(usize, usize)> = Vec::new(); + let mut new: Vec<(usize, u64)> = Vec::new(); for (page, write) in pages { - if seen.get(&page).is_some_and(|&last| last >= write) { - continue; - } - let (start, end) = ((page * PAGE).max(from), ((page + 1) * PAGE).min(to)); - if start >= end { + let last = seen.get(&page).copied(); + if last.is_some_and(|last| last >= write) || (page * PAGE).max(from) >= ((page + 1) * PAGE).min(to) { continue; } // Keep partial pages dirty: the caller has not taken the rest. @@ -740,9 +780,26 @@ impl Tracked { { seen.insert(page, write); } - match ranges.last_mut() { - Some((_, last)) if *last == start => *last = end, - _ => ranges.push((start, end)), + new.push((page, last.unwrap_or(0))); + } + // Of a page taken before, the parts written since, where they are + // known (`VICTORY_TAKE_PARTS=0`: the page). + let parts = if crate::toggled!("VICTORY_TAKE_PARTS") { parts_written(&new) } else { vec![WHOLE; new.len()] }; + let mut ranges: Vec<(usize, usize)> = Vec::new(); + for (&(page, last), &parts) in new.iter().zip(&parts) { + let mut parts = if last == 0 { WHOLE } else { parts }; + while parts != 0 { + let first = parts.trailing_zeros() as usize; + let past = first + (!(parts >> first)).trailing_zeros() as usize; + parts &= if past >= PARTS { 0 } else { u16::MAX << past }; + let (start, end) = ((page * PAGE + first * KERNEL_PAGE).max(from), (page * PAGE + past.min(PARTS) * KERNEL_PAGE).min(to)); + if start >= end { + continue; + } + match ranges.last_mut() { + Some((_, last)) if *last == start => *last = end, + _ => ranges.push((start, end)), + } } } ranges @@ -1365,7 +1422,10 @@ static GUARDS: Mutex = Mutex::new(Guards { }); fn guards() -> std::sync::MutexGuard<'static, Guards> { - GUARDS.lock().unwrap_or_else(|e| e.into_inner()) + if let Ok(g) = GUARDS.try_lock() { + return g; + } + waited(3, || GUARDS.lock().unwrap_or_else(|e| e.into_inner())) } /// The 4 KiB pages of title memory that what shaders wrote was put into, @@ -3553,6 +3613,42 @@ mod tests { crate::title_memory_section_gone(section); } + /// Of a page taken before, what is taken again is the kernel's pages + /// written since; where they are not known, all of it. + #[test] + fn what_is_taken_again_is_what_was_written() { + // 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); + let write = |at: usize| { + // SAFETY: committed pages of ours. + unsafe { ((p + at) as *mut u8).write_volatile(1) } + }; + let tracked = track(p, 4 * PAGE, false).expect("watched"); + write(5); + write(PAGE + 5000); + assert_eq!(tracked.take(p, p + 4 * PAGE), [(p, p + 2 * PAGE)], "never taken"); + assert!(tracked.take(p, p + 4 * PAGE).is_empty()); + write(PAGE + 5000); + write(PAGE + 8192); + write(PAGE + 65535); + write(2 * PAGE); + assert_eq!( + tracked.take(p, p + 4 * PAGE), + [(p + PAGE + 4096, p + PAGE + 3 * 4096), (p + 2 * PAGE - 4096, p + 3 * PAGE)], + "page 2 was never taken" + ); + write(2 * PAGE + 70); + // Two askings' writes are in what is taken after both. + assert!(writes(p, p + 4 * PAGE, false).is_some()); + write(2 * PAGE + 9000); + assert_eq!(tracked.take(p, p + 4 * PAGE), [(p + 2 * PAGE, p + 2 * PAGE + 4096), (p + 2 * PAGE + 8192, p + 2 * PAGE + 12288)]); + // SAFETY: our allocation. + unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; + } + /// The set of blocks against another of the same. #[test] fn blocks_are_a_set() { diff --git a/crates/victory-loader/src/write_sites.rs b/crates/victory-loader/src/write_sites.rs index 11f2d97..f1167e3 100644 --- a/crates/victory-loader/src/write_sites.rs +++ b/crates/victory-loader/src/write_sites.rs @@ -1,5 +1,6 @@ -//! Places in the title's code that set a bit of a byte which is nearly always set already, changed -//! at load to look first (`VICTORY_WRITE_SITES=`; off without it). +//! Places in the title's code that write what is nearly always there already, changed at load to +//! look first (`VICTORY_WRITE_SITES=`; off without it): flags that are set, registers and +//! constants moved to memory, 16 and 32 bytes of the vector registers. //! //! The title's threads raise flags in their objects at every use ("drawn this frame"): `or byte //! [object+n], bit`. The objects lie in memory that copies for the card are kept of, and each such @@ -52,8 +53,141 @@ fn or_byte(code: &[u8]) -> Option<(usize, u8, u8, &[u8], u8)> { Some((end + 1, rex, modrm, &code[rest..end], constant)) } +/// How many bytes behind a ModRM byte name an address, `None` for a register, for the instruction +/// pointer's neighbourhood, the stack (whose pointer is another in our code) and a plain address. +/// `b`: the prefix's bit for the base. +fn address(code: &[u8], modrm: u8, b: bool) -> Option { + let (mode, rm) = (modrm >> 6, modrm & 7); + if mode == 3 || mode == 0 && rm == 5 { + return None; + } + let mut len = 0; + if rm == 4 { + let sib = *code.first()?; + if sib & 7 == 4 && !b || sib & 7 == 5 && mode == 0 { + return None; + } + len = 1; + } + len += match mode { + 1 => 1, + 2 => 4, + _ => 0, + }; + Some(len) +} + +/// The end of a stub that has nothing in rcx if the write is left out, and the title's rcx on the +/// stack: the write (`code[..len]`, at `at`) or not, and back. `wide`: all of rcx counts. +fn write_or_not(out: &mut Vec, stub: usize, code: &[u8], at: usize, len: usize, wide: bool) -> Option<()> { + if !wide { + out.push(0x67); + } + out.extend([0xe3, u8::try_from(1 + len + 5).ok()?]); // jrcxz (jecxz) past the write + out.push(0x59); // pop rcx + out.extend(&code[..len]); + out.extend(crate::console_insn::jump(stub + out.len(), at + len)?); + out.push(0x59); + out.extend(crate::console_insn::jump(stub + out.len(), at + len)?); + Some(()) +} + +/// [`stub`] for a vector register's store. No flag is touched. +fn vector_stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { + let (reg_high, xb, third, op_at) = match *code.first()? { + 0xc5 => { + let b = *code.get(1)?; + (b & 0x80 == 0, 0x60, b, 2) + } + 0xc4 => { + let b = *code.get(1)?; + if b & 0x1f != 1 { + return None; + } + (b & 0x80 == 0, b & 0x60, *code.get(2)?, 3) + } + _ => return None, + }; + let (op, modrm) = (*code.get(op_at)?, *code.get(op_at + 1)?); + if !matches!((op, third & 3), (0x11 | 0x29, 0 | 1) | (0x7f, 1 | 2)) || third >> 3 & 15 != 15 { + return None; + } + let long = third & 4; + if !std::is_x86_feature_detected!("avx2") { + return None; + } + let rest = address(code.get(op_at + 2..)?, modrm, xb & 0x20 == 0)?; + let len = op_at + 2 + rest; + if len < 5 { + return None; + } + let reg = modrm >> 3 & 7 | if reg_high { 8 } else { 0 }; + let spare = if reg == 1 { 2u8 } else { 1 }; + let mut out = vec![0x51]; // push rcx + out.extend([0x48, 0x8d, 0x64, 0x24, 0xe0]); // lea rsp, [rsp-32] + out.extend([0xc5, 0xfe, 0x7f, spare << 3 | 4, 0x24]); // vmovdqu [rsp], spare (32 bytes) + // vpcmpeqb spare, reg, [m] + out.extend([0xc4, 0x80 | xb | 1, (!reg & 15) << 3 | long | 1, 0x74, modrm & 0xc7 | spare << 3]); + out.extend(&code[op_at + 2..len]); + out.extend([0xc5, 0xf9 | long, 0xd7, 0xc8 | spare]); // vpmovmskb ecx, spare + out.extend([0xc5, 0xfe, 0x6f, spare << 3 | 4, 0x24]); // vmovdqu spare, [rsp] + out.extend([0x48, 0x8d, 0x64, 0x24, 0x20]); // lea rsp, [rsp+32] + out.extend([0xf7, 0xd1]); // not ecx + if long == 0 { + out.extend([0x0f, 0xb7, 0xc9]); // movzx ecx, cx + } + write_or_not(&mut out, stub, code, at, len, false)?; + Some((len, out)) +} + +/// [`stub`] for a `mov` of a register or a constant, 4 or 8 bytes. No flag is touched. +fn move_stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { + let mut at_op = 0; + let mut rex = 0x40; + if code.first()? & 0xf0 == 0x40 { + rex = code[0]; + at_op = 1; + } + let (op, modrm) = (*code.get(at_op)?, *code.get(at_op + 1)?); + let wide = rex & 8 != 0; + let reg = modrm >> 3 & 7 | (rex & 4) << 1; + let rest = address(code.get(at_op + 2..)?, modrm, rex & 1 != 0)?; + let end = at_op + 2 + rest; + let (len, constant) = match op { + 0x89 if reg != 1 && reg != 4 => (end, None), + 0xc7 if reg & 7 == 0 => { + let bytes = code.get(end..end + 4)?.try_into().ok()?; + (end + 4, Some(i32::from_le_bytes(bytes).checked_add(1)?)) + } + _ => return None, + }; + if len < 5 { + return None; + } + let mut out = vec![0x51]; // push rcx + out.extend([rex & 0x4b, 0x8b, modrm & 0xc7 | 1 << 3]); // mov rcx, [m] + out.extend(&code[at_op + 2..end]); + let w = 0x40 | rex & 8; + out.extend([w, 0xf7, 0xd1]); // not rcx + match constant { + Some(next) => { + out.extend([w, 0x8d, 0x89]); // lea rcx, [rcx+constant+1] + out.extend(next.to_le_bytes()); + } + // lea rcx, [rcx+reg+1] + None => out.extend([w | (reg & 8) >> 2, 0x8d, 0x4c, (reg & 7) << 3 | 1, 1]), + } + write_or_not(&mut out, stub, code, at, len, wide)?; + Some((len, out)) +} + /// The code at `stub` for the instruction at `at` (`code` from there). fn stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { + vector_stub(code, at, stub).or_else(|| move_stub(code, at, stub)).or_else(|| or_stub(code, at, stub)) +} + +/// [`stub`] for the `or` of a byte with a constant. +fn or_stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { let (len, rex, modrm, rest, constant) = or_byte(code)?; if len < 5 { return None; @@ -232,6 +366,94 @@ mod tests { } } + /// Memory a vector store may ask to lie on its boundary. + #[repr(C, align(64))] + #[derive(Clone, Copy)] + struct Memory([u8; 0x80]); + + /// Moves of registers and constants, and vector stores, in code of a test's: changed, they + /// store what they did, leave registers and flags, and write nothing that is there already. + #[test] + fn changed_moves_and_vector_stores_do_what_they_did() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READONLY, PAGE_READWRITE, VirtualAlloc, VirtualProtect, + }; + // Each stores at r9+40h (r10 is 0): rdx, r13 or a vector register 0, 1, 9. + let stores: &[(&[u8], usize)] = &[ + (&[0x49, 0x89, 0x51, 0x40], 0), // (four bytes: left alone) + (&[0x4b, 0x89, 0x54, 0xd1, 0x40], 8), // mov [r9+r10*8+40h], rdx + (&[0x43, 0x89, 0x54, 0xd1, 0x40], 4), // mov [r9+r10*8+40h], edx + (&[0x4d, 0x89, 0xa9, 0x40, 0, 0, 0], 8), // mov [r9+40h], r13 + (&[0x45, 0x89, 0xa9, 0x40, 0, 0, 0], 4), // mov [r9+40h], r13d + (&[0x41, 0xc7, 0x41, 0x40, 0x78, 0x56, 0x34, 0x92], 4), // mov dword [r9+40h], 92345678h + (&[0x49, 0xc7, 0x41, 0x40, 0x78, 0x56, 0x34, 0x92], 8), // mov qword [r9+40h], the same + (&[0xc4, 0xc1, 0x7a, 0x7f, 0x41, 0x40], 16), // vmovdqu [r9+40h], xmm0 + (&[0xc4, 0xc1, 0x7a, 0x7f, 0x49, 0x40], 16), // vmovdqu [r9+40h], xmm1 + (&[0xc4, 0x41, 0x78, 0x29, 0x49, 0x40], 16), // vmovaps [r9+40h], xmm9 + (&[0xc4, 0x81, 0x78, 0x11, 0x44, 0xd1, 0x40], 16), // vmovups [r9+r10*8+40h], xmm0 + (&[0xc4, 0xc1, 0x7c, 0x11, 0x41, 0x40], 32), // vmovups [r9+40h], ymm0 + (&[0xc4, 0xc1, 0x7e, 0x7f, 0x49, 0x40], 32), // vmovdqu [r9+40h], ymm1 + ]; + type F = unsafe extern "system" fn(*mut u8, u64, *mut u8); + for &(store, size) in stores { + let mut code = vec![0x41, 0x55, 0x49, 0x89, 0xc9, 0x4d, 0x31, 0xd2, 0x49, 0x89, 0xd5]; // push r13 ; r9 = rcx ; r10 = 0 ; r13 = rdx + code.extend([0x48, 0xc7, 0xc1, 0x34, 0x12, 0, 0]); // mov rcx, 1234h + code.extend([0x48, 0x83, 0xec, 0x40, 0xc5, 0x7a, 0x7f, 0x0c, 0x24]); // sub rsp, 40h ; xmm9 kept + code.extend([0xc4, 0xc1, 0x7e, 0x6f, 0x00]); // vmovdqu ymm0, [r8] + code.extend([0xc4, 0xc1, 0x7e, 0x6f, 0x48, 0x20]); // vmovdqu ymm1, [r8+32] + code.extend([0xc4, 0x41, 0x7a, 0x6f, 0x48, 0x10]); // vmovdqu xmm9, [r8+16] + code.extend([0x48, 0x39, 0xc0]); // cmp rax, rax + let at = code.len(); + code.extend(store); + code.extend([0x9c, 0x41, 0x5b]); // pushfq ; pop r11 + code.extend([0xc5, 0xfe, 0x7f, 0x4c, 0x24, 0x10]); // vmovdqu [rsp+10h], ymm1 + code.extend([0x48, 0x8b, 0x44, 0x24, 0x18, 0x48, 0x03, 0x44, 0x24, 0x28]); // rax = two of its parts + code.extend([0xc5, 0x7a, 0x6f, 0x0c, 0x24, 0x48, 0x83, 0xc4, 0x40, 0x41, 0x5d]); // xmm9 back ; rsp ; pop r13 + // Flags, rcx and rax behind the source ; vzeroupper ; ret + code.extend([0x4d, 0x89, 0x58, 0x40, 0x49, 0x89, 0x48, 0x48, 0x49, 0x89, 0x40, 0x50, 0xc5, 0xf8, 0x77, 0xc3]); + // SAFETY: fresh memory for code, twice, one of them changed before it runs; data of ours. + unsafe { + let place = VirtualAlloc(std::ptr::null(), 0x10000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize; + assert_ne!(place, 0); + let second = place + 0x2000; + std::ptr::copy_nonoverlapping(code.as_ptr(), place as *mut u8, code.len()); + std::ptr::copy_nonoverlapping(code.as_ptr(), second as *mut u8, code.len()); + assert_eq!(apply("t.dll", second, 0x2000, &format!("t.dll {at:x}")), usize::from(size != 0), "{store:x?}"); + if size == 0 { + continue; + } + let (plain, changed): (F, F) = (std::mem::transmute(place), std::mem::transmute(second)); + let data = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + for seed in 0..200u64 { + let value = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15); + let mut source = [[0u8; 0x60]; 2]; + for (k, byte) in source[0][..0x40].iter_mut().enumerate() { + *byte = (value >> (k % 8 * 8)) as u8 ^ k as u8; + } + source[1] = source[0]; + let was = Memory(std::array::from_fn(|k| (seed as usize * 7 + k) as u8)); + let mut memory = [was; 2]; + plain(memory[0].0.as_mut_ptr(), value, source[0].as_mut_ptr()); + changed(memory[1].0.as_mut_ptr(), value, source[1].as_mut_ptr()); + assert!(memory[0].0 == memory[1].0, "{store:x?}"); + assert!(memory[0].0[..0x40] == was.0[..0x40] && memory[0].0[0x40 + size..] == was.0[0x40 + size..]); + assert_eq!(source[0], source[1], "{store:x?}: registers and flags"); + // One bit different; and nothing different, in read-only memory. + let mut off = memory[0]; + off.0[0x40 + seed as usize % size] ^= 1 << (seed % 8); + changed(off.0.as_mut_ptr(), value, source[1].as_mut_ptr()); + assert!(off.0 == memory[0].0, "{store:x?}"); + std::ptr::copy_nonoverlapping(memory[0].0.as_ptr(), data, 0x80); + let mut old = 0; + VirtualProtect(data.cast(), 4096, PAGE_READONLY, &mut old); + changed(data, value, source[1].as_mut_ptr()); + assert_eq!(source[0], source[1], "{store:x?}: registers and flags, nothing written"); + VirtualProtect(data.cast(), 4096, PAGE_READWRITE, &mut old); + } + } + } + } + /// A byte that would not change is not written. #[test] fn a_byte_that_stays_is_not_written() { From 7fdcfd885bdf82df3cf1fc2246ab718515ba4c00 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:46:47 -0600 Subject: [PATCH 2/4] Test of parts taken: other tests' notes at the address Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index d08825a..a120b25 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -3627,9 +3627,9 @@ mod tests { unsafe { ((p + at) as *mut u8).write_volatile(1) } }; let tracked = track(p, 4 * PAGE, false).expect("watched"); - write(5); - write(PAGE + 5000); - assert_eq!(tracked.take(p, p + 4 * PAGE), [(p, p + 2 * PAGE)], "never taken"); + // (Other tests' memory was here.) + (0..4).for_each(|page| write(page * PAGE + 5)); + assert_eq!(tracked.take(p, p + 4 * PAGE), [(p, p + 4 * PAGE)], "never taken"); assert!(tracked.take(p, p + 4 * PAGE).is_empty()); write(PAGE + 5000); write(PAGE + 8192); @@ -3637,8 +3637,7 @@ mod tests { write(2 * PAGE); assert_eq!( tracked.take(p, p + 4 * PAGE), - [(p + PAGE + 4096, p + PAGE + 3 * 4096), (p + 2 * PAGE - 4096, p + 3 * PAGE)], - "page 2 was never taken" + [(p + PAGE + 4096, p + PAGE + 3 * 4096), (p + 2 * PAGE - 4096, p + 2 * PAGE + 4096)] ); write(2 * PAGE + 70); // Two askings' writes are in what is taken after both. From d8acf26bf85d1325f2133ae0a9f1f72dd8535de2 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:24:11 -0600 Subject: [PATCH 3/4] Views mapped beside guarded ones: all views of the page are opened together, under the lock A page shown at several addresses, and one more view of it being mapped: the views that were to be opened were looked for before the lock was taken, so one made clean in between stayed clean with a writable view beside it (a write of the title's through that one was not told until its block's next told write), and they were opened one range after another, so for some microseconds one was writable while others were still known by their bits (told one asking late). Both are older than the faults' work; VICTORY_OPEN_ONE_VIEW made the first common. Also: what is known by its bits is not where bytes were just put in beside the guard (VICTORY_COPY_BESIDE, VICTORY_STORE_BESIDE). The test of writes through other views failed in 6 of 200 runs, then 4 of 380 with the first mended, 0 of 603 (four tests each) with both. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 48 ++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index a120b25..81d4213 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -1177,7 +1177,11 @@ pub(crate) fn guarded(start: usize, end: usize) -> bool { /// Whether nothing of `[start, end)` can have been written since an asking /// noted it in the journal ([`PUBLISHED`]). fn published(start: usize, end: usize) -> bool { - light() && PUBLISHED.all(start / BLOCK, end.div_ceil(BLOCK)) + let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); + // (In this order: who puts something in beside a guard sets the one bit, + // then clears the other, which an asking that is publishing the block may + // just be setting.) + light() && PUBLISHED.all(first, last) && !BESIDE.any(first, last) } /// Since the last frame line: what asking about title memory was. Kernel @@ -1544,7 +1548,7 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, /// Whether every write of the title's to 64 KiB block `block` so far is in /// the journal ([`PUBLISHED`]). pub(crate) fn block_published(block: usize) -> bool { - light() && PUBLISHED.all(block, block + 1) + published(block * BLOCK, (block + 1) * BLOCK) } /// Whether shaders' writes went into a page of `[at, at + len)` in the last @@ -2126,20 +2130,22 @@ pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) { if !view_guard() { return; } - let mut ranges = crate::inplace::views_of_section(section, offset, len); + let ranges = crate::inplace::views_of_section(section, offset, len); // (A block is noted in `PROTECTED` ahead of the look at its page's views // that did not find this one yet.) - ranges.retain(|&(at, n)| PROTECTED.any(at / BLOCK, (at + n).div_ceil(BLOCK))); - if ranges.is_empty() { + if !ranges.iter().any(|&(at, n)| PROTECTED.any(at / BLOCK, (at + n).div_ceil(BLOCK))) { return; } + // All of them, once one is guarded: another may have been made clean + // since that look, relying on those that are opened here. And all + // together: none may be writable while another is clean (who asks about + // that one by its bits takes no lock). let mut g = guards(); - for &(at, n) in &ranges { - let blocks: Vec = g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).collect(); - #[cfg(feature = "diagnostics")] - ALIASES[2].fetch_add(blocks.len() as u64, std::sync::atomic::Ordering::Relaxed); - unguard(&mut g, &blocks); - } + let blocks: Vec = + ranges.iter().flat_map(|&(at, n)| g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).collect::>()).collect(); + #[cfg(feature = "diagnostics")] + ALIASES[2].fetch_add(blocks.len() as u64, std::sync::atomic::Ordering::Relaxed); + unguard(&mut g, &blocks); } /// The runtime is about to unmap a view of which it maps a part again at @@ -2153,7 +2159,12 @@ pub fn title_memory_splitting(at: usize, len: usize) { return; } let mut g = guards(); - // (The view itself too: the part that stays is read-only until then.) + // (The view itself too: the part that stays is read-only until then. And + // all of them told as written before the first is writable.) + for &other in &others { + g.clean.remove(other / BLOCK); + PUBLISHED.clear(other / BLOCK); + } open(&mut g, at, at.saturating_add(len)); for other in others { open(&mut g, other, other + BLOCK); @@ -3991,6 +4002,8 @@ mod many_askers_tests { let to = page + 1 + next((PAGES - page).min(3)); // Written through one view, asked about at another. let (through, asked) = (all[next(VIEWS)], next(VIEWS)); + #[allow(unused_assignments)] + let mut how = 0; let (at, last) = (all[asked], &mut last[asked]); if next(4) != 0 { // As in the test above, or after a word of ours, @@ -4014,6 +4027,7 @@ mod many_askers_tests { continue; } let reading = (next(3) == 0).then(super::title_memory_reading); + how = usize::from(reading.is_some()); 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) }; @@ -4021,8 +4035,10 @@ mod many_askers_tests { past.fetch_add(1, std::sync::atomic::Ordering::Relaxed); assert_eq!(unsafe { (word as *const u64).read_volatile() }, 2, "put elsewhere"); } else { + how += 2; if next(4) == 0 { super::writing(word, 8); + how += 4; } unsafe { (word as *mut u64).write_volatile(1) }; } @@ -4040,7 +4056,13 @@ mod many_askers_tests { } let (now, written) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view"); let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1); - assert!(number > last[page], "page {page}: {number} is not after {}", last[page]); + assert!( + number > last[page], + "{VIEWS} views, page {page}, through {:x} ({how}), asked at {:x}: {number} is not after {}", + through / PAGE + page, + at / PAGE + page, + last[page] + ); for l in &mut last[from..to] { *l = now; } From 0f1607c82aa5c958a804627caeea9d39d0156dc6 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 15:31:33 -0600 Subject: [PATCH 4/4] The pages shaders' writes were put into are noted without a lock Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 102 +++++++++++++++++++++++++++----- 1 file changed, 86 insertions(+), 16 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 81d4213..4077178 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -1433,10 +1433,69 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> { } /// The 4 KiB pages of title memory that what shaders wrote was put into, -/// and the frame it last was. -static LANDED: Mutex>>> = Mutex::new(None); +/// and the frame it last was: in pieces made when first needed and never let +/// go. Some 20,000 pages a frame are noted by the relay and the landing +/// threads: in a map behind one lock that was 309 waits for it and 280 looks +/// at its table in the 40 s of a profile, as many as all else of the landings' +/// notes (run faults-5). +struct Landed([std::sync::atomic::AtomicPtr; Landed::PIECES]); -/// A page's number, spread: some 20,000 a frame are noted in [`LANDED`]. +/// Of 256 MiB: the frame (its low 31 bits and one), 0 for never. +type LandedPiece = [std::sync::atomic::AtomicU32; Landed::PAGES]; + +impl Landed { + const PAGES: usize = 1 << 16; + /// 128 TiB, what a process has. + const PIECES: usize = 1 << 19; + + fn stamp(frame: u64) -> u32 { + (frame as u32 & 0x7fff_ffff) + 1 + } + + fn note(&self, page: usize, frame: u64) { + use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed}; + let Some(place) = self.0.get(page / Landed::PAGES) else { + return; + }; + let mut piece = place.load(Acquire); + if piece.is_null() { + let made: Box = Box::new([const { std::sync::atomic::AtomicU32::new(0) }; Landed::PAGES]); + let made = Box::into_raw(made); + piece = match place.compare_exchange(std::ptr::null_mut(), made, AcqRel, Acquire) { + Ok(_) => made, + Err(there) => { + // SAFETY: made just now, and another thread's is there. + drop(unsafe { Box::from_raw(made) }); + there + } + }; + } + // SAFETY: a piece, which is never freed. + let at = unsafe { &(&*piece)[page % Landed::PAGES] }; + let stamp = Landed::stamp(frame); + // (Most are noted several times a frame: no write then.) + if at.load(Relaxed) != stamp { + at.store(stamp, Relaxed); + } + } + + /// Whether `page` was noted in a frame from `since` on, up to `now`. + fn since(&self, page: usize, since: u64, now: u64) -> bool { + let Some(place) = self.0.get(page / Landed::PAGES) else { + return false; + }; + // SAFETY: null, or a piece, which is never freed. + let Some(piece) = (unsafe { place.load(std::sync::atomic::Ordering::Acquire).as_ref() }) else { + return false; + }; + let stamp = piece[page % Landed::PAGES].load(std::sync::atomic::Ordering::Relaxed); + stamp != 0 && u64::from(Landed::stamp(now).wrapping_sub(stamp) & 0x7fff_ffff) <= now.saturating_sub(since) + } +} + +static LANDED: Landed = Landed([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Landed::PIECES]); + +/// A page's number, spread. #[derive(Default)] struct PageHash(u64); @@ -1461,15 +1520,13 @@ impl std::hash::Hasher for PageHash { pub(crate) fn landing(at: usize, len: usize) { { let frame = crate::frame::current(); - let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); - let landed = landed.get_or_insert_with(Default::default); let (first, last) = (at / KERNEL_PAGE, (at + len.max(1) - 1) / KERNEL_PAGE); - landed.extend((first..=last).map(|page| (page, frame))); + (first..=last).for_each(|page| LANDED.note(page, frame)); for (block, others) in elsewhere(at, len) { let block = block / KERNEL_PAGE; let here = first.max(block)..=last.min(block + BLOCK / KERNEL_PAGE - 1); for other in others { - landed.extend(here.clone().map(|page| (page - block + other / KERNEL_PAGE, frame))); + here.clone().for_each(|page| LANDED.note(page - block + other / KERNEL_PAGE, frame)); } } } @@ -1502,15 +1559,13 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, let elsewhere: Vec<(usize, Vec)> = spans.iter().flat_map(|&(at, len)| elsewhere(at, len)).collect(); { let frame = crate::frame::current(); - let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); - let landed = landed.get_or_insert_with(Default::default); for &page in pages { - landed.insert(page, frame); + LANDED.note(page, frame); } for (block, others) in &elsewhere { let first = block / KERNEL_PAGE; for &page in pages.iter().filter(|&&page| (first..first + BLOCK / KERNEL_PAGE).contains(&page)) { - landed.extend(others.iter().map(|other| (page - first + other / KERNEL_PAGE, frame))); + others.iter().for_each(|other| LANDED.note(page - first + other / KERNEL_PAGE, frame)); } } } @@ -1554,11 +1609,8 @@ pub(crate) fn block_published(block: usize) -> bool { /// Whether shaders' writes went into a page of `[at, at + len)` in the last /// `frames` frames. pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool { - let since = crate::frame::current().saturating_sub(frames); - let landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); - landed.as_ref().is_some_and(|landed| { - (at / 4096..=(at + len.max(1) - 1) / 4096).any(|page| landed.get(&page).is_some_and(|&f| f >= since)) - }) + let now = crate::frame::current(); + (at / 4096..=(at + len.max(1) - 1) / 4096).any(|page| LANDED.since(page, now.saturating_sub(frames), now)) } /// Whether every block of `[at, at + len)` is view memory written since a @@ -3659,6 +3711,24 @@ mod tests { unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; } + /// The frames pages were last landed in. + #[test] + fn landed_pages_are_known_by_their_frame() { + static LANDED: Landed = Landed([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Landed::PIECES]); + let landed = &LANDED; + for page in [0, 5, Landed::PAGES - 1, Landed::PAGES, 7 * Landed::PAGES + 3] { + assert!(!landed.since(page, 0, 100)); + landed.note(page, 100); + assert!(landed.since(page, 100, 100) && landed.since(page, 0, 100) && landed.since(page, 90, 110)); + assert!(!landed.since(page, 101, 110)); + landed.note(page, 0x1_0000_0005); + assert!(landed.since(page, 0x1_0000_0000, 0x1_0000_0007) && !landed.since(page, 0x1_0000_0006, 0x1_0000_0007)); + assert!(!landed.since(page + 1, 0, 0x1_0000_0007)); + } + landed.note(usize::MAX / 4096, 1); + assert!(!landed.since(usize::MAX / 4096, 0, 1)); + } + /// The set of blocks against another of the same. #[test] fn blocks_are_a_set() {