Merge branch 'day/faults' into local/next

This commit is contained in:
local committed 2026-11-25 15:35:09 -06:00
commit 2547124475
6 files changed
+551 -64

No files matched your search

+195 -30
View File
@@ -151,11 +151,48 @@ static JOURNAL: RwLock<Journal> = 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<T>(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<T>(_: 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
@@ -1369,14 +1426,76 @@ static GUARDS: Mutex<Guards> = 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,
/// and the frame it last was.
static LANDED: Mutex<Option<std::collections::HashMap<usize, u64, std::hash::BuildHasherDefault<PageHash>>>> = 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<LandedPiece>; 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<LandedPiece> = 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);
@@ -1401,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));
}
}
}
@@ -1442,15 +1559,13 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64,
let elsewhere: Vec<(usize, Vec<usize>)> = 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));
}
}
}
@@ -1494,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
@@ -3566,6 +3678,59 @@ 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");
// (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);
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 + 2 * PAGE + 4096)]
);
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 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() {