Write faults: a block just written rests before it is guarded again (VICTORY_GUARD_REST=0: not), a fault opens the view it came through alone (VICTORY_OPEN_ONE_VIEW=0: every view), guarded blocks kept as bits

A book of the faults (VICTORY_FAULT_BOOK=<file>, diagnostics) says of the
dorm: 586 faults a frame on 900 blocks, 245 of them on a block that had
faulted in the same frame already, 220 within 3 ms of the refresh that made
the block read-only; 69 ms a frame of the title's threads, of which 6 with
the guards' lock and 63 waiting for it. What is held under it is mostly
VirtualProtect (5 us and more in the game's process, one at a time whoever
asks: a bench found 14 threads no faster than one).

- A block a write fault opened is left open by the refreshes of the next
  3 ms and told as written at each.
- The other views of its page stay read-only, not clean.
- The sets of guarded, clean, absent and aliased blocks are bits, a range is
  looked at by words; the lock is let go between the runs a refresh guards;
  a fault that finds its block open takes no lock; the record of the title's
  views is read by many threads at once; the kernel is not asked about memory
  known to be a guarded view.

Run faults-2 (A/B of both switches, 20 phases of 10 s in the dorm): faults
601 -> 391 a frame, blocks made read-only 928 -> 407, the title's threads
27.5 -> 15.8 ms a frame in them (69 before), frame 64.8 -> 62.5 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-25 11:36:09 -06:00
1 parent bc83b16387
commit 0578afffbb
6 files changed
+569 -123

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
//! A book of the title's write faults on guarded view memory
//! (`VICTORY_FAULT_BOOK=<file>`; builds with diagnostics): which block, when
//! in the frame, what it waited for, and what else happened to the block
//! (taken by a refresh, asked about), for 40 frames from each of the times
//! `VICTORY_FAULT_BOOK_AT` gives (seconds after the start; 150,210,270 unless
//! given). Written as `<file>.<n>.bin`, records of 40 bytes: ticks of the
//! performance counter, two words, thread, what.
#![cfg(feature = "diagnostics")]
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
use std::sync::{Mutex, OnceLock};
/// What a record is of.
#[derive(Clone, Copy)]
#[repr(u32)]
pub(crate) enum What {
/// A frame ended (a: its number).
Frame = 0,
/// A write fault opened block `a`; b: blocks opened with it (the upper
/// 32 bits), nanoseconds of waiting for the guards' lock; c: nanoseconds
/// with it.
Fault = 1,
/// Blocks `[a, b)` were found written, or never taken, and made read-only.
Taken = 2,
/// `[a, b)` was asked about and known unwritten by its bits.
Known = 3,
/// `[a, b)` was asked about block by block; c: how many were written.
Asked = 4,
/// We opened block `a` ourselves.
Ours = 5,
/// Another view of a page taken, block `a`, was made read-only.
Alias = 6,
/// A fault on block `a` that someone else had opened; b: nanoseconds.
Open = 7,
/// Blocks `[a, b)` were opened ahead of the title's writes.
Ahead = 8,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct Record {
at: i64,
a: u64,
b: u64,
c: u64,
thread: u32,
what: u32,
}
static ON: AtomicBool = AtomicBool::new(false);
static BOOK: Mutex<Vec<Record>> = Mutex::new(Vec::new());
fn ticks() -> i64 {
let mut t = 0;
// SAFETY: an out pointer of the right size.
unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut t) };
t
}
/// Whether records are kept now.
pub(crate) fn on() -> bool {
ON.load(Relaxed)
}
pub(crate) fn note(what: What, a: usize, b: usize, c: u64) {
if !on() {
return;
}
// SAFETY: a question about this thread.
let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
let record = Record { at: ticks(), a: a as u64, b: b as u64, c, thread, what: what as u32 };
BOOK.lock().unwrap_or_else(|e| e.into_inner()).push(record);
}
/// A frame ended.
pub(crate) fn frame() {
const FRAMES: u64 = 40;
static SETTINGS: OnceLock<Option<(String, Vec<u64>)>> = OnceLock::new();
static BEGAN: OnceLock<std::time::Instant> = OnceLock::new();
static LEFT: AtomicU64 = AtomicU64::new(0);
static MADE: AtomicU64 = AtomicU64::new(0);
let began = *BEGAN.get_or_init(std::time::Instant::now);
let Some((file, times)) = SETTINGS.get_or_init(|| {
let file = std::env::var("VICTORY_FAULT_BOOK").ok().filter(|f| !f.is_empty())?;
let times = std::env::var("VICTORY_FAULT_BOOK_AT").unwrap_or_else(|_| "150,210,270".into());
Some((file, times.split(',').filter_map(|t| t.trim().parse().ok()).collect()))
}) else {
return;
};
note(What::Frame, crate::frame::current() as usize, 0, 0);
if on() {
if LEFT.fetch_sub(1, Relaxed) > 1 {
return;
}
ON.store(false, Relaxed);
let records = std::mem::take(&mut *BOOK.lock().unwrap_or_else(|e| e.into_inner()));
let file = format!("{file}.{}.bin", MADE.fetch_add(1, Relaxed));
std::thread::spawn(move || {
// SAFETY: plain data, every byte of it written.
let bytes = unsafe { std::slice::from_raw_parts(records.as_ptr().cast::<u8>(), size_of_val(&records[..])) };
match std::fs::write(&file, bytes) {
Ok(()) => tracing::info!(file, records = records.len(), "book of faults written"),
Err(e) => tracing::warn!(file, %e, "book of faults not written"),
}
});
} else if times.get(MADE.load(Relaxed) as usize).is_some_and(|&t| began.elapsed().as_secs() >= t) {
LEFT.store(FRAMES, Relaxed);
ON.store(true, Relaxed);
}
}
+24 -9
View File
@@ -37,7 +37,6 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::ffi::c_void; use std::ffi::c_void;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
use windows::Win32::Foundation::HANDLE; use windows::Win32::Foundation::HANDLE;
@@ -281,7 +280,9 @@ struct Views {
whole: Vec<(usize, usize)>, whole: Vec<(usize, usize)>,
} }
static VIEWS: Mutex<Views> = Mutex::new(Views { /// Read by many threads at once (write faults, landings), changed when the
/// runtime maps or unmaps.
static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views {
views: BTreeMap::new(), views: BTreeMap::new(),
pages: BTreeMap::new(), pages: BTreeMap::new(),
pages_twice: 0, pages_twice: 0,
@@ -289,14 +290,18 @@ static VIEWS: Mutex<Views> = Mutex::new(Views {
whole: Vec::new(), whole: Vec::new(),
}); });
fn views() -> std::sync::MutexGuard<'static, Views> { fn views() -> std::sync::RwLockReadGuard<'static, Views> {
VIEWS.lock().unwrap_or_else(|e| e.into_inner()) VIEWS.read().unwrap_or_else(|e| e.into_inner())
}
fn views_mut() -> std::sync::RwLockWriteGuard<'static, Views> {
VIEWS.write().unwrap_or_else(|e| e.into_inner())
} }
/// The runtime made a section of `bytes` for physical pages; `committed` /// The runtime made a section of `bytes` for physical pages; `committed`
/// if with `SEC_COMMIT` (only such a section can be opened as a heap). /// if with `SEC_COMMIT` (only such a section can be opened as a heap).
pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { pub fn title_memory_section(section: usize, bytes: u64, committed: bool) {
let mut v = views(); let mut v = views_mut();
v.sections.retain(|s| s.0 != section); v.sections.retain(|s| s.0 != section);
// A handle's number given out again: the view was of the section that // A handle's number given out again: the view was of the section that
// had it before (it stays mapped: someone may be writing through it). // had it before (it stays mapped: someone may be writing through it).
@@ -308,7 +313,7 @@ pub fn title_memory_section(section: usize, bytes: u64, committed: bool) {
/// sees is of it any more, and [`beside`]'s view goes. /// sees is of it any more, and [`beside`]'s view goes.
pub fn title_memory_section_gone(section: usize) { pub fn title_memory_section_gone(section: usize) {
let whole = { let whole = {
let mut v = views(); let mut v = views_mut();
let at = v.whole.iter().position(|w| w.0 == section); let at = v.whole.iter().position(|w| w.0 == section);
at.map(|i| v.whole.swap_remove(i).1) at.map(|i| v.whole.swap_remove(i).1)
}; };
@@ -324,7 +329,7 @@ pub fn title_memory_section_gone(section: usize) {
/// `offset` on. Call after [`crate::title_memory_remapped`] of the range. /// `offset` on. Call after [`crate::title_memory_remapped`] of the range.
pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) {
{ {
let mut v = views(); let mut v = views_mut();
v.views.insert(at, (len, section, offset)); v.views.insert(at, (len, section, offset));
for k in 0..len.div_ceil(K64) { for k in 0..len.div_ceil(K64) {
let shown = v.pages.entry((section, offset + (k * K64) as u64)).or_default(); let shown = v.pages.entry((section, offset + (k * K64) as u64)).or_default();
@@ -343,7 +348,7 @@ pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) {
/// the views that touch it are forgotten (the runtime tells again those it /// the views that touch it are forgotten (the runtime tells again those it
/// maps anew). /// maps anew).
pub(crate) fn views_gone(at: usize, len: usize) { pub(crate) fn views_gone(at: usize, len: usize) {
let mut v = views(); let mut v = views_mut();
if v.views.is_empty() { if v.views.is_empty() {
return; return;
} }
@@ -529,7 +534,17 @@ pub(crate) fn cover(at: usize, len: usize) -> Cover {
/// `crate::watch::title_memory_reading`: until it lets go the title sees /// `crate::watch::title_memory_reading`: until it lets go the title sees
/// the same pages at `at`. /// the same pages at `at`.
pub(crate) fn beside(at: usize, len: usize) -> Option<usize> { pub(crate) fn beside(at: usize, len: usize) -> Option<usize> {
let mut v = views(); let known = {
let v = views();
let Cover::Run(section, offset) = cover_in(&v.views, at, len) else {
return None;
};
v.whole.iter().find(|w| w.0 == section).map(|w| (w.1, offset))
};
if let Some((base, offset)) = known {
return (base != 0).then(|| base + offset as usize);
}
let mut v = views_mut();
let Cover::Run(section, offset) = cover_in(&v.views, at, len) else { let Cover::Run(section, offset) = cover_in(&v.views, at, len) else {
return None; return None;
}; };
+2
View File
@@ -20,6 +20,8 @@ mod capture;
pub mod console; pub mod console;
#[cfg(all(windows, feature = "diagnostics"))] #[cfg(all(windows, feature = "diagnostics"))]
mod copystat; mod copystat;
#[cfg(all(windows, feature = "diagnostics"))]
mod faultbook;
#[cfg(windows)] #[cfg(windows)]
mod cores; mod cores;
pub mod descriptor; pub mod descriptor;
+1
View File
@@ -963,6 +963,7 @@ extern "system" fn present(
#[cfg(all(windows, feature = "diagnostics"))] #[cfg(all(windows, feature = "diagnostics"))]
fn frame_ends() { fn frame_ends() {
crate::timeline::presented(); crate::timeline::presented();
crate::faultbook::frame();
crate::ab::presented(|switch, was, will| { crate::ab::presented(|switch, was, will| {
if switch == "VICTORY_ASYNC_SUBMIT" && was && !will { if switch == "VICTORY_ASYNC_SUBMIT" && was && !will {
behind::leave(); behind::leave();
+2 -1
View File
@@ -3485,7 +3485,8 @@ impl Shadow {
fn update_free(&self, from: usize, to: usize) -> usize { fn update_free(&self, from: usize, to: usize) -> usize {
if self.watched.load(Ordering::Relaxed) != NOT_WATCHED { if self.watched.load(Ordering::Relaxed) != NOT_WATCHED {
if let Some((now, written)) = crate::watch::writes(from, to, true) { if let Some((now, written)) = crate::watch::writes(from, to, true) {
let guarded = crate::watch::guarded(from, to); // (A range whose blocks rest after a write has no guard now.)
let guarded = crate::watch::guarded(from, to) || self.watched.load(Ordering::Relaxed) == GUARDED;
self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed); self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed);
let copied = self.copy_stale(from, to, now, &written); let copied = self.copy_stale(from, to, now, &written);
self.refresh_check(from, to); self.refresh_check(from, to);
+430 -113
View File
@@ -27,6 +27,7 @@
//! before. //! before.
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
use std::ops::{Bound, RangeBounds};
use std::sync::{Condvar, Mutex, RwLock}; use std::sync::{Condvar, Mutex, RwLock};
/// The unit tracked and copied: 64 KiB, the console's page (the kernel's /// The unit tracked and copied: 64 KiB, the console's page (the kernel's
@@ -625,7 +626,10 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
// Read-only since an asking noted it: the bits first, then the journal. // Read-only since an asking noted it: the bits first, then the journal.
if guarded && published(start, end) { if guarded && published(start, end) {
#[cfg(feature = "diagnostics")] #[cfg(feature = "diagnostics")]
tally(2, 1); {
tally(2, 1);
crate::faultbook::note(crate::faultbook::What::Known, first, last, 0);
}
let j = journal(); let j = journal();
return Some((next_asking(), of(&j))); return Some((next_asking(), of(&j)));
} }
@@ -636,7 +640,9 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
return Some(known); return Some(known);
} }
let mut guards_asked = false; let mut guards_asked = false;
let pages = match kernel_written(first, last) { // (View memory read-only by our hand: the kernel would refuse.)
let refused = guarded && light() && PROTECTED.any(first, last);
let pages = match if refused { None } else { kernel_written(first, last) } {
Some(pages) => pages, Some(pages) => pages,
None => { None => {
guards_asked = true; guards_asked = true;
@@ -692,6 +698,10 @@ pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64],
let (first, last) = (start / PAGE, end.div_ceil(PAGE)); let (first, last) = (start / PAGE, end.div_ceil(PAGE));
// The bits first, then the journal, as in `writes`. // The bits first, then the journal, as in `writes`.
let known = published(start, end); let known = published(start, end);
#[cfg(feature = "diagnostics")]
if known {
crate::faultbook::note(crate::faultbook::What::Known, first, last, 1);
}
let j = journal(); let j = journal();
if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) {
return false; return false;
@@ -877,7 +887,7 @@ static PROTECTED: Bits = Bits::new();
fn publish(pages: &[usize]) { fn publish(pages: &[usize]) {
let g = guards(); let g = guards();
for page in pages { for page in pages {
if g.clean.contains(page) || g.held.contains(page) { if g.clean.contains(*page) || g.held.contains(*page) {
PUBLISHED.set(*page); PUBLISHED.set(*page);
} }
} }
@@ -948,9 +958,9 @@ pub fn title_memory_allocated(at: usize, len: usize) {
return; return;
} }
let mut g = guards(); let mut g = guards();
let blocks: Vec<usize> = g.held.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); let blocks: Vec<usize> = g.held.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).collect();
for block in blocks { for block in blocks {
g.held.remove(&block); g.held.remove(block);
PUBLISHED.clear(block); PUBLISHED.clear(block);
} }
} }
@@ -967,7 +977,7 @@ pub(crate) fn look_at_holes() {
let blocks: Vec<usize> = { let blocks: Vec<usize> = {
let g = guards(); let g = guards();
let from = FROM.load(std::sync::atomic::Ordering::Relaxed); let from = FROM.load(std::sync::atomic::Ordering::Relaxed);
let part: Vec<usize> = g.held.range(from..).take(g.held.len() / PARTS + 1).copied().collect(); let part: Vec<usize> = g.held.range(from..).take(g.held.len() / PARTS + 1).collect();
FROM.store(part.last().map_or(0, |b| b + 1), std::sync::atomic::Ordering::Relaxed); FROM.store(part.last().map_or(0, |b| b + 1), std::sync::atomic::Ordering::Relaxed);
part part
}; };
@@ -980,7 +990,7 @@ pub(crate) fn look_at_holes() {
// (Or unmapped memory was mapped since the part was taken: told // (Or unmapped memory was mapped since the part was taken: told
// already, and forgotten.) // already, and forgotten.)
let mut g = guards(); let mut g = guards();
if g.held.remove(&block) { if g.held.remove(block) {
PUBLISHED.clear(block); PUBLISHED.clear(block);
static SAID: std::sync::Once = std::sync::Once::new(); static SAID: std::sync::Once = std::sync::Once::new();
SAID.call_once(|| { SAID.call_once(|| {
@@ -1037,16 +1047,162 @@ fn guards_timed() -> std::sync::MutexGuard<'static, Guards> {
g g
} }
/// A set of blocks, a bit each: a fault, or a look at a range of thousands of
/// blocks, is a few words of it and no walk through a tree of every guarded
/// block there is.
struct Blocks(BTreeMap<usize, Box<[u64; Blocks::WORDS]>>);
impl Blocks {
/// The words of 4 GiB.
const WORDS: usize = 1 << 10;
const IN_PIECE: usize = Blocks::WORDS * 64;
const fn new() -> Blocks {
Blocks(BTreeMap::new())
}
fn word(&self, word: usize) -> u64 {
self.0.get(&(word / Blocks::WORDS)).map_or(0, |piece| piece[word % Blocks::WORDS])
}
fn contains(&self, block: usize) -> bool {
self.word(block / 64) >> (block % 64) & 1 != 0
}
/// Whether it was not there.
fn insert(&mut self, block: usize) -> bool {
let piece = self.0.entry(block / Blocks::IN_PIECE).or_insert_with(|| Box::new([0; Blocks::WORDS]));
let word = &mut piece[block % Blocks::IN_PIECE / 64];
let was = *word;
*word |= 1 << (block % 64);
was != *word
}
/// Whether it was there.
fn remove(&mut self, block: usize) -> bool {
let Some(piece) = self.0.get_mut(&(block / Blocks::IN_PIECE)) else {
return false;
};
let word = &mut piece[block % Blocks::IN_PIECE / 64];
let was = *word;
*word &= !(1 << (block % 64));
was != *word
}
fn insert_all(&mut self, blocks: std::ops::Range<usize>) {
for block in blocks {
self.insert(block);
}
}
/// Those of `range`, in order.
fn range(&self, range: impl RangeBounds<usize>) -> impl Iterator<Item = usize> + '_ {
let first = match range.start_bound() {
Bound::Included(&first) => first,
Bound::Excluded(&before) => before.saturating_add(1),
Bound::Unbounded => 0,
};
// (Exclusive. No block's number is near the top.)
let last = match range.end_bound() {
Bound::Included(&last) => last.saturating_add(1),
Bound::Excluded(&last) => last,
Bound::Unbounded => usize::MAX,
}
.max(first);
self.0.range(first / Blocks::IN_PIECE..=last / Blocks::IN_PIECE).flat_map(move |(&piece, words)| {
let base = piece * Blocks::IN_PIECE;
let from = first.max(base) - base;
let to = last.min(base + Blocks::IN_PIECE).saturating_sub(base);
let words = if from < to { &words[from / 64..to.div_ceil(64)] } else { &[][..] };
words.iter().enumerate().flat_map(move |(k, &bits)| {
let at = (from / 64 + k) * 64;
BitsOf(bits & in_word(at, from, to)).map(move |bit| base + at + bit)
})
})
}
fn len(&self) -> usize {
self.0.values().flat_map(|piece| piece.iter()).map(|word| word.count_ones() as usize).sum()
}
}
/// Of the 64 blocks from `at` on, those in `[from, to)`, a bit each.
fn in_word(at: usize, from: usize, to: usize) -> u64 {
let low = from.saturating_sub(at).min(64);
let high = to.saturating_sub(at).min(64);
if low >= high { 0 } else { (u64::MAX >> (64 - (high - low))) << low }
}
/// The bits of a word that are set, by number.
struct BitsOf(u64);
impl Iterator for BitsOf {
type Item = usize;
fn next(&mut self) -> Option<usize> {
let bit = (self.0 != 0).then(|| self.0.trailing_zeros() as usize)?;
self.0 &= self.0 - 1;
Some(bit)
}
}
/// Whether a write fault opens the view that was written and leaves the
/// page's other views read-only, not clean any more
/// (`VICTORY_OPEN_ONE_VIEW=0`: opens them all, as before).
///
/// The others were opened (a change of protection each, under the guards'
/// lock, with other faults waiting) and made read-only again when the page
/// was next taken, though the title writes through one of them: 586 faults a
/// frame opened 880 blocks (run faults-1). A write through one left as it was
/// faults, and opens it.
fn open_one_view() -> bool {
crate::toggled!("VICTORY_OPEN_ONE_VIEW")
}
/// How long a block the title has just opened by a write is left open by
/// those that take it (`VICTORY_GUARD_REST=<microseconds>`, 3,000 unless
/// given; `0`: not at all, as before).
///
/// 220 of a frame's 586 faults came within 3 ms after a refresh had taken the
/// block and made it read-only, while the title was still writing it, and
/// what a refresh takes is asked about again by the next within a millisecond
/// (run faults-1): made read-only, written, opened, up to a dozen times a
/// frame. A block that rests counts as written at each asking, so nothing is
/// missed; it is read-only at the first asking after its rest, which the
/// title's later writes are seen by.
fn rest() -> std::time::Duration {
#[cfg(test)]
{
REST_IN_TEST.get()
}
#[cfg(not(test))]
{
static US: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
if !crate::toggled!("VICTORY_GUARD_REST") {
return std::time::Duration::ZERO;
}
let us = *US.get_or_init(|| {
std::env::var("VICTORY_GUARD_REST").ok().and_then(|v| v.trim().parse().ok()).filter(|us| *us > 1).unwrap_or(3000)
});
std::time::Duration::from_micros(us)
}
}
#[cfg(test)]
thread_local! {
/// [`rest`], for what this thread asks.
static REST_IN_TEST: std::cell::Cell<std::time::Duration> = const { std::cell::Cell::new(std::time::Duration::ZERO) };
}
struct Guards { struct Guards {
/// Blocks we made read-only. /// Blocks we made read-only.
protected: BTreeSet<usize>, protected: Blocks,
/// Of those, the ones not written since a copy took them. /// Of those, the ones not written since a copy took them.
clean: BTreeSet<usize>, clean: Blocks,
/// Blocks already copied as zeros. While they remain wholly uncommitted, /// Blocks already copied as zeros. While they remain wholly uncommitted,
/// the copy can skip hundreds of MB of failing kernel reads per world frame. /// the copy can skip hundreds of MB of failing kernel reads per world frame.
absent: BTreeSet<usize>, absent: Blocks,
/// Of those, the ones in placeholders ([`known_holes`]). /// Of those, the ones in placeholders ([`known_holes`]).
held: BTreeSet<usize>, held: Blocks,
/// Blocks that were absent and turned out to be other memory than views /// Blocks that were absent and turned out to be other memory than views
/// when something was there again: never guarded, copied every time. /// when something was there again: never guarded, copied every time.
foreign: BTreeSet<usize>, foreign: BTreeSet<usize>,
@@ -1060,24 +1216,44 @@ struct Guards {
/// read-only together with those (which are in it as well): what opens /// read-only together with those (which are in it as well): what opens
/// one opens them all. (A write's range can be huge, `fread`'s, so only /// one opens them all. (A write's range can be huge, `fread`'s, so only
/// these are looked up.) /// these are looked up.)
aliased: BTreeSet<usize>, aliased: Blocks,
/// Blocks opened by a write fault, and when ([`rest`]).
opened: std::collections::HashMap<usize, std::time::Instant, std::hash::BuildHasherDefault<PageHash>>,
} }
impl Guards { impl Guards {
fn left_alone(&self, block: usize) -> bool { fn left_alone(&self, block: usize) -> bool {
self.kernel.iter().chain(&self.changing).any(|&(first, last)| (first..last).contains(&block)) self.kernel.iter().chain(&self.changing).any(|&(first, last)| (first..last).contains(&block))
} }
/// Whether `block` is left open for now: the title has just written it.
fn rests(&self, block: usize, rest: std::time::Duration) -> bool {
!rest.is_zero() && self.opened.get(&block).is_some_and(|at| at.elapsed() < rest)
}
/// A write fault opened `block`.
fn opened(&mut self, block: usize) {
const MANY: usize = 1 << 13;
if self.opened.len() >= MANY {
self.opened.retain(|_, at| at.elapsed().as_millis() < 50);
if self.opened.len() >= MANY {
self.opened.clear();
}
}
self.opened.insert(block, std::time::Instant::now());
}
} }
static GUARDS: Mutex<Guards> = Mutex::new(Guards { static GUARDS: Mutex<Guards> = Mutex::new(Guards {
protected: BTreeSet::new(), protected: Blocks::new(),
clean: BTreeSet::new(), clean: Blocks::new(),
absent: BTreeSet::new(), absent: Blocks::new(),
held: BTreeSet::new(), held: Blocks::new(),
foreign: BTreeSet::new(), foreign: BTreeSet::new(),
kernel: Vec::new(), kernel: Vec::new(),
changing: Vec::new(), changing: Vec::new(),
aliased: BTreeSet::new(), aliased: Blocks::new(),
opened: std::collections::HashMap::with_hasher(std::hash::BuildHasherDefault::new()),
}); });
fn guards() -> std::sync::MutexGuard<'static, Guards> { fn guards() -> std::sync::MutexGuard<'static, Guards> {
@@ -1227,7 +1403,7 @@ pub(crate) fn written_since_taken(at: usize, len: usize) -> bool {
} }
let g = guards(); let g = guards();
(at / BLOCK..=(at + len - 1) / BLOCK) (at / BLOCK..=(at + len - 1) / BLOCK)
.all(|b| !g.clean.contains(&b) && !g.absent.contains(&b) && !g.protected.contains(&b)) .all(|b| !g.clean.contains(b) && !g.absent.contains(b) && !g.protected.contains(b))
} }
/// For view memory: the pages of `[start, end)`'s blocks written since /// For view memory: the pages of `[start, end)`'s blocks written since
@@ -1246,7 +1422,7 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1"))
&& (PROTECTED.any(first, first + 1) || { && (PROTECTED.any(first, first + 1) || {
let g = guards_timed(); let g = guards_timed();
g.protected.contains(&first) || g.absent.contains(&first) g.protected.contains(first) || g.absent.contains(first)
}); });
if !known && !is_view(start, end) { if !known && !is_view(start, end) {
return None; return None;
@@ -1264,7 +1440,7 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
tally(3, 1); tally(3, 1);
return Some(Vec::new()); return Some(Vec::new());
} }
g.absent.range(first..last).filter(|block| !g.held.contains(block)).copied().collect() g.absent.range(first..last).filter(|block| !g.held.contains(*block)).collect()
}; };
let mut came: Vec<(usize, bool)> = Vec::new(); let mut came: Vec<(usize, bool)> = Vec::new();
let mut uncommitted_until = first; let mut uncommitted_until = first;
@@ -1281,45 +1457,56 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
came.push((block, is_view(block * BLOCK, (block + 1) * BLOCK))); came.push((block, is_view(block * BLOCK, (block + 1) * BLOCK)));
} }
} }
let rest = rest();
let mut g = guards_timed(); let mut g = guards_timed();
#[cfg(feature = "diagnostics")] #[cfg(feature = "diagnostics")]
tally(4, 1); tally(4, 1);
for &(block, view) in &came { for &(block, view) in &came {
if g.absent.remove(&block) && !view { if g.absent.remove(block) && !view {
g.foreign.insert(block); g.foreign.insert(block);
} }
} }
// The range's blocks that are neither clean nor known to be holes. A
// frame asks about some 10 GB of view memory, 150,000 blocks, nearly all
// clean.
let mut written = Vec::new(); let mut written = Vec::new();
let mut run: Option<usize> = None; for word in first / 64..last.div_ceil(64) {
// The range's clean blocks, and those known to be holes, in order: read let known = g.clean.word(word) | g.absent.word(word);
// off the sets in one pass, not looked up one block at a time. A frame written.extend(BitsOf(!known & in_word(word * 64, first, last)).map(|bit| word * 64 + bit));
// asks about some 10 GB of view memory, 150,000 blocks, nearly all }
// clean: the lookups were most of the 60-90 ms a frame of "guards" let mut run: Option<(usize, usize)> = None;
// (run 54). What the loop adds to the sets meanwhile is the block it for &block in &written {
// stands at or ones before it. if let Some((from, to)) = run
let clean: Vec<usize> = g.clean.range(first..last).copied().collect(); && to != block
let absent: Vec<usize> = g.absent.range(first..last).copied().collect(); {
let (mut clean, mut absent) = (clean.into_iter().peekable(), absent.into_iter().peekable()); protect(&mut g, from, to);
for block in first..=last { run = None;
let is_clean = clean.next_if_eq(&block).is_some(); // Faults of the title's wait for the lock: each block is done on
let is_absent = absent.next_if_eq(&block).is_some(); // its own, and looked at anew below.
if block < last && !is_clean && !is_absent { drop(g);
written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE); g = guards_timed();
if g.protected.contains(&block) {
// Read-only by way of another view of its page, or not clean
// because one could not be made so.
if cover(&mut g, block, block + 1) {
g.clean.insert(block);
}
} else if !g.foreign.contains(&block) && !g.left_alone(block) {
run.get_or_insert(block);
continue;
}
} }
if let Some(from) = run.take() { if g.protected.contains(block) {
protect(&mut g, from, block); // Read-only by way of another view of its page, or not clean
// because one could not be made so.
if let Some((from, to)) = run.take() {
protect(&mut g, from, to);
}
if cover(&mut g, block, block + 1) {
g.clean.insert(block);
}
} else if !g.foreign.contains(&block) && !g.left_alone(block) && !g.rests(block, rest) {
run = Some((run.map_or(block, |r| r.0), block + 1));
} else if let Some((from, to)) = run.take() {
protect(&mut g, from, to);
} }
} }
if let Some((from, to)) = run {
protect(&mut g, from, to);
}
drop(g);
#[cfg(feature = "diagnostics")]
crate::faultbook::note(crate::faultbook::What::Asked, first, last, written.len() as u64);
Some(written) Some(written)
} }
@@ -1374,6 +1561,8 @@ fn is_view(start: usize, end: usize) -> bool {
/// one of those is this memory written, and only a fault can say so. /// one of those is this memory written, and only a fault can say so.
/// `VICTORY_VIEW_GUARD=0` leaves the other views as they are, as before. /// `VICTORY_VIEW_GUARD=0` leaves the other views as they are, as before.
fn protect(g: &mut Guards, from: usize, to: usize) { fn protect(g: &mut Guards, from: usize, to: usize) {
#[cfg(feature = "diagnostics")]
crate::faultbook::note(crate::faultbook::What::Taken, from, to, 0);
protect_here(g, from, to); protect_here(g, from, to);
cover(g, from, to); cover(g, from, to);
} }
@@ -1403,7 +1592,7 @@ fn cover(g: &mut Guards, from: usize, to: usize) -> bool {
let mut all = true; let mut all = true;
for (page, others) in elsewhere(from * BLOCK, (to - from) * BLOCK) { for (page, others) in elsewhere(from * BLOCK, (to - from) * BLOCK) {
let block = page / BLOCK; let block = page / BLOCK;
if !g.protected.contains(&block) { if !g.protected.contains(block) {
continue; // not there, or not ours to guard continue; // not there, or not ours to guard
} }
#[cfg(feature = "diagnostics")] #[cfg(feature = "diagnostics")]
@@ -1415,7 +1604,7 @@ fn cover(g: &mut Guards, from: usize, to: usize) -> bool {
} }
if !covered { if !covered {
all = false; all = false;
g.clean.remove(&block); g.clean.remove(block);
} }
} }
all all
@@ -1430,10 +1619,10 @@ fn cover(g: &mut Guards, from: usize, to: usize) -> bool {
fn protect_alias(g: &mut Guards, block: usize) -> bool { fn protect_alias(g: &mut Guards, block: usize) -> bool {
use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect};
g.aliased.insert(block); g.aliased.insert(block);
if g.protected.contains(&block) { if g.protected.contains(block) {
return true; return true;
} }
if g.left_alone(block) { if g.left_alone(block) || g.rests(block, rest()) {
return false; return false;
} }
// Ahead of the protection. // Ahead of the protection.
@@ -1450,6 +1639,8 @@ fn protect_alias(g: &mut Guards, block: usize) -> bool {
} }
if done && matches!(old, PAGE_READWRITE | PAGE_READONLY) { if done && matches!(old, PAGE_READWRITE | PAGE_READONLY) {
g.protected.insert(block); g.protected.insert(block);
#[cfg(feature = "diagnostics")]
crate::faultbook::note(crate::faultbook::What::Alias, block, 0, 0);
return true; return true;
} }
if done { if done {
@@ -1492,8 +1683,8 @@ fn protect_here(g: &mut Guards, from: usize, to: usize) {
done done
}; };
let note = |g: &mut Guards, from: usize, to: usize| { let note = |g: &mut Guards, from: usize, to: usize| {
g.protected.extend(from..to); g.protected.insert_all(from..to);
g.clean.extend(from..to); g.clean.insert_all(from..to);
}; };
// Ahead of the protection (`PROTECTED`). // Ahead of the protection (`PROTECTED`).
(from..to).for_each(|block| PROTECTED.set(block)); (from..to).for_each(|block| PROTECTED.set(block));
@@ -1540,25 +1731,33 @@ fn uncommitted_end(block: usize) -> usize {
} }
/// Gives write access back to the guarded blocks of `[start, end)` and /// Gives write access back to the guarded blocks of `[start, end)` and
/// notes them written; true if any was guarded. The same physical pages at /// notes them written; how many there were. The same physical pages at
/// every other view of them are opened too: the write that faulted (or is /// every other view of them are written by that too (the write that faulted,
/// ours, `crate::host::copy_mapped`) goes through one view, and every /// or is ours, `crate::host::copy_mapped`, goes through one view): they are
/// guard over the pages must copy them again. /// clean no longer, whether they are opened as well ([`open_one_view`]) or
fn open(g: &mut Guards, start: usize, end: usize) -> bool { /// not.
fn open(g: &mut Guards, start: usize, end: usize) -> usize {
let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
if first >= last { if first >= last {
return false; return 0;
} }
let mut blocks: Vec<usize> = g.protected.range(first..last).copied().collect(); let mut blocks: Vec<usize> = g.protected.range(first..last).collect();
let here = blocks.len(); let here = blocks.len();
if !g.aliased.is_empty() { let aliased: Vec<usize> = g.aliased.range(first..last).collect();
let aliased: Vec<usize> = g.aliased.range(first..last).copied().collect(); if !aliased.is_empty() {
let one = open_one_view();
for block in aliased { for block in aliased {
g.aliased.remove(&block); g.aliased.remove(block);
for other in crate::inplace::pages_of(block * BLOCK) { for other in crate::inplace::pages_of(block * BLOCK) {
let other = other / BLOCK; let other = other / BLOCK;
g.aliased.remove(&other); if one {
if !(first..last).contains(&other) && g.protected.contains(&other) { // Before the first can be written.
g.clean.remove(other);
PUBLISHED.clear(other);
continue;
}
g.aliased.remove(other);
if !(first..last).contains(&other) && g.protected.contains(other) {
blocks.push(other); blocks.push(other);
} }
} }
@@ -1567,7 +1766,7 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool {
ALIASES[1].fetch_add((blocks.len() - here) as u64, std::sync::atomic::Ordering::Relaxed); ALIASES[1].fetch_add((blocks.len() - here) as u64, std::sync::atomic::Ordering::Relaxed);
} }
unguard(g, &blocks); unguard(g, &blocks);
here != 0 here
} }
/// Gives write access back to `blocks`, guarded ones. /// Gives write access back to `blocks`, guarded ones.
@@ -1577,10 +1776,10 @@ fn unguard(g: &mut Guards, blocks: &[usize]) {
let started = std::time::Instant::now(); let started = std::time::Instant::now();
// All of them before the first can be written: a write through one is a // All of them before the first can be written: a write through one is a
// write of the others' bytes. // write of the others' bytes.
for block in blocks { for &block in blocks {
g.protected.remove(block); g.protected.remove(block);
g.clean.remove(block); g.clean.remove(block);
PUBLISHED.clear(*block); PUBLISHED.clear(block);
} }
for &block in blocks { for &block in blocks {
let mut old = 0; let mut old = 0;
@@ -1611,11 +1810,13 @@ pub fn writing(at: usize, len: usize) {
let last = at.saturating_add(len).div_ceil(BLOCK); let last = at.saturating_add(len).div_ceil(BLOCK);
if !light() || PROTECTED.any(at / BLOCK, last) { if !light() || PROTECTED.any(at / BLOCK, last) {
let mut g = guards_timed(); let mut g = guards_timed();
let opened = open(&mut g, at, at.saturating_add(len));
#[cfg(feature = "diagnostics")] #[cfg(feature = "diagnostics")]
let held = g.protected.len(); {
open(&mut g, at, at.saturating_add(len)); tally(6, opened as u64);
#[cfg(feature = "diagnostics")] crate::faultbook::note(crate::faultbook::What::Ours, at / BLOCK, last, opened as u64);
tally(6, (held - g.protected.len()) as u64); }
let _ = opened;
} }
// A placed texture there changes with no descriptor written. // A placed texture there changes with no descriptor written.
crate::descriptor::host::remapped(at, len); crate::descriptor::host::remapped(at, len);
@@ -1638,10 +1839,10 @@ pub fn kernel_writing(at: usize, len: usize) -> KernelWrite {
open(&mut g, at, at.saturating_add(len)); open(&mut g, at, at.saturating_add(len));
if len != 0 { if len != 0 {
// Nothing known of them stands while they are left alone. // Nothing known of them stands while they are left alone.
let absent: Vec<usize> = g.absent.range(first..last).copied().collect(); let absent: Vec<usize> = g.absent.range(first..last).collect();
for block in absent { for block in absent {
g.absent.remove(&block); g.absent.remove(block);
if g.held.remove(&block) { if g.held.remove(block) {
PUBLISHED.clear(block); PUBLISHED.clear(block);
} }
} }
@@ -1758,7 +1959,7 @@ pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) {
} }
let mut g = guards(); let mut g = guards();
for &(at, n) in &ranges { for &(at, n) in &ranges {
let blocks: Vec<usize> = g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).copied().collect(); let blocks: Vec<usize> = g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).collect();
#[cfg(feature = "diagnostics")] #[cfg(feature = "diagnostics")]
ALIASES[2].fetch_add(blocks.len() as u64, std::sync::atomic::Ordering::Relaxed); ALIASES[2].fetch_add(blocks.len() as u64, std::sync::atomic::Ordering::Relaxed);
unguard(&mut g, &blocks); unguard(&mut g, &blocks);
@@ -1776,6 +1977,8 @@ pub fn title_memory_splitting(at: usize, len: usize) {
return; return;
} }
let mut g = guards(); let mut g = guards();
// (The view itself too: the part that stays is read-only until then.)
open(&mut g, at, at.saturating_add(len));
for other in others { for other in others {
open(&mut g, other, other + BLOCK); open(&mut g, other, other + BLOCK);
if CHANGING.get().0 { if CHANGING.get().0 {
@@ -1905,7 +2108,7 @@ fn came_back(at: usize, write: bool) -> bool {
return readable_view(at); return readable_view(at);
} }
// (A refresh may have guarded the page that came back.) // (A refresh may have guarded the page that came back.)
open(&mut guards(), at, at + 1) || writable(at) open(&mut guards(), at, at + 1) != 0 || writable(at)
}; };
let before = changes(); let before = changes();
if there() || again_after_change(before, there) { if there() || again_after_change(before, there) {
@@ -2016,14 +2219,10 @@ pub fn title_memory_unmapping(at: usize, len: usize) {
_ => g.changing.push((first, last)), _ => g.changing.push((first, last)),
} }
} }
let blocks: Vec<usize> = g let blocks: Vec<usize> = g.protected.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).collect();
.protected
.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK))
.copied()
.collect();
for block in blocks { for block in blocks {
g.protected.remove(&block); g.protected.remove(block);
g.clean.remove(&block); g.clean.remove(block);
PUBLISHED.clear(block); PUBLISHED.clear(block);
PROTECTED.clear(block); PROTECTED.clear(block);
} }
@@ -2036,8 +2235,8 @@ pub fn title_memory_unmapping(at: usize, len: usize) {
pub fn title_memory_freed(at: usize, len: usize) { pub fn title_memory_freed(at: usize, len: usize) {
let mut g = guards(); let mut g = guards();
let first = at / BLOCK; let first = at / BLOCK;
let noted = [&g.protected, &g.absent, &g.foreign].map(|set| set.range(first..).next()); let noted = [g.protected.range(first..).next(), g.absent.range(first..).next(), g.foreign.range(first..).next().copied()];
let Some(noted) = noted.into_iter().flatten().min().copied() else { let Some(noted) = noted.into_iter().flatten().min() else {
return; return;
}; };
let end = if len != 0 { let end = if len != 0 {
@@ -2048,10 +2247,10 @@ pub fn title_memory_freed(at: usize, len: usize) {
if noted >= end { if noted >= end {
return; return;
} }
let absent: Vec<usize> = g.absent.range(first..end).copied().collect(); let absent: Vec<usize> = g.absent.range(first..end).collect();
for block in absent { for block in absent {
g.absent.remove(&block); g.absent.remove(block);
if g.held.remove(&block) { if g.held.remove(block) {
PUBLISHED.clear(block); PUBLISHED.clear(block);
} }
} }
@@ -2096,10 +2295,10 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static,
crate::inplace::title_memory_freeing(at, len); crate::inplace::title_memory_freeing(at, len);
let mut g = guards(); let mut g = guards();
let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK); let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK);
let absent: Vec<usize> = g.absent.range(range.clone()).copied().collect(); let absent: Vec<usize> = g.absent.range(range.clone()).collect();
for block in absent { for block in absent {
g.absent.remove(&block); g.absent.remove(block);
if g.held.remove(&block) { if g.held.remove(block) {
PUBLISHED.clear(block); PUBLISHED.clear(block);
} }
} }
@@ -2107,9 +2306,9 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static,
for block in foreign { for block in foreign {
g.foreign.remove(&block); g.foreign.remove(&block);
} }
let aliased: Vec<usize> = g.aliased.range(range).copied().collect(); let aliased: Vec<usize> = g.aliased.range(range).collect();
for block in aliased { for block in aliased {
g.aliased.remove(&block); g.aliased.remove(block);
} }
g g
} }
@@ -2153,20 +2352,41 @@ pub(crate) fn install() {
}; };
} }
let at = r.ExceptionInformation[1]; let at = r.ExceptionInformation[1];
// Held across both checks: another thread may have opened the block let block = at / BLOCK;
// since this one faulted, and a copy may have guarded it again since // Another thread may have opened the block since this one faulted
// (then it is ours again, not read-only for some other reason). // (then nothing waits for the lock), and a copy may have guarded it
let mut g = guards(); // again since that (then it is ours again, not read-only for some
if open(&mut g, at, at + 1) { // other reason).
for _ in 0..3 {
if !PROTECTED.any(block, block + 1) && writable(at) {
#[cfg(feature = "diagnostics")]
crate::faultbook::note(crate::faultbook::What::Open, block, 0, 0);
return EXCEPTION_CONTINUE_EXECUTION;
}
#[cfg(feature = "diagnostics")] #[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::GuardFaults, 1); let began = std::time::Instant::now();
return EXCEPTION_CONTINUE_EXECUTION; // (Let go again before the next look: the runtime wants the
// guards to end a change.)
let mut g = guards();
#[cfg(feature = "diagnostics")]
let waited = began.elapsed();
let opened = open(&mut g, at, at + 1);
if opened != 0 {
g.opened(block);
drop(g);
#[cfg(feature = "diagnostics")]
{
crate::copystat::add(crate::copystat::C::GuardFaults, 1);
let ns = waited.as_nanos().min(u128::from(u32::MAX)) as usize;
let held = (began.elapsed() - waited).as_nanos() as u64;
crate::faultbook::note(crate::faultbook::What::Fault, block, opened << 32 | ns, held);
}
return EXCEPTION_CONTINUE_EXECUTION;
}
} }
if writable(at) { if writable(at) {
return EXCEPTION_CONTINUE_EXECUTION; return EXCEPTION_CONTINUE_EXECUTION;
} }
// (The runtime wants the guards to end a change.)
drop(g);
match ours { match ours {
Some(exit) => fail(exit), Some(exit) => fail(exit),
None if came_back(at, true) => EXCEPTION_CONTINUE_EXECUTION, None if came_back(at, true) => EXCEPTION_CONTINUE_EXECUTION,
@@ -2452,7 +2672,7 @@ mod tests {
assert!(written.contains(&(p / PAGE + 1, now))); assert!(written.contains(&(p / PAGE + 1, now)));
assert!(written.iter().all(|w| w.0 == p / PAGE + 1 || w.1 < now)); assert!(written.iter().all(|w| w.0 == p / PAGE + 1 || w.1 < now));
} }
assert!(!guards().held.contains(&(p / BLOCK + 1))); assert!(!guards().held.contains(p / BLOCK + 1));
drop(writing); drop(writing);
ask(); ask();
assert!((0..3).all(known) == holes); assert!((0..3).all(known) == holes);
@@ -2460,12 +2680,12 @@ mod tests {
let _changing = title_memory_remapping(); let _changing = title_memory_remapping();
title_memory_unmapping(p, BLOCK); title_memory_unmapping(p, BLOCK);
ask(); ask();
assert!(!known(0) && !guards().held.contains(&(p / BLOCK))); assert!(!known(0) && !guards().held.contains(p / BLOCK));
} }
ask(); ask();
assert!((0..3).all(known) == holes); assert!((0..3).all(known) == holes);
title_memory_freed(p, BLOCK); title_memory_freed(p, BLOCK);
assert!(!known(0) && !guards().held.contains(&(p / BLOCK))); assert!(!known(0) && !guards().held.contains(p / BLOCK));
title_memory_unmapping(p, 3 * BLOCK); title_memory_unmapping(p, 3 * BLOCK);
// SAFETY: our placeholders. // SAFETY: our placeholders.
unsafe { unsafe {
@@ -2495,7 +2715,7 @@ mod tests {
assert!(writes(at, at + BLOCK, true).is_some()); assert!(writes(at, at + BLOCK, true).is_some());
{ {
let g = guards(); let g = guards();
assert!(!g.protected.contains(&(at / BLOCK)) && !g.clean.contains(&(at / BLOCK))); assert!(!g.protected.contains(at / BLOCK) && !g.clean.contains(at / BLOCK));
} }
assert!(!published(at, at + BLOCK)); assert!(!published(at, at + BLOCK));
// SAFETY: our view. // SAFETY: our view.
@@ -2554,7 +2774,7 @@ mod tests {
assert!(holes.iter().all(|page| written.contains(page)), "copied every time"); assert!(holes.iter().all(|page| written.contains(page)), "copied every time");
as_made(); as_made();
let g = guards(); let g = guards();
assert!(holes.iter().all(|block| !g.held.contains(block) && !g.absent.contains(block))); assert!(holes.iter().all(|&block| !g.held.contains(block) && !g.absent.contains(block)));
} }
writing(p, BLOCK); writing(p, BLOCK);
as_made(); as_made();
@@ -2575,7 +2795,7 @@ mod tests {
let noted = |block: usize| { let noted = |block: usize| {
let g = guards(); let g = guards();
let block = p / BLOCK + block; let block = p / BLOCK + block;
g.protected.contains(&block) || g.clean.contains(&block) || g.absent.contains(&block) g.protected.contains(block) || g.clean.contains(block) || g.absent.contains(block)
}; };
assert!(guard(p, p + 3 * BLOCK).is_some()); assert!(guard(p, p + 3 * BLOCK).is_some());
assert!(noted(0) && noted(1) && noted(2)); assert!(noted(0) && noted(1) && noted(2));
@@ -3031,6 +3251,93 @@ mod tests {
drop_views(section, &[one, two], SIZE); drop_views(section, &[one, two], SIZE);
} }
/// A write opens the view it goes through and no other: the others stay
/// read-only, are told as written, and take writes of their own.
#[test]
fn a_write_opens_the_view_it_goes_through() {
let (section, one, two) = two_views(BLOCK);
let page = |view: usize| view / PAGE;
for view in [one, two] {
assert_eq!(guard(view, view + BLOCK), Some(vec![page(view)]));
}
// SAFETY (all): a view, opened by the handler.
unsafe { ((two + 8) as *mut u8).write(1) };
assert!(writable(two) && !writable(one));
unsafe { ((one + 8) as *mut u8).write(1) };
assert!(writable(two) && writable(one));
assert_eq!(guard(one, one + BLOCK), Some(vec![page(one)]));
assert_eq!(guard(two, two + BLOCK), Some(vec![page(two)]));
// Written at the view that was left as it was, after the other.
unsafe { ((two + 8) as *mut u8).write(1) };
assert_eq!(guard(one, one + BLOCK), Some(vec![page(one)]), "not clean, though never opened");
assert!(!writable(two) && !writable(one));
assert_eq!(guard(two, two + BLOCK), Some(vec![page(two)]));
assert_eq!(guard(one, one + BLOCK), Some(Vec::new()));
// Of a page that was told at one view, a kernel write to the other
// finds it open.
unsafe { ((two + 8) as *mut u8).write(1) };
assert!(!writable(one));
writing(one, 8);
assert!(writable(one));
drop_views(section, &[one, two], BLOCK);
}
/// A block the title has just written is not made read-only, and is told
/// as written at each asking, at every view of it, until it has rested.
#[test]
fn a_block_just_written_rests() {
let (section, one, two) = two_views(BLOCK);
let page = one / PAGE;
let rests = |rests: bool| REST_IN_TEST.set(std::time::Duration::from_secs(if rests { 3600 } else { 0 }));
assert_eq!(guard(one, one + BLOCK), Some(vec![page]));
assert_eq!(guard(one, one + BLOCK), Some(Vec::new()));
rests(true);
assert_eq!(guard(one, one + BLOCK), Some(Vec::new()), "nothing written: as it was");
// SAFETY (all): a view, opened by the handler.
unsafe { ((two + 8) as *mut u8).write(1) };
for _ in 0..3 {
assert_eq!(guard(one, one + BLOCK), Some(vec![page]));
assert!(writable(two), "no fault for the next write");
assert!(writes(two, two + BLOCK, true).is_some() && !published(two, two + BLOCK) && !published(one, one + BLOCK));
unsafe { ((two + 8) as *mut u8).write(1) };
}
rests(false);
assert_eq!(guard(one, one + BLOCK), Some(vec![page]));
assert!(!writable(two) && !writable(one));
assert_eq!(guard(one, one + BLOCK), Some(Vec::new()));
drop_views(section, &[one, two], BLOCK);
}
/// The set of blocks against another of the same.
#[test]
fn blocks_are_a_set() {
let (mut set, mut other) = (Blocks::new(), BTreeSet::new());
let mut seed = 1u64;
let mut next = |n: usize| {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(seed >> 33) as usize % n
};
for round in 0..40_000 {
// About the ends of pieces and words.
let block = [0, 63, Blocks::IN_PIECE, 3 * Blocks::IN_PIECE - 70][next(4)] + next(140);
if next(3) == 0 {
assert_eq!(set.remove(block), other.remove(&block));
} else {
assert_eq!(set.insert(block), other.insert(block));
}
assert_eq!(set.contains(block), other.contains(&block));
if round % 64 == 0 {
let a = [0, 63, Blocks::IN_PIECE, 3 * Blocks::IN_PIECE - 70][next(4)] + next(140);
let b = a + [next(10), next(300), 2 * Blocks::IN_PIECE + next(100)][next(3)];
assert!(set.range(a..b).eq(other.range(a..b).copied()), "{a}..{b}");
assert!(set.range(a..).eq(other.range(a..).copied()) && set.range(..).eq(other.iter().copied()));
assert!(set.range(a..=b).eq(other.range(a..=b).copied()));
assert_eq!(set.len(), other.len());
}
}
assert_eq!(set.range(5..usize::MAX).next(), other.range(5..).next().copied());
}
/// What is known of a block by its bit is so at every view of its page: /// What is known of a block by its bit is so at every view of its page:
/// the write through one takes the bits of all. /// the write through one takes the bits of all.
#[test] #[test]
@@ -3251,7 +3558,14 @@ mod many_askers_tests {
/// again between. /// again between.
#[test] #[test]
fn no_write_to_views_is_lost_between_askers() { fn no_write_to_views_is_lost_between_askers() {
writes_to_views_are_not_lost::<1>(); writes_to_views_are_not_lost::<1>(0);
}
/// The same with blocks that rest after a write ([`super::rest`]).
#[test]
fn no_write_to_resting_views_is_lost_between_askers() {
writes_to_views_are_not_lost::<1>(50);
writes_to_views_are_not_lost::<3>(50);
} }
/// The same of pages shown at three addresses, each of which has copies /// The same of pages shown at three addresses, each of which has copies
@@ -3261,10 +3575,11 @@ mod many_askers_tests {
/// for one address only, `VICTORY_VIEW_GUARD=0`.) /// for one address only, `VICTORY_VIEW_GUARD=0`.)
#[test] #[test]
fn no_write_through_another_view_is_lost_between_askers() { fn no_write_through_another_view_is_lost_between_askers() {
writes_to_views_are_not_lost::<3>(); writes_to_views_are_not_lost::<3>(0);
} }
fn writes_to_views_are_not_lost<const VIEWS: usize>() { fn writes_to_views_are_not_lost<const VIEWS: usize>(rest: u64) {
let rest = std::time::Duration::from_micros(rest);
const PAGES: usize = 12; const PAGES: usize = 12;
const THREADS: usize = 8; const THREADS: usize = 8;
// SAFETY: views of a section of our own. // SAFETY: views of a section of our own.
@@ -3292,6 +3607,7 @@ mod many_askers_tests {
std::thread::scope(|s| { std::thread::scope(|s| {
if VIEWS > 1 { if VIEWS > 1 {
s.spawn(move || { s.spawn(move || {
super::REST_IN_TEST.set(rest);
let mut last = [0u64; VIEWS]; let mut last = [0u64; VIEWS];
for round in 0..300usize { for round in 0..300usize {
let (page, asked) = (round * 5 % PAGES, round % VIEWS); let (page, asked) = (round * 5 % PAGES, round % VIEWS);
@@ -3321,6 +3637,7 @@ mod many_askers_tests {
for t in 0..THREADS { for t in 0..THREADS {
let (by_bits, past) = (&by_bits, &past); let (by_bits, past) = (&by_bits, &past);
s.spawn(move || { s.spawn(move || {
super::REST_IN_TEST.set(rest);
let mut last = [[0u64; PAGES]; VIEWS]; let mut last = [[0u64; PAGES]; VIEWS];
let mut seed = t as u64 * 7919 + 1; let mut seed = t as u64 * 7919 + 1;
let mut next = |n: usize| { let mut next = |n: usize| {