Merge local/copies: holes known by their bits, landed blocks taken
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
de135da286
8 files changed
+628
-70
No files matched your search
@@ -1689,6 +1689,7 @@ impl State {
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let refreshed = std::time::Instant::now();
|
||||
crate::watch::look_at_holes();
|
||||
self.heap_textures(list, heap, host);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked, refreshed.elapsed()]) {
|
||||
|
||||
@@ -4709,7 +4709,7 @@ impl Host {
|
||||
for list in runs {
|
||||
for step in &list.deferred().copies {
|
||||
if let Step::Refresh(shadow, address, len) = step
|
||||
&& !shadow.unwatched()
|
||||
&& shadow.asked_ahead()
|
||||
{
|
||||
let span = spans
|
||||
.entry(std::sync::Arc::as_ptr(shadow) as usize)
|
||||
@@ -4719,6 +4719,8 @@ impl Host {
|
||||
}
|
||||
}
|
||||
let ranges: Vec<(usize, usize)> = spans.into_values().collect();
|
||||
#[cfg(feature = "diagnostics")]
|
||||
SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
|
||||
crate::watch::ask_once(&ranges);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
split.part(0);
|
||||
@@ -6215,9 +6217,11 @@ impl std::hash::Hasher for AddressHash {
|
||||
/// in under flights' writes; the lists' steps, the refreshes among them; the
|
||||
/// snapshots; what goes to copies in the card's memory; the lists sent; and
|
||||
/// of the steps: the refreshes, and the copies and fills (those with the
|
||||
/// refreshes a copy of title memory flushes).
|
||||
/// refreshes a copy of title memory flushes). Of the asking, which ranges it
|
||||
/// is of. Of the refreshes, those before ranges are given to shaders, one
|
||||
/// copy at a time: nanoseconds, and how many.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
static SPLIT: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
|
||||
static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
|
||||
|
||||
/// Since the last frame-rate line: flushes of refreshes, their refreshes,
|
||||
/// those known to copy nothing, and those done on several threads.
|
||||
@@ -6234,6 +6238,11 @@ impl Split {
|
||||
Split(std::cell::Cell::new(std::time::Instant::now()))
|
||||
}
|
||||
|
||||
/// Nanoseconds since the last part.
|
||||
fn so_far(&self) -> u64 {
|
||||
self.0.get().elapsed().as_nanos() as u64
|
||||
}
|
||||
|
||||
/// What came since the last part was part `i`.
|
||||
fn part(&self, i: usize) {
|
||||
let now = std::time::Instant::now();
|
||||
@@ -6250,11 +6259,12 @@ fn split_line(frames: f64) {
|
||||
let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
|
||||
let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / (1 << 20) as f64 / frames).collect();
|
||||
tracing::info!(
|
||||
"preparing per frame, the submitting thread: {:.1} ms asking the write watch, {:.1} putting the title's bytes under flights' \
|
||||
"preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \
|
||||
writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
|
||||
several threads; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \
|
||||
several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \
|
||||
card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})",
|
||||
ms[0],
|
||||
ms[8],
|
||||
ms[1],
|
||||
ms[2],
|
||||
ms[6],
|
||||
@@ -6262,6 +6272,8 @@ fn split_line(frames: f64) {
|
||||
f[1],
|
||||
f[2],
|
||||
f[3],
|
||||
ms[9],
|
||||
ms[10] * 1e6,
|
||||
ms[7],
|
||||
ms[3],
|
||||
ms[4],
|
||||
@@ -6269,12 +6281,17 @@ fn split_line(frames: f64) {
|
||||
if crate::watch::light() { "on" } else { "off" },
|
||||
);
|
||||
tracing::info!(
|
||||
"asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB; view ranges: {:.0} answered by their \
|
||||
"asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
|
||||
written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
|
||||
bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
|
||||
waiting for the guards, {:.1} ms changing protections; pages taken again for the card: {:.1} MB compared, {:.1} MB of them \
|
||||
as they were, {:.1} MB to go up (VICTORY_SEND_CHANGED)",
|
||||
a[0],
|
||||
a[1] / 1024.0,
|
||||
a[11] / 1e6,
|
||||
a[12],
|
||||
a[10],
|
||||
a[9],
|
||||
a[2],
|
||||
a[3],
|
||||
a[4],
|
||||
@@ -6414,7 +6431,12 @@ impl Batch {
|
||||
Self::update(&shadow, from, to);
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
|
||||
{
|
||||
let ns = started.elapsed().as_nanos() as u64;
|
||||
SPLIT[6].fetch_add(ns, Ordering::Relaxed);
|
||||
SPLIT[9].fetch_add(ns, Ordering::Relaxed);
|
||||
SPLIT[10].fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Brings `[from, to)` of a copy up to date, timed.
|
||||
@@ -6497,7 +6519,7 @@ impl Batch {
|
||||
let ranges: Vec<(usize, usize)> = self
|
||||
.refreshes
|
||||
.iter()
|
||||
.filter(|r| !r.0.unwatched())
|
||||
.filter(|r| r.0.asked_ahead())
|
||||
.map(|r| (r.1, r.2))
|
||||
.collect();
|
||||
crate::watch::ask_ahead(&ranges);
|
||||
@@ -7795,6 +7817,50 @@ mod refresh_tests {
|
||||
at
|
||||
}
|
||||
|
||||
/// Title memory of `blocks` pages in a placeholder, one view to a page,
|
||||
/// and every fourth page not there: as a title that streams has it.
|
||||
fn with_holes(blocks: usize) -> usize {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
|
||||
VirtualAlloc2, VirtualFree,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
// SAFETY: a placeholder and a section of our own.
|
||||
unsafe {
|
||||
let at = VirtualAlloc2(
|
||||
GetCurrentProcess(),
|
||||
std::ptr::null(),
|
||||
blocks * PAGE,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
|
||||
PAGE_NOACCESS,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
) as usize;
|
||||
assert_ne!(at, 0);
|
||||
let len = blocks * PAGE;
|
||||
let section =
|
||||
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
|
||||
for block in (0..blocks).filter(|b| b % 4 != 3) {
|
||||
let to = at + block * PAGE;
|
||||
VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
|
||||
let view = MapViewOfFile3(
|
||||
section,
|
||||
GetCurrentProcess(),
|
||||
to as *const _,
|
||||
(block * PAGE) as u64,
|
||||
PAGE,
|
||||
MEM_REPLACE_PLACEHOLDER,
|
||||
PAGE_READWRITE,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
);
|
||||
assert_eq!(view.Value as usize, to);
|
||||
crate::title_memory_remapped(to, PAGE);
|
||||
}
|
||||
at
|
||||
}
|
||||
}
|
||||
|
||||
fn memory(len: usize) -> *mut u8 {
|
||||
// SAFETY: a plain allocation.
|
||||
unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
|
||||
@@ -8243,12 +8309,17 @@ mod refresh_tests {
|
||||
const EACH: usize = 224 << 10;
|
||||
const BIG: usize = 174 << 20;
|
||||
let watched = title(3000 * EACH, false);
|
||||
let views = title(1400 * EACH, true);
|
||||
// `VICTORY_BENCH_HOLES=0`: views without holes.
|
||||
let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
|
||||
let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
|
||||
let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
|
||||
let big = title(BIG, true);
|
||||
// SAFETY: the test's own memory.
|
||||
unsafe {
|
||||
std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
|
||||
std::ptr::write_bytes(views as *mut u8, 1, 1400 * EACH);
|
||||
for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
|
||||
std::ptr::write_bytes(at as *mut u8, 1, PAGE);
|
||||
}
|
||||
std::ptr::write_bytes(big as *mut u8, 1, BIG);
|
||||
}
|
||||
let mut small = Vec::new();
|
||||
@@ -8271,8 +8342,10 @@ mod refresh_tests {
|
||||
// The title's writes, and the relay's beside the submission.
|
||||
for _ in 0..9 {
|
||||
let at = views + random.below(1400 * EACH / 8) * 8;
|
||||
// SAFETY: the test's own memory.
|
||||
unsafe { (at as *mut u64).write_volatile(frame as u64) };
|
||||
if there(at) {
|
||||
// SAFETY: the test's own memory.
|
||||
unsafe { (at as *mut u64).write_volatile(frame as u64) };
|
||||
}
|
||||
}
|
||||
for _ in 0..60 {
|
||||
let at = watched + random.below(3000 * EACH / 8) * 8;
|
||||
|
||||
@@ -133,6 +133,16 @@ pub(crate) fn spent(which: usize, from: std::time::Instant) -> std::time::Instan
|
||||
|
||||
/// For the frame-rate line: where landing went, per frame.
|
||||
pub(crate) fn log(frames: f64) {
|
||||
let t: Vec<f64> = TAKEN.iter().map(|t| t.swap(0, Ordering::Relaxed) as f64 / frames).collect();
|
||||
if t[0] > 0.0 {
|
||||
tracing::info!(
|
||||
"blocks landed in beside the guards per frame: {:.0}, {:.0} of them held by the copy they were landed through, which takes \
|
||||
them no more (VICTORY_LAND_TAKEN={})",
|
||||
t[0],
|
||||
t[1],
|
||||
u8::from(taken()),
|
||||
);
|
||||
}
|
||||
let s: Vec<f64> = STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
|
||||
if s[stat::PIECES] == 0.0 && s[stat::REST] == 0.0 {
|
||||
return;
|
||||
@@ -416,8 +426,39 @@ pub(crate) struct Notes {
|
||||
pages: Vec<usize>,
|
||||
/// Per piece, from the first such page to the last: address, bytes.
|
||||
spans: Vec<(usize, usize)>,
|
||||
/// Per piece put beside the guards, all of it: its 64 KiB block and the
|
||||
/// copy it was landed through (which the job holds until the flush).
|
||||
landed: Vec<(usize, *const crate::shadow::Shadow)>,
|
||||
}
|
||||
|
||||
// SAFETY: the pointers are used by the job that has the notes, in `flush`.
|
||||
unsafe impl Send for Notes {}
|
||||
|
||||
/// Whether a copy a landing went through is noted as up to date with it
|
||||
/// (`VICTORY_LAND_TAKEN=0`: it is not, and the next refresh copies the 64
|
||||
/// KiB again and sends them up to the card, as before).
|
||||
///
|
||||
/// What a landing puts into title memory the copy holds already: the card
|
||||
/// wrote it there, and a copy in the card's memory was given it on the CPU's
|
||||
/// side by the same merge. But the block counted as written, for that copy
|
||||
/// as for every other one, so the next refresh copied the whole block, sent
|
||||
/// it up and had the card hash it again: some 900 blocks a frame landed
|
||||
/// beside the guards, of the 103 MB a frame that went up (run record-1).
|
||||
///
|
||||
/// Why it may be left out ([`crate::shadow::Shadow::landed`]): the copy held
|
||||
/// title memory's bytes of the block before the landing, if it had taken it
|
||||
/// after the block's last noted write and no write was to be noted (the
|
||||
/// block's bit, `crate::watch::block_published`), and the landing put the
|
||||
/// same bytes into both. Only where one copy alone landed in the block.
|
||||
fn taken() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_LAND_TAKEN").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// Since the last frame-rate line: blocks landed in beside the guards, and
|
||||
/// those of them the copy was noted as up to date with.
|
||||
static TAKEN: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
|
||||
|
||||
impl Notes {
|
||||
/// At the end of a job: what it wrote beside the guards is noted.
|
||||
pub(crate) fn flush(&mut self) {
|
||||
@@ -425,9 +466,24 @@ impl Notes {
|
||||
return;
|
||||
}
|
||||
let noting = std::time::Instant::now();
|
||||
crate::watch::landed_beside(&self.pages, &self.spans);
|
||||
let (now, blocks) = crate::watch::landed_beside(&self.pages, &self.spans);
|
||||
TAKEN[0].fetch_add(blocks.len() as u64, Ordering::Relaxed);
|
||||
if taken() {
|
||||
for (block, before) in blocks {
|
||||
let mut through = self.landed.iter().filter(|l| l.0 == block).map(|l| l.1);
|
||||
let Some(copy) = through.next() else {
|
||||
continue;
|
||||
};
|
||||
if !copy.is_null() && through.all(|other| other == copy) {
|
||||
// SAFETY: the job holds its copies until this is done.
|
||||
let copy = unsafe { &*copy };
|
||||
TAKEN[1].fetch_add(u64::from(copy.landed(block, before, now)), Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.pages.clear();
|
||||
self.spans.clear();
|
||||
self.landed.clear();
|
||||
spent(stat::NOTES, noting);
|
||||
}
|
||||
}
|
||||
@@ -447,9 +503,10 @@ pub(crate) unsafe fn piece(
|
||||
parts: &[(usize, usize)],
|
||||
take: bool,
|
||||
notes: &mut Notes,
|
||||
copy: *const crate::shadow::Shadow,
|
||||
) -> u64 {
|
||||
// SAFETY: the caller's.
|
||||
unsafe { piece_at(title, now, held, parts, take, notes, beside_on()) }
|
||||
unsafe { piece_at(title, now, held, parts, take, notes, beside_on(), copy) }
|
||||
}
|
||||
|
||||
/// [`piece`], and whether a view of ours is looked for.
|
||||
@@ -464,6 +521,7 @@ unsafe fn piece_at(
|
||||
take: bool,
|
||||
notes: &mut Notes,
|
||||
beside: bool,
|
||||
copy: *const crate::shadow::Shadow,
|
||||
) -> u64 {
|
||||
let Some(end) = parts.last().map(|p| p.1) else {
|
||||
return 0;
|
||||
@@ -527,6 +585,10 @@ unsafe fn piece_at(
|
||||
});
|
||||
if let Some((from, to)) = span {
|
||||
notes.spans.push((from, to - from));
|
||||
// Not through a copy that is not to be noted, if that is asked: the
|
||||
// block then has two.
|
||||
let through = if missing == 0 { copy } else { std::ptr::null() };
|
||||
notes.landed.push((title / BLOCK, through));
|
||||
}
|
||||
count(stat::NEW_PIECES, u64::from(new_pages > 0));
|
||||
count(stat::PAGES, pages);
|
||||
|
||||
@@ -192,7 +192,7 @@ fn a_piece_lands_what_the_card_wrote_in_its_parts() {
|
||||
let asked = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view").0;
|
||||
let mut notes = Notes::default();
|
||||
// SAFETY: vectors of `len` bytes.
|
||||
let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes) };
|
||||
let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes, std::ptr::null()) };
|
||||
notes.flush();
|
||||
let mut expect_held = base.clone();
|
||||
let mut expect = there.clone();
|
||||
@@ -292,7 +292,7 @@ fn landings_beside_the_title_and_its_refreshes_lose_nothing() {
|
||||
let offset = address - at;
|
||||
// SAFETY: each job its own pieces of the two vectors.
|
||||
unsafe {
|
||||
piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes);
|
||||
piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes, std::ptr::null());
|
||||
}
|
||||
}
|
||||
notes.flush();
|
||||
@@ -420,7 +420,7 @@ fn what_landing_costs() {
|
||||
let mut notes = Notes::default();
|
||||
for &(at, now, held) in &landing[jobs[j].clone()] {
|
||||
// SAFETY: each its own bytes.
|
||||
unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside) };
|
||||
unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside, std::ptr::null()) };
|
||||
}
|
||||
notes.flush();
|
||||
});
|
||||
|
||||
@@ -72,6 +72,6 @@ pub use host::on_failure;
|
||||
pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view};
|
||||
#[cfg(windows)]
|
||||
pub use watch::{
|
||||
title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping,
|
||||
title_memory_allocated, title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping,
|
||||
writing as kernel_will_write,
|
||||
};
|
||||
@@ -939,6 +939,8 @@ fn give_back(v: Vec<u8>) {
|
||||
}
|
||||
|
||||
const NOT_WATCHED: u8 = 2;
|
||||
/// Watched, not by the kernel but by the guards, when last asked about.
|
||||
const GUARDED: u8 = 3;
|
||||
|
||||
/// Where `a` and `b` (of one length) first differ, compared eight bytes at
|
||||
/// a time.
|
||||
@@ -2017,6 +2019,14 @@ impl Shadow {
|
||||
self.watched.load(Ordering::Relaxed) == NOT_WATCHED
|
||||
}
|
||||
|
||||
/// Whether a submission asks the kernel about the copy's ranges ahead:
|
||||
/// not of memory that is not watched, nor of view memory, which the
|
||||
/// kernel would refuse (and with it the ranges asked about together).
|
||||
pub(crate) fn asked_ahead(&self) -> bool {
|
||||
let watched = self.watched.load(Ordering::Relaxed);
|
||||
watched != NOT_WATCHED && (watched != GUARDED || !crate::watch::light())
|
||||
}
|
||||
|
||||
/// The copy's own number (see the field).
|
||||
pub(crate) fn id(&self) -> u64 {
|
||||
self.id
|
||||
@@ -2774,7 +2784,7 @@ impl Shadow {
|
||||
if from >= to {
|
||||
return true;
|
||||
}
|
||||
if self.watched.load(Ordering::Relaxed) != 1 {
|
||||
if !matches!(self.watched.load(Ordering::Relaxed), 1 | GUARDED) {
|
||||
return false;
|
||||
}
|
||||
// Around ranges shaders are writing the refresh asks gap by gap.
|
||||
@@ -2804,7 +2814,8 @@ impl Shadow {
|
||||
fn update_free(&self, from: usize, to: usize) -> usize {
|
||||
if self.watched.load(Ordering::Relaxed) != NOT_WATCHED {
|
||||
if let Some((now, written)) = crate::watch::writes(from, to, true) {
|
||||
self.watched.store(1, Ordering::Relaxed);
|
||||
let guarded = crate::watch::guarded(from, to);
|
||||
self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed);
|
||||
let copied = self.copy_stale(from, to, now, &written);
|
||||
self.refresh_check(from, to);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
@@ -3379,7 +3390,7 @@ impl Shadow {
|
||||
// Where title memory is not mapped the CPU's side keeps what
|
||||
// the card wrote, as before.
|
||||
let merged =
|
||||
unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes) };
|
||||
unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes, self) };
|
||||
self.walls_merged(hi - lo, merged as usize);
|
||||
put += merged;
|
||||
}
|
||||
@@ -3409,7 +3420,33 @@ impl Shadow {
|
||||
// keeps out what else writes them. Title memory that is not there
|
||||
// is looked at again when the next flight that declared the range
|
||||
// lands.
|
||||
unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes) }
|
||||
unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes, self) }
|
||||
}
|
||||
|
||||
/// What shaders wrote in 64 KiB block `block` (of title memory) of this
|
||||
/// copy was put into title memory beside the guard, which was noted as a
|
||||
/// write with number `now`, `before` the number of the block's last write
|
||||
/// before. If the copy held title memory's bytes of the block ahead of
|
||||
/// that it holds them still, and is noted to ([`crate::land`] says why);
|
||||
/// whether it was.
|
||||
///
|
||||
/// That it did: it took the whole block after that write, and no other
|
||||
/// came that is not noted yet. Looked at after the note, whatever comes
|
||||
/// later has a number above it: a write of the title's takes the block's
|
||||
/// bit, until an asking has noted it.
|
||||
pub(crate) fn landed(&self, block: usize, before: u64, now: u64) -> bool {
|
||||
let Some(page) = block.checked_sub(self.start as usize / PAGE) else {
|
||||
return false;
|
||||
};
|
||||
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(at) = copied.get_mut(page) else {
|
||||
return false;
|
||||
};
|
||||
let held = *at != 0 && *at >= before && crate::watch::block_published(block);
|
||||
if held {
|
||||
*at = (*at).max(now);
|
||||
}
|
||||
held
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+430
-48
@@ -140,11 +140,17 @@ fn kernel_written(first: usize, last: usize) -> Option<Vec<usize>> {
|
||||
&mut granularity,
|
||||
)
|
||||
} != 0;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
tally(10, u64::from(failed));
|
||||
tally(11, started.elapsed().as_nanos() as u64);
|
||||
}
|
||||
if failed {
|
||||
return None;
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
tally(12, count as u64);
|
||||
use crate::copystat::{C, add};
|
||||
add(C::Watches, 1);
|
||||
add(C::WatchUs, started.elapsed().as_micros() as u64);
|
||||
@@ -534,6 +540,27 @@ impl Bits {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a bit of `[first, last)` is set.
|
||||
fn any(&self, first: usize, last: usize) -> bool {
|
||||
let mut block = first;
|
||||
while block < last {
|
||||
let word = block / 64;
|
||||
let until = ((word + 1) * 64).min(last);
|
||||
let mask = (u64::MAX >> (64 - (until - block))) << (block % 64);
|
||||
match self.piece(word) {
|
||||
Some(piece) => {
|
||||
if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::SeqCst) & mask != 0 {
|
||||
return true;
|
||||
}
|
||||
block = until;
|
||||
}
|
||||
// None of the piece's.
|
||||
None => block = (word / Bits::WORDS + 1) * Bits::WORDS * 64,
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether the bits of all of `[first, last)` are set (not so of none).
|
||||
fn all(&self, first: usize, last: usize) -> bool {
|
||||
let mut block = first;
|
||||
@@ -567,18 +594,146 @@ impl Bits {
|
||||
/// at the journal after that finds every earlier write in it. A write that
|
||||
/// comes while the bit is looked at is no different from one that comes just
|
||||
/// after an asking: the next asking finds the block open.
|
||||
///
|
||||
/// So too for the blocks of placeholders that were copied as zeros
|
||||
/// (`Guards::held`): nothing can be there before the runtime maps it, and
|
||||
/// it tells of that ([`title_memory_remapped`]) before the title is.
|
||||
static PUBLISHED: Bits = Bits::new();
|
||||
|
||||
/// The blocks read-only by our hand, or about to be: set under the guards'
|
||||
/// lock ahead of the protection, cleared under it when the block is open
|
||||
/// again. Who finds none set has no guard to open and need not wait for the
|
||||
/// lock ([`writing`]): some 700 pieces a frame are landed in memory that is
|
||||
/// no view.
|
||||
static PROTECTED: Bits = Bits::new();
|
||||
|
||||
/// An asking made blocks of `pages` clean and noted them in the journal.
|
||||
fn publish(pages: &[usize]) {
|
||||
let g = guards();
|
||||
for page in pages {
|
||||
if g.clean.contains(page) {
|
||||
if g.clean.contains(page) || g.held.contains(page) {
|
||||
PUBLISHED.set(*page);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether placeholders are known for what they are (`VICTORY_KNOWN_HOLES=0`:
|
||||
/// every hole is looked at at every asking, as before).
|
||||
///
|
||||
/// Most ranges asked about have holes, reservations the title maps its pages
|
||||
/// into as it streams (231,000 regions, 1,125 of a frame's 1,530 asked view
|
||||
/// ranges, run next1-1). Such a range was never known whole: each asking put
|
||||
/// a question to Windows for each of its holes, under the guards' lock, and
|
||||
/// 111 ms a frame of all threads' time went into waiting for that lock.
|
||||
fn known_holes() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_KNOWN_HOLES").is_none_or(|v| v != "0") && light())
|
||||
}
|
||||
|
||||
/// Whether `block` lies in a placeholder: a reservation in which pages come
|
||||
/// to be only by mapping a view (or an allocation) in its place, which an
|
||||
/// ordinary commit cannot do.
|
||||
fn placeholder(block: usize) -> bool {
|
||||
/// `MEMORY_REGION_INFORMATION` (ntddk).
|
||||
#[repr(C)]
|
||||
#[derive(Default)]
|
||||
struct Region {
|
||||
allocation_base: usize,
|
||||
allocation_protect: u32,
|
||||
region_type: u32,
|
||||
region_size: usize,
|
||||
commit_size: usize,
|
||||
partition_id: usize,
|
||||
node_preference: usize,
|
||||
}
|
||||
#[link(name = "ntdll", kind = "raw-dylib")]
|
||||
unsafe extern "system" {
|
||||
fn NtQueryVirtualMemory(
|
||||
process: *mut std::ffi::c_void,
|
||||
at: *const std::ffi::c_void,
|
||||
class: u32,
|
||||
out: *mut std::ffi::c_void,
|
||||
len: usize,
|
||||
returned: *mut usize,
|
||||
) -> i32;
|
||||
}
|
||||
// (Class 3 answers with the kind of memory in that word, not the flags.)
|
||||
const MEMORY_REGION_INFORMATION_EX: u32 = 7;
|
||||
const PLACEHOLDER_RESERVATION: u32 = 1 << 8;
|
||||
let mut region = Region::default();
|
||||
// SAFETY: the answer's room and its size.
|
||||
let status = unsafe {
|
||||
NtQueryVirtualMemory(
|
||||
windows_sys::Win32::System::Threading::GetCurrentProcess(),
|
||||
(block * BLOCK) as *const _,
|
||||
MEMORY_REGION_INFORMATION_EX,
|
||||
(&raw mut region).cast(),
|
||||
size_of::<Region>(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
status >= 0 && region.region_type & PLACEHOLDER_RESERVATION != 0
|
||||
}
|
||||
|
||||
/// The runtime gave the title memory at `[at, at + len)`, allocated or
|
||||
/// committed: what was known of holes there is asked again.
|
||||
pub fn title_memory_allocated(at: usize, len: usize) {
|
||||
if len == 0 || !known_holes() {
|
||||
return;
|
||||
}
|
||||
let mut g = guards();
|
||||
let blocks: Vec<usize> = g.held.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect();
|
||||
for block in blocks {
|
||||
g.held.remove(&block);
|
||||
PUBLISHED.clear(block);
|
||||
}
|
||||
}
|
||||
|
||||
/// Once a frame: a hundredth of the known holes are looked at, in case one
|
||||
/// was filled with nobody telling ([`title_memory_allocated`],
|
||||
/// [`title_memory_remapped`]), which no title we know does.
|
||||
pub(crate) fn look_at_holes() {
|
||||
const PARTS: usize = 100;
|
||||
if !known_holes() {
|
||||
return;
|
||||
}
|
||||
static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let blocks: Vec<usize> = {
|
||||
let g = guards();
|
||||
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();
|
||||
FROM.store(part.last().map_or(0, |b| b + 1), std::sync::atomic::Ordering::Relaxed);
|
||||
part
|
||||
};
|
||||
let mut until = 0;
|
||||
for block in blocks {
|
||||
if block >= until {
|
||||
until = uncommitted_end(block);
|
||||
}
|
||||
if block >= until {
|
||||
// (Or unmapped memory was mapped since the part was taken: told
|
||||
// already, and forgotten.)
|
||||
let mut g = guards();
|
||||
if g.held.remove(&block) {
|
||||
PUBLISHED.clear(block);
|
||||
static SAID: std::sync::Once = std::sync::Once::new();
|
||||
SAID.call_once(|| {
|
||||
tracing::warn!(
|
||||
address = format_args!("{:#x}", block * BLOCK),
|
||||
"a placeholder of the title's was filled with nobody telling (VICTORY_KNOWN_HOLES=0 asks every time)"
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a block of `[start, end)` is view memory read-only by our hand:
|
||||
/// the kernel keeps no written pages of it and would refuse an asking.
|
||||
pub(crate) fn guarded(start: usize, end: usize) -> bool {
|
||||
PROTECTED.any(start / BLOCK, end.div_ceil(BLOCK))
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -589,9 +744,11 @@ fn published(start: usize, end: usize) -> bool {
|
||||
/// askings and the KiB they walked; view ranges answered by their bits, by
|
||||
/// the guards whole clean, and block by block; blocks made read-only; blocks
|
||||
/// opened by ourselves; nanoseconds waiting for the guards' lock and
|
||||
/// nanoseconds of changing protections (all threads).
|
||||
/// nanoseconds of changing protections (all threads); questions to Windows
|
||||
/// about holes; kernel askings refused; nanoseconds in kernel askings; the
|
||||
/// 4 KiB pages they found written.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
static ASKS: [std::sync::atomic::AtomicU64; 9] = [const { std::sync::atomic::AtomicU64::new(0) }; 9];
|
||||
static ASKS: [std::sync::atomic::AtomicU64; 13] = [const { std::sync::atomic::AtomicU64::new(0) }; 13];
|
||||
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn tally(what: usize, n: u64) {
|
||||
@@ -600,7 +757,7 @@ fn tally(what: usize, n: u64) {
|
||||
|
||||
/// [`ASKS`], taken.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) fn asks() -> [u64; 9] {
|
||||
pub(crate) fn asks() -> [u64; 13] {
|
||||
std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
|
||||
}
|
||||
|
||||
@@ -622,12 +779,15 @@ struct Guards {
|
||||
/// Blocks already copied as zeros. While they remain wholly uncommitted,
|
||||
/// the copy can skip hundreds of MB of failing kernel reads per world frame.
|
||||
absent: BTreeSet<usize>,
|
||||
/// Of those, the ones in placeholders ([`known_holes`]).
|
||||
held: BTreeSet<usize>,
|
||||
}
|
||||
|
||||
static GUARDS: Mutex<Guards> = Mutex::new(Guards {
|
||||
protected: BTreeSet::new(),
|
||||
clean: BTreeSet::new(),
|
||||
absent: BTreeSet::new(),
|
||||
held: BTreeSet::new(),
|
||||
});
|
||||
|
||||
fn guards() -> std::sync::MutexGuard<'static, Guards> {
|
||||
@@ -687,7 +847,12 @@ pub(crate) fn landing(at: usize, len: usize) {
|
||||
/// before they were did so with the number of an asking made before that,
|
||||
/// which is under the one given here, and takes it again; noted before, a
|
||||
/// copy could read the older bytes with a number above the note's.
|
||||
pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) {
|
||||
///
|
||||
/// Returns the note's number, and for each 64 KiB block noted the number of
|
||||
/// the block's last write before (0: none is known).
|
||||
pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, Vec<(usize, u64)>) {
|
||||
let mut before = Vec::with_capacity(spans.len());
|
||||
let noted;
|
||||
{
|
||||
let frame = crate::frame::current();
|
||||
let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
|
||||
@@ -699,11 +864,12 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) {
|
||||
{
|
||||
let mut j = journal_mut();
|
||||
let now = next_asking();
|
||||
noted = now;
|
||||
let mut last = usize::MAX;
|
||||
for &page in pages {
|
||||
let block = page * KERNEL_PAGE / PAGE;
|
||||
if block != last {
|
||||
j.written.insert(block, now);
|
||||
before.push((block, j.written.insert(block, now).unwrap_or(0)));
|
||||
last = block;
|
||||
}
|
||||
}
|
||||
@@ -712,6 +878,13 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) {
|
||||
// A placed texture there changes with no descriptor written.
|
||||
crate::descriptor::host::remapped(at, len);
|
||||
}
|
||||
(noted, before)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// Whether shaders' writes went into a page of `[at, at + len)` in the last
|
||||
@@ -751,53 +924,64 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
|
||||
// of the 68 ms a frame of "guards" (run 58).
|
||||
// `VICTORY_GUARD_ASK=1` asks every time, as before.
|
||||
static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && {
|
||||
let g = guards_timed();
|
||||
let first = start / BLOCK;
|
||||
g.protected.contains(&first) || g.absent.contains(&first)
|
||||
};
|
||||
let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
|
||||
let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1"))
|
||||
&& (PROTECTED.any(first, first + 1) || {
|
||||
let g = guards_timed();
|
||||
g.protected.contains(&first) || g.absent.contains(&first)
|
||||
});
|
||||
if !known && !is_view(start, end) {
|
||||
return None;
|
||||
}
|
||||
install();
|
||||
let mut g = guards_timed();
|
||||
let mut written = Vec::new();
|
||||
let mut run: Option<usize> = None;
|
||||
let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
|
||||
// The range's clean blocks, in order: read off the set in one pass,
|
||||
// not looked up one block at a time. A frame 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" (run 54). What the loop adds to
|
||||
// the set meanwhile is the block it stands at or ones before it.
|
||||
let clean: Vec<usize> = g.clean.range(first..last).copied().collect();
|
||||
if clean.len() == last - first {
|
||||
// Nothing written, mapped or new since the range was last taken.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
tally(3, 1);
|
||||
return Some(written);
|
||||
// The holes that an ordinary commit may have filled, with no word of the
|
||||
// runtime's. Windows is asked with the lock not held (the range is, no
|
||||
// other thread asks about it: `ASKING`); what the runtime tells meanwhile
|
||||
// takes the block out of the set, and it is looked at as any other.
|
||||
let unsure: Vec<usize> = {
|
||||
let g = guards_timed();
|
||||
if g.clean.range(first..last).count() == last - first {
|
||||
// Nothing written, mapped or new since the range was last taken.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
tally(3, 1);
|
||||
return Some(Vec::new());
|
||||
}
|
||||
g.absent.range(first..last).filter(|block| !g.held.contains(block)).copied().collect()
|
||||
};
|
||||
let mut came: Vec<usize> = Vec::new();
|
||||
let mut uncommitted_until = first;
|
||||
for block in unsure {
|
||||
// One question for the blocks of a region.
|
||||
if block >= uncommitted_until {
|
||||
uncommitted_until = uncommitted_end(block);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
tally(9, 1);
|
||||
}
|
||||
if block >= uncommitted_until {
|
||||
came.push(block);
|
||||
}
|
||||
}
|
||||
let mut g = guards_timed();
|
||||
#[cfg(feature = "diagnostics")]
|
||||
tally(4, 1);
|
||||
let mut next_clean = 0;
|
||||
let mut uncommitted_until = first;
|
||||
for block in &came {
|
||||
g.absent.remove(block);
|
||||
}
|
||||
let mut written = Vec::new();
|
||||
let mut run: Option<usize> = None;
|
||||
// The range's clean blocks, and those known to be holes, in order: read
|
||||
// off the sets in one pass, not looked up one block at a time. A frame
|
||||
// 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"
|
||||
// (run 54). What the loop adds to the sets meanwhile is the block it
|
||||
// stands at or ones before it.
|
||||
let clean: Vec<usize> = g.clean.range(first..last).copied().collect();
|
||||
let absent: Vec<usize> = g.absent.range(first..last).copied().collect();
|
||||
let (mut clean, mut absent) = (clean.into_iter().peekable(), absent.into_iter().peekable());
|
||||
for block in first..=last {
|
||||
while next_clean < clean.len() && clean[next_clean] < block {
|
||||
next_clean += 1;
|
||||
}
|
||||
let is_clean = next_clean < clean.len() && clean[next_clean] == block;
|
||||
let mut open = block < last && !is_clean;
|
||||
if open && g.absent.contains(&block) {
|
||||
// Ordinary commits need no runtime mapping notification. Reuse
|
||||
// this asking's query for the following blocks in the same region.
|
||||
if block >= uncommitted_until {
|
||||
uncommitted_until = uncommitted_end(block);
|
||||
}
|
||||
open = block >= uncommitted_until;
|
||||
if open {
|
||||
g.absent.remove(&block);
|
||||
}
|
||||
}
|
||||
if open {
|
||||
let is_clean = clean.next_if_eq(&block).is_some();
|
||||
let is_absent = absent.next_if_eq(&block).is_some();
|
||||
if block < last && !is_clean && !is_absent {
|
||||
written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE);
|
||||
if g.protected.contains(&block) {
|
||||
// Written through the runtime, still read-only.
|
||||
@@ -887,15 +1071,30 @@ fn protect(g: &mut Guards, from: usize, to: usize) {
|
||||
g.protected.extend(from..to);
|
||||
g.clean.extend(from..to);
|
||||
};
|
||||
// Ahead of the protection (`PROTECTED`).
|
||||
(from..to).for_each(|block| PROTECTED.set(block));
|
||||
if set(from, to) {
|
||||
note(g, from, to);
|
||||
return;
|
||||
}
|
||||
let mut uncommitted_until = from;
|
||||
for block in from..to {
|
||||
if set(block, block + 1) {
|
||||
// (Not one question a block of a region that is not there.)
|
||||
if block >= uncommitted_until && set(block, block + 1) {
|
||||
note(g, block, block + 1);
|
||||
} else if block < uncommitted_end(block) {
|
||||
continue;
|
||||
}
|
||||
PROTECTED.clear(block);
|
||||
if block >= uncommitted_until {
|
||||
uncommitted_until = uncommitted_end(block);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
tally(9, 1);
|
||||
}
|
||||
if block < uncommitted_until {
|
||||
g.absent.insert(block);
|
||||
if known_holes() && placeholder(block) {
|
||||
g.held.insert(block);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -935,6 +1134,7 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool {
|
||||
let mut old = 0;
|
||||
// SAFETY: a block we made read-only.
|
||||
unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) };
|
||||
PROTECTED.clear(block);
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if !blocks.is_empty() {
|
||||
@@ -949,7 +1149,8 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool {
|
||||
/// reads into its own memory.
|
||||
pub fn writing(at: usize, len: usize) {
|
||||
// The length is the title's (`fread`'s size times count, saturated).
|
||||
{
|
||||
let last = at.saturating_add(len).div_ceil(BLOCK);
|
||||
if !light() || PROTECTED.any(at / BLOCK, last) {
|
||||
let mut g = guards_timed();
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let held = g.protected.len();
|
||||
@@ -1037,6 +1238,7 @@ pub fn title_memory_unmapping(at: usize, len: usize) {
|
||||
g.protected.remove(&block);
|
||||
g.clean.remove(&block);
|
||||
PUBLISHED.clear(block);
|
||||
PROTECTED.clear(block);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1055,6 +1257,9 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static,
|
||||
let absent: Vec<usize> = g.absent.range(range).copied().collect();
|
||||
for block in absent {
|
||||
g.absent.remove(&block);
|
||||
if g.held.remove(&block) {
|
||||
PUBLISHED.clear(block);
|
||||
}
|
||||
}
|
||||
g
|
||||
}
|
||||
@@ -1704,6 +1909,183 @@ mod many_askers_tests {
|
||||
// of these writes.)
|
||||
}
|
||||
|
||||
/// A range of a placeholder with views in it is known whole, its holes
|
||||
/// among it, until something is mapped into one, unmapped from it or
|
||||
/// allocated there. A hole that is no placeholder's is asked about.
|
||||
#[test]
|
||||
fn holes_are_known_until_the_runtime_tells() {
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
const BLOCKS: usize = 8;
|
||||
// SAFETY (all): a placeholder and a section of our own, which stay.
|
||||
let (at, section) = unsafe {
|
||||
let at = VirtualAlloc2(
|
||||
GetCurrentProcess(),
|
||||
std::ptr::null(),
|
||||
BLOCKS * PAGE,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
|
||||
PAGE_NOACCESS,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
) as usize;
|
||||
let section =
|
||||
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (BLOCKS * PAGE) as u32, std::ptr::null());
|
||||
(at, section)
|
||||
};
|
||||
let map = |block: usize| unsafe {
|
||||
let to = at + block * PAGE;
|
||||
VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
|
||||
let view = MapViewOfFile3(
|
||||
section,
|
||||
GetCurrentProcess(),
|
||||
to as *const _,
|
||||
(block * PAGE) as u64,
|
||||
PAGE,
|
||||
MEM_REPLACE_PLACEHOLDER,
|
||||
PAGE_READWRITE,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
);
|
||||
assert_eq!(view.Value as usize, to);
|
||||
super::title_memory_remapped(to, PAGE);
|
||||
};
|
||||
map(1);
|
||||
map(5);
|
||||
assert!(super::placeholder(at / PAGE) && super::placeholder(at / PAGE + 7) && !super::placeholder(at / PAGE + 5));
|
||||
let end = at + BLOCKS * PAGE;
|
||||
let ask = |since: u64| -> (u64, Vec<usize>) {
|
||||
let (now, written) = writes(at, end, true).expect("a view");
|
||||
(now, written.into_iter().filter(|w| w.1 > since).map(|w| w.0 - at / PAGE).collect())
|
||||
};
|
||||
let (first, all) = ask(0);
|
||||
assert_eq!(all, (0..BLOCKS).collect::<Vec<_>>());
|
||||
assert!(super::published(at, end), "with its holes");
|
||||
// Written; mapped into; unmapped.
|
||||
unsafe { ((at + 5 * PAGE) as *mut u8).write_volatile(1) };
|
||||
assert!(!super::published(at, end));
|
||||
let (second, all) = ask(first);
|
||||
assert_eq!(all, [5]);
|
||||
map(2);
|
||||
assert!(!super::published(at, end));
|
||||
let (third, all) = ask(second);
|
||||
assert_eq!(all, [2]);
|
||||
unsafe { ((at + 2 * PAGE) as *mut u8).write_volatile(1) };
|
||||
let (fourth, all) = ask(third);
|
||||
assert_eq!(all, [2]);
|
||||
super::title_memory_unmapping(at + 5 * PAGE, PAGE);
|
||||
unsafe {
|
||||
let view = MEMORY_MAPPED_VIEW_ADDRESS { Value: (at + 5 * PAGE) as *mut _ };
|
||||
UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER);
|
||||
}
|
||||
let (fifth, all) = ask(fourth);
|
||||
assert_eq!(all, [5]);
|
||||
assert!(super::published(at, end));
|
||||
// Told of memory there, though there is none: asked about again.
|
||||
super::title_memory_allocated(at, PAGE);
|
||||
assert!(!super::published(at, end));
|
||||
let (_, all) = ask(fifth);
|
||||
assert_eq!(all, []);
|
||||
// A reservation of the ordinary kind is no placeholder.
|
||||
let plain = unsafe { VirtualAlloc(std::ptr::null(), PAGE, MEM_RESERVE, PAGE_NOACCESS) } as usize;
|
||||
assert!(!super::placeholder(plain / PAGE));
|
||||
super::look_at_holes();
|
||||
assert!(!super::published(at, end), "block 0 stays asked about");
|
||||
assert!(super::published(at + PAGE, end), "the others are as they were");
|
||||
super::title_memory_unmapping(at, BLOCKS * PAGE);
|
||||
}
|
||||
|
||||
/// Pages mapped into a placeholder, written and unmapped again, each by a
|
||||
/// thread of its own as the runtime does it, while others ask about all
|
||||
/// of it: what was written, and that a page came or went, is told to
|
||||
/// whoever asks after it, and blocks are known by their bits meanwhile.
|
||||
#[test]
|
||||
fn no_mapping_is_lost_between_askers() {
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
const BLOCKS: usize = 12;
|
||||
// SAFETY (all): a placeholder and a section of our own, which stay.
|
||||
let (at, section) = unsafe {
|
||||
let at = VirtualAlloc2(
|
||||
GetCurrentProcess(),
|
||||
std::ptr::null(),
|
||||
BLOCKS * PAGE,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
|
||||
PAGE_NOACCESS,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
) as usize;
|
||||
for block in 0..BLOCKS - 1 {
|
||||
VirtualFree((at + block * PAGE) as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
|
||||
}
|
||||
let section =
|
||||
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (BLOCKS * PAGE) as u32, std::ptr::null());
|
||||
(at, section as usize)
|
||||
};
|
||||
let end = at + BLOCKS * PAGE;
|
||||
let (stop, by_bits) = (AtomicBool::new(false), AtomicUsize::new(0));
|
||||
let number = |written: &[(usize, u64)], block: usize| written.iter().find(|w| w.0 == at / PAGE + block).map_or(0, |w| w.1);
|
||||
std::thread::scope(|s| {
|
||||
let mappers: Vec<_> = (0..4usize)
|
||||
.map(|t| {
|
||||
let number = &number;
|
||||
s.spawn(move || {
|
||||
for round in 0..120 {
|
||||
let block = t * 3 + round % 3;
|
||||
let to = at + block * PAGE;
|
||||
let (before, _) = writes(at, end, true).expect("a view");
|
||||
unsafe {
|
||||
let view = MapViewOfFile3(
|
||||
section as _,
|
||||
GetCurrentProcess(),
|
||||
to as *const _,
|
||||
(block * PAGE) as u64,
|
||||
PAGE,
|
||||
MEM_REPLACE_PLACEHOLDER,
|
||||
PAGE_READWRITE,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
);
|
||||
assert_eq!(view.Value as usize, to);
|
||||
super::title_memory_remapped(to, PAGE);
|
||||
(to as *mut u8).write_volatile(round as u8);
|
||||
}
|
||||
let (mapped, written) = writes(at, end, true).expect("a view");
|
||||
assert!(number(&written, block) > before, "mapped and written: not told");
|
||||
unsafe { ((to + 9) as *mut u8).write_volatile(round as u8) };
|
||||
let (again, written) = writes(to, to + PAGE, true).expect("a view");
|
||||
assert!(number(&written, block) > mapped, "written again: not told");
|
||||
super::title_memory_unmapping(to, PAGE);
|
||||
unsafe {
|
||||
let view = MEMORY_MAPPED_VIEW_ADDRESS { Value: to as *mut _ };
|
||||
assert_ne!(UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER), 0);
|
||||
}
|
||||
let _ = again;
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for t in 0..3usize {
|
||||
let (stop, by_bits) = (&stop, &by_bits);
|
||||
s.spawn(move || {
|
||||
let mut k = t;
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
k = (k * 5 + 3) % 64;
|
||||
let (from, to) = (at + k % 6 * PAGE, end - k / 8 % 5 * PAGE);
|
||||
by_bits.fetch_add(usize::from(super::published(from, to)), Ordering::Relaxed);
|
||||
assert!(writes(from, to, true).is_some());
|
||||
}
|
||||
});
|
||||
}
|
||||
let failed = mappers.into_iter().map(|m| m.join()).filter(Result::is_err).count();
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
assert_eq!(failed, 0);
|
||||
});
|
||||
assert!(by_bits.into_inner() > 0, "the bits answered none");
|
||||
// All unmapped: known whole, and nothing but holes.
|
||||
writes(at, end, true).expect("a view");
|
||||
assert!(super::published(at, end));
|
||||
super::title_memory_unmapping(at, BLOCKS * PAGE);
|
||||
}
|
||||
|
||||
/// A block's bit goes with everything that makes it the title's to write,
|
||||
/// or forgets it.
|
||||
#[test]
|
||||
|
||||
@@ -162,6 +162,9 @@ pub extern "system" fn XMemVirtualAlloc(
|
||||
"XMemVirtualAlloc"
|
||||
);
|
||||
}
|
||||
if !at.is_null() && !placeholder {
|
||||
victory_gpu::title_memory_allocated(at as usize, size);
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user