#![cfg(windows)] pub(crate) mod mirror; use std::sync::Mutex; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; const BLOCK: usize = crate::watch::PAGE; const SMALLEST: usize = 4 << 30; static AT: AtomicUsize = AtomicUsize::new(0); static END: AtomicUsize = AtomicUsize::new(0); static NOTED: AtomicU64 = AtomicU64::new(0); pub(crate) fn upload_on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| { ["EONACAT_XS_ARENA_UPLOAD", "EONACAT_XS_ARENA_UPLOAD_CHECK", "EONACAT_XS_ARENA_MIRROR"] .iter() .any(|name| std::env::var_os(name).is_some_and(|v| v == "1")) }) } pub(crate) fn check_on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("EONACAT_XS_ARENA_UPLOAD_CHECK").is_some_and(|v| v == "1")) } pub fn arena_reserved(at: usize, len: usize, protect: u32) { if !upload_on() || len < SMALLEST || at == 0 { return; } if protect & 0xf800 == 0 { tracing::info!( at = format_args!("{at:#x}"), bytes = format_args!("{len:#x}"), protect = format_args!("{protect:#x}"), "arena upload-on-write: a big placeholder without GPU protection, left to the guards" ); return; } if AT.load(Ordering::Acquire) != 0 { tracing::info!( at = format_args!("{at:#x}"), bytes = format_args!("{len:#x}"), "arena upload-on-write: another big placeholder, left to the guards (only the first is the arena)" ); return; } if !crate::watch::own(at, len) { tracing::warn!( at = format_args!("{at:#x}"), bytes = format_args!("{len:#x}"), "arena upload-on-write: the arena could not be taken from the guards (EONACAT_XS_MEMORY_OWNED=0, or not 64 KiB aligned); left to them" ); return; } if check_on() { let _ = LAST.set(Last { at, began: std::time::Instant::now(), blocks: (0..len / BLOCK).map(|_| AtomicU64::new(0)).collect(), }); } END.store(at + len, Ordering::Release); AT.store(at, Ordering::Release); tracing::info!( at = format_args!("{at:#x}"), end = format_args!("{:#x}", at + len), check = check_on(), "arena upload-on-write: the arena is neither guarded nor write-watched; the copies over it take what its writers tell (EONACAT_XS_ARENA_UPLOAD=1)" ); } pub(crate) fn freed(at: usize, len: usize) { let lo = AT.load(Ordering::Acquire); if lo == 0 || at != lo || (len != 0 && len != END.load(Ordering::Acquire) - lo) { return; } AT.store(0, Ordering::Release); crate::watch::disown(lo); tracing::info!(at = format_args!("{lo:#x}"), "arena upload-on-write: the arena was freed"); } pub(crate) fn part(at: usize, len: usize) -> Option<(usize, usize)> { let lo = AT.load(Ordering::Acquire); if lo == 0 || len == 0 { return None; } let hi = END.load(Ordering::Acquire); let (from, to) = (at.max(lo), at.saturating_add(len).min(hi)); (from < to).then(|| (from, to - from)) } #[inline] pub(crate) fn holds_block(block: usize) -> bool { let lo = AT.load(Ordering::Relaxed); lo != 0 && (lo / BLOCK..END.load(Ordering::Relaxed) / BLOCK).contains(&block) } pub(crate) fn range() -> Option<(usize, usize)> { let lo = AT.load(Ordering::Acquire); (lo != 0).then(|| (lo, END.load(Ordering::Acquire))) } #[track_caller] pub(crate) fn wrote(at: usize, len: usize) { wrote_by(at, len, std::panic::Location::caller()); } fn wrote_by(at: usize, len: usize, by: &'static std::panic::Location<'static>) { mirror::wrote(at, len); crate::cardpool::card_written(at as u64, len as u64); let Some((at, len)) = part(at, len) else { return; }; NOTED.fetch_add(len as u64, Ordering::Relaxed); if check_on() { last_noted(at, len, by); } crate::watch::owner_wrote(at, len); } pub(crate) struct Noting(usize, usize, &'static std::panic::Location<'static>); impl Noting { #[track_caller] pub(crate) fn new(at: usize, len: usize) -> Noting { Noting(at, len, std::panic::Location::caller()) } } impl Drop for Noting { fn drop(&mut self) { wrote_by(self.0, self.1, self.2); } } struct Last { at: usize, began: std::time::Instant, blocks: Box<[AtomicU64]>, } static LAST: std::sync::OnceLock = std::sync::OnceLock::new(); const WHOS: usize = 32; static WHO: [std::sync::atomic::AtomicPtr>; WHOS] = [const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; WHOS]; fn who(by: &'static std::panic::Location<'static>) -> usize { let p = std::ptr::from_ref(by).cast_mut(); for (i, slot) in WHO.iter().enumerate().take(WHOS - 1) { let had = slot.load(Ordering::Acquire); if had == p { return i; } if had.is_null() { match slot.compare_exchange(std::ptr::null_mut(), p, Ordering::AcqRel, Ordering::Acquire) { Ok(_) => return i, Err(now) if now == p => return i, Err(_) => continue, } } } WHOS - 1 } fn who_name(i: usize) -> String { let p = WHO.get(i).map_or(std::ptr::null_mut(), |slot| slot.load(Ordering::Acquire)); if p.is_null() { return "others".into(); } let by = unsafe { &*p }; let file = by.file().rsplit(['/', '\\']).next().unwrap_or(by.file()); format!("{file}:{}", by.line()) } fn last_noted(at: usize, len: usize, by: &'static std::panic::Location<'static>) { let Some(last) = LAST.get() else { return; }; let word = ((who(by) as u64 + 1) << 48) | (last.began.elapsed().as_millis() as u64 & ((1 << 48) - 1)); let (first, end) = ((at - last.at) / BLOCK, (at + len - last.at).div_ceil(BLOCK)); for slot in last.blocks.get(first..end.min(last.blocks.len())).into_iter().flatten() { slot.store(word, Ordering::Relaxed); } } fn last_of(block: usize) -> Option<(usize, u64)> { let last = LAST.get()?; let word = last.blocks.get(block.checked_sub(last.at / BLOCK)?)?.load(Ordering::Relaxed); if word == 0 { return None; } let ms = last.began.elapsed().as_millis() as u64; Some(((word >> 48) as usize - 1, ms.saturating_sub(word & ((1 << 48) - 1)))) } const EVERY: std::time::Duration = std::time::Duration::from_secs(5); const SAMPLE: usize = 1 << 20; const PIECE: usize = 4096; struct Window { began: Option, refreshes: u64, compared: u64, differing: u64, pieces: u64, again: u64, examples: Vec, now: std::collections::BTreeSet, before: std::collections::BTreeSet, kinds: [u64; KINDS], by: [u64; WHOS], } const KEPT: usize = 4096; #[derive(Clone, Copy)] enum Kind { Looked, NoView, Alone, ArenaOnly, OutsideGuarded, OutsideOpen, Many, Landed, Due, NeverNoted, TitleZero, HeldZero, } const KINDS: usize = Kind::HeldZero as usize + 1; const KIND_NAMES: [&str; KINDS] = [ "looked", "no_view", "alone", "arena_only", "outside_guarded", "outside_open", "many_views", "landed", "due", "never_noted", "title_zero", "held_zero", ]; const LOOKED: usize = 64; fn whose(at: usize, title: &[u8], held: &[u8], kinds: &mut [u64; KINDS], by: &mut [u64; WHOS]) -> String { let mut count = |kind: Kind| kinds[kind as usize] += 1; count(Kind::Looked); let (lo, hi) = range().unwrap_or((0, 0)); let block = at / BLOCK; let views = crate::inplace::pages_of(block * BLOCK); let outside: Vec = views.iter().copied().filter(|&view| !(lo..hi).contains(&view)).collect(); let open = outside.iter().filter(|&&view| !crate::watch::guards_any(view, BLOCK)).count(); match (views.len(), outside.len()) { (0, _) => count(Kind::NoView), (1, _) => count(Kind::Alone), (_, 0) => count(Kind::ArenaOnly), _ if open == 0 => count(Kind::OutsideGuarded), _ => count(Kind::OutsideOpen), } if views.len() > crate::watch::MANY_VIEWS { count(Kind::Many); } if crate::watch::landed_lately(at, PIECE, 4) { count(Kind::Landed); } if crate::watch::arena_due_blocks(block * BLOCK, (block + 1) * BLOCK) != 0 { count(Kind::Due); } if title.iter().all(|&b| b == 0) { count(Kind::TitleZero); } if held.iter().all(|&b| b == 0) { count(Kind::HeldZero); } let last = last_of(block); match last { Some((who, _)) => by[who] += 1, None => count(Kind::NeverNoted), } let last = last.map_or_else(|| "never".to_string(), |(who, ms)| format!("{}@{ms}ms", who_name(who))); let outside = match outside.first() { Some(first) => format!("o{}{}={first:#x}", outside.len(), if open == 0 { "g" } else { "u" }), None => "o0".into(), }; format!("{at:#x}:v{}/{outside}/{last}", views.len()) } static WINDOW: Mutex = Mutex::new(Window { began: None, refreshes: 0, compared: 0, differing: 0, pieces: 0, again: 0, examples: Vec::new(), now: std::collections::BTreeSet::new(), before: std::collections::BTreeSet::new(), kinds: [0; KINDS], by: [0; WHOS], }); static TURN: AtomicU64 = AtomicU64::new(0); pub(crate) fn check(start: usize, data: *const u8, from: usize, to: usize, taken: &[(usize, usize)]) { if !check_on() || part(from, to - from) != Some((from, to - from)) { return; } let mut rest: Vec<(usize, usize)> = Vec::new(); let mut at = from; for &(a, b) in taken { if a > at { rest.push((at, a)); } at = at.max(b); } if at < to { rest.push((at, to)); } let rest: Vec<(usize, usize)> = rest .into_iter() .map(|(a, b)| (a.next_multiple_of(PIECE), b / PIECE * PIECE)) .filter(|&(a, b)| a < b) .collect(); let total: usize = rest.iter().map(|&(a, b)| b - a).sum(); let (mut compared, mut differing, mut pieces) = (0u64, 0u64, Vec::new()); let (mut kinds, mut by, mut said) = ([0u64; KINDS], [0u64; WHOS], Vec::new()); if total != 0 { let turn = TURN.fetch_add(1, Ordering::Relaxed).wrapping_mul(0x9e37_79b9_7f4a_7c15) as usize; let skip = turn % (total / PIECE); let all = || rest.iter().flat_map(|&(a, b)| (a..b).step_by(PIECE)); let mut title = [0u8; PIECE]; for at in all().skip(skip).chain(all().take(skip)).take(SAMPLE / PIECE) { if crate::host::read_into(at as *const u8, &mut title) { let held = unsafe { std::slice::from_raw_parts(data.add(at - start), PIECE) }; let n = held.iter().zip(&title).filter(|(a, b)| a != b).count() as u64; compared += PIECE as u64; if n != 0 { differing += n; if pieces.len() < LOOKED { said.push(whose(at, &title, held, &mut kinds, &mut by)); } pieces.push(at); } } } } let mut w = WINDOW.lock().unwrap_or_else(|e| e.into_inner()); let now = std::time::Instant::now(); let began = *w.began.get_or_insert(now); w.refreshes += 1; w.compared += compared; w.differing += differing; w.pieces += pieces.len() as u64; for (k, n) in kinds.iter().enumerate() { w.kinds[k] += n; } for (k, n) in by.iter().enumerate() { w.by[k] += n; } for (i, piece) in pieces.into_iter().enumerate() { if w.before.contains(&piece) { w.again += 1; } if w.examples.len() < 6 && let Some(said) = said.get(i) { w.examples.push(said.clone()); } if w.now.len() < KEPT { w.now.insert(piece); } } if now.duration_since(began) < EVERY { return; } let (lo, hi) = range().unwrap_or((0, 0)); let examples = w.examples.clone(); let kinds_line: Vec = KIND_NAMES.iter().zip(w.kinds).map(|(name, n)| format!("{name}={n}")).collect(); let mut writers: Vec<(u64, usize)> = w.by.iter().enumerate().filter(|(_, n)| **n != 0).map(|(i, n)| (*n, i)).collect(); writers.sort_unstable_by(|a, b| b.cmp(a)); let writers: Vec = writers.iter().take(8).map(|&(n, i)| format!("{}={n}", who_name(i))).collect(); tracing::info!( pieces = %kinds_line.join(" "), last_noted_by = %writers.join(" "), "arena upload-on-write check: what the differing pieces' pages are (views: o = outside the arena, g/u = guarded/unguarded there; the writer that last noted the block; EONACAT_XS_ARENA_UPLOAD_CHECK=1)" ); tracing::info!( refreshes = w.refreshes, compared_mb = format_args!("{:.1}", w.compared as f64 / 1e6), differing_mb = format_args!("{:.3}", w.differing as f64 / 1e6), pieces_differing = w.pieces, differing_before_too = w.again, examples = %examples.join(" "), noted_mb = format_args!("{:.1}", NOTED.swap(0, Ordering::Relaxed) as f64 / 1e6), blocks_held_open = crate::watch::arena_due_blocks(lo, hi), seconds = format_args!("{:.1}", now.duration_since(began).as_secs_f64()), "arena upload-on-write check: bytes of the arena's copies that differ from title memory with nothing noted (4 KiB pieces; EONACAT_XS_ARENA_UPLOAD_CHECK=1)" ); let seen = std::mem::take(&mut w.now); w.before = seen; w.began = Some(now); w.refreshes = 0; w.compared = 0; w.differing = 0; w.pieces = 0; w.again = 0; w.examples.clear(); w.kinds = [0; KINDS]; w.by = [0; WHOS]; }