From 90aaade09ac76641923b1ea6c24cc1348179c528 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Mon, 30 Nov 2026 08:51:04 +0100 Subject: [PATCH 1/2] d3d12: the other views' blocks of a guarded range are made read-only by one change a run (D3D12-ALIAS-PROTECT-RUNS) A range guarded together with the other views of its pages (protect, protect_claimed) made each of those views' blocks read-only with a VirtualProtect of its own: a call per 64 KiB block, each telling every core to forget the page (232 blocks a frame, 6.7 ms, measured on an RTX 4060). A view shows the range's pages in a row, so its blocks follow each other. cover now decides for every other view's block first (read-only already, to be made so, or not now) and then makes the wanted ones read-only by runs of blocks that follow each other, one change a run. A run whose change fails (not of one view) is done block by block, as before; a first block that is not as we left it keeps its protection. As protect_here and unguard_runs do, the first block's protection speaks for the run. LEONIDA_ALIAS_RUNS=0 makes a change a block, as before; with diagnostics the guards line counts the runs and those the change failed for. --- d3d12/crates/leonida-gpu/src/copystat.rs | 5 +- d3d12/crates/leonida-gpu/src/watch.rs | 172 +++++++++++++++++++++-- 2 files changed, 167 insertions(+), 10 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/copystat.rs b/d3d12/crates/leonida-gpu/src/copystat.rs index 651eae7ab6..6639962bec 100644 --- a/d3d12/crates/leonida-gpu/src/copystat.rs +++ b/d3d12/crates/leonida-gpu/src/copystat.rs @@ -1282,11 +1282,14 @@ pub(crate) fn log(frames: f64) { let [together, written, mapped] = [0, 1, 2].map(|n| crate::watch::ALIASES[n].load(std::sync::atomic::Ordering::Relaxed)); let [runs, runs_failed] = [0, 1].map(|n| crate::watch::UNGUARD_RUNS[n].load(std::sync::atomic::Ordering::Relaxed)); + let [alias_runs, alias_runs_failed] = + [0, 1].map(|n| crate::watch::ALIAS_RUNS[n].load(std::sync::atomic::Ordering::Relaxed)); tracing::info!( "guards over several views of a page, since the start: {together} blocks guarded with their other views, \ {written} views opened by a write through another, {mapped} ranges opened because a view of them was mapped; \ runs of guarded blocks opened by one change of protection: {runs}, and {runs_failed} it failed for \ - (LEONIDA_UNGUARD_RUNS)" + (LEONIDA_UNGUARD_RUNS); runs of other views' blocks made read-only by one change: {alias_runs}, and \ + {alias_runs_failed} it failed for (LEONIDA_ALIAS_RUNS)" ); tracing::info!( "waits for the write trackers' locks per frame, all threads (number, time): {}", diff --git a/d3d12/crates/leonida-gpu/src/watch.rs b/d3d12/crates/leonida-gpu/src/watch.rs index 02edd8e29d..f73cf1f746 100644 --- a/d3d12/crates/leonida-gpu/src/watch.rs +++ b/d3d12/crates/leonida-gpu/src/watch.rs @@ -3252,6 +3252,8 @@ pub(crate) static ALIASES: [std::sync::atomic::AtomicU64; 3] = [const { std::syn /// have now; a view whose block's claim cannot be had is not covered. fn cover(g: &Guards, from: usize, to: usize, mut claims: Option<&mut Claims>) -> bool { let mut all = true; + // Other views' blocks to make read-only, and the block each covers. + let mut wanted: Vec<(usize, usize)> = Vec::new(); for (page, others) in elsewhere(from * BLOCK, (to - from) * BLOCK) { let block = page / BLOCK; if !g.protected.contains(block) { @@ -3262,38 +3264,151 @@ fn cover(g: &Guards, from: usize, to: usize, mut claims: Option<&mut Claims>) -> g.aliased.insert(block); let mut covered = true; for other in others { - covered &= protect_alias(g, other / BLOCK, claims.as_deref_mut()); + match alias(g, other / BLOCK, claims.as_deref_mut()) { + Alias::ReadOnly => {} + Alias::Wanted => wanted.push((other / BLOCK, block)), + Alias::Not => covered = false, + } } if !covered { all = false; g.clean.remove(block); } } + for block in protect_aliases(g, wanted) { + all = false; + g.clean.remove(block); + } all } -/// Makes `block` read-only: another view of a page a copy is about to take -/// through its own, so that a write through this one faults too. It is not +/// What [`cover`] finds of another view's block. +enum Alias { + /// Read-only already, by our hand. + ReadOnly, + /// To be made read-only ([`protect_aliases`]). + Wanted, + /// It cannot be now: another changes it, or it is left alone. + Not, +} + +/// Whether blocks of other views that follow each other are made read-only +/// by one change of protection (`LEONIDA_ALIAS_RUNS=0`: a change a block, +/// as before). +/// +/// A range guarded with the other views of its pages ([`protect`], +/// [`protect_claimed`]) made each of those views' blocks read-only with a +/// change of its own: a call each, and each tells every core to forget the +/// page (232 blocks a frame, 6.7 ms, on an RTX 4060). A view shows the +/// range's pages in a row, so its blocks follow each other: one change a +/// run. A run that is not of one view (the change fails, and changes +/// nothing) is done block by block. +/// +/// What it takes for granted, as [`protect_here`] and [`unguard_runs`] do: +/// that the first block's protection speaks for the run. +fn alias_runs() -> bool { + crate::toggled!("LEONIDA_ALIAS_RUNS") +} + +/// Makes the other views' blocks of `wanted` read-only ([`alias_runs`]); +/// the blocks they cover that are not covered for it (one block may be +/// another's for several). +fn protect_aliases(g: &Guards, mut wanted: Vec<(usize, usize)>) -> Vec { + wanted.sort_unstable(); + let mut uncovered = Vec::new(); + let mut i = 0; + while i < wanted.len() { + let mut k = i + 1; + // (The same block twice is in the same run.) + while k < wanted.len() && (wanted[k].0 == wanted[k - 1].0 || alias_runs() && wanted[k].0 == wanted[k - 1].0 + 1) { + k += 1; + } + let failed = protect_alias_run(g, wanted[i].0, wanted[k - 1].0 + 1); + uncovered.extend(wanted[i..k].iter().filter(|w| failed.contains(&w.0)).map(|w| w.1)); + i = k; + } + uncovered +} + +/// Makes blocks `[from, to)` of another view read-only: by one change for +/// more than one ([`alias_runs`]), else each with [`protect_alias`]. The +/// blocks that are not read-only after. +fn protect_alias_run(g: &Guards, from: usize, to: usize) -> Vec { + use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; + let each = |from: usize, to: usize| (from..to).filter(|&block| !protect_alias(g, block)).collect::>(); + if to - from == 1 { + return each(from, to); + } + // Ahead of the protection. + (from..to).for_each(|block| PROTECTED.set(block)); + let mut old = 0; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + // SAFETY: title view memory; only its protection changes. + let done = unsafe { VirtualProtect((from * BLOCK) as *const _, (to - from) * BLOCK, PAGE_READONLY, &mut old) } != 0; + #[cfg(feature = "diagnostics")] + { + tally(5, (to - from) as u64); + tally(8, started.elapsed().as_nanos() as u64); + } + #[cfg(any(test, feature = "diagnostics"))] + ALIAS_RUNS[usize::from(!done)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if !done { + // Not of one view, or not all there: each for itself. + (from..to).for_each(|block| PROTECTED.clear(block)); + return each(from, to); + } + let mut failed = Vec::new(); + let mut first = from; + if !matches!(old, PAGE_READWRITE | PAGE_READONLY) { + // The first is other memory's, and keeps its protection. + // SAFETY: as it was. + unsafe { VirtualProtect((from * BLOCK) as *const _, BLOCK, old, &mut old) }; + PROTECTED.clear(from); + failed.push(from); + first = from + 1; + } + for block in first..to { + g.protected.insert(block); + #[cfg(feature = "diagnostics")] + crate::faultbook::note(crate::faultbook::What::Alias, block, 0, 0); + } + failed +} + +/// Diagnostics, since the start: runs of other views' blocks made read-only +/// by one change of protection ([`alias_runs`]), and runs it failed for. +#[cfg(any(test, feature = "diagnostics"))] +pub(crate) static ALIAS_RUNS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Of `block`, another view of a page a copy is about to take through its +/// own, whether it is read-only already, is to be made so, so that a write +/// through it faults too ([`protect_alias`]), or cannot be. It is not /// noted clean: the copies of title memory at this view have not taken the /// page ([`guard`] tells such a block as written, then notes it clean). /// One that is clean stays so: had the page been written since its copies -/// took it, [`open`] would have opened it. Whether it is read-only now. -fn protect_alias(g: &Guards, block: usize, claims: Option<&mut Claims>) -> bool { - use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; +/// took it, [`open`] would have opened it. +fn alias(g: &Guards, block: usize, claims: Option<&mut Claims>) -> Alias { if let Some(claims) = claims && !claims.holds(block) && !claims.try_one(block) { // Another changes it now (a fault opens it): not covered. - return false; + return Alias::Not; } g.aliased.insert(block); if g.protected.contains(block) { - return true; + return Alias::ReadOnly; } if g.left_alone(block) || g.rests(block, rest()) { - return false; + return Alias::Not; } + Alias::Wanted +} + +/// Makes `block` of another view read-only ([`alias`]): whether it is now. +fn protect_alias(g: &Guards, block: usize) -> bool { + use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; // Ahead of the protection. PROTECTED.set(block); let mut old = 0; @@ -5553,6 +5668,45 @@ mod tests { drop_views(section, &[guarded, other], SIZE); } + /// The blocks of another view of a guarded range are made read-only by + /// one change of protection, and a first block that is not as we left + /// it keeps its protection while the others are guarded. + /// (`LEONIDA_ALIAS_RUNS`.) + #[test] + fn another_views_blocks_are_guarded_by_one_change() { + use windows_sys::Win32::System::Memory::{PAGE_NOACCESS, PAGE_READONLY, VirtualProtect}; + const SIZE: usize = 4 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + // (Other tests make runs read-only meanwhile: at least ours.) + let runs = || [0, 1].map(|n| ALIAS_RUNS[n].load(std::sync::atomic::Ordering::Relaxed)); + let before = runs(); + assert_eq!(guard(guarded, guarded + SIZE), Some((0..4).map(pages).collect())); + assert!(runs()[0] > before[0], "the other view's four blocks were not made read-only by one change"); + for b in 0..4 { + assert_eq!(protection(other + b * BLOCK), PAGE_READONLY, "block {b}"); + assert!(PROTECTED.any(other / BLOCK + b, other / BLOCK + b + 1), "block {b}"); + } + drop_views(section, &[guarded, other], SIZE); + + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + let mut old = 0; + // SAFETY: the other view's first block. + assert_ne!(unsafe { VirtualProtect(other as *const _, BLOCK, PAGE_NOACCESS, &mut old) }, 0); + assert_eq!(guard(guarded, guarded + SIZE), Some((0..4).map(pages).collect())); + assert_eq!(protection(other), PAGE_NOACCESS, "not ours: as it was"); + assert!(!PROTECTED.any(other / BLOCK, other / BLOCK + 1)); + for b in 1..4 { + assert_eq!(protection(other + b * BLOCK), PAGE_READONLY, "block {b}"); + } + // The guarded block it covered is not clean: told as written again. + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0)])); + // SAFETY: as it was made. + assert_ne!(unsafe { VirtualProtect(other as *const _, BLOCK, PAGE_READWRITE, &mut old) }, 0); + drop_views(section, &[guarded, other], SIZE); + } + /// A write of the runtime's own, told at one view of the pages /// (`writing`): the other views' next checks report the pages written. #[test] From aa3a0328b8064c2b61e0c77df2e36241490ff588 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:05:32 +0100 Subject: [PATCH 2/2] d3d12: a run of alias blocks is made read-only at once only where it has one protection One change of protection answers with the first block's protection only, so a block in the middle of a run that was not as we leave guarded memory (no access, a guard page) was made read-only all the same; block by block each was looked at and kept its protection. A run now asks Windows first (VirtualQuery) and is changed at once only over the blocks that are one region of committed read-write or read-only memory; any other block is done on its own, as before. The test covers a block in the middle too. --- d3d12/crates/leonida-gpu/src/watch.rs | 71 ++++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 7 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/watch.rs b/d3d12/crates/leonida-gpu/src/watch.rs index f73cf1f746..ea0d1452e4 100644 --- a/d3d12/crates/leonida-gpu/src/watch.rs +++ b/d3d12/crates/leonida-gpu/src/watch.rs @@ -3330,15 +3330,54 @@ fn protect_aliases(g: &Guards, mut wanted: Vec<(usize, usize)>) -> Vec { uncovered } -/// Makes blocks `[from, to)` of another view read-only: by one change for -/// more than one ([`alias_runs`]), else each with [`protect_alias`]. The -/// blocks that are not read-only after. +/// Makes blocks `[from, to)` of another view read-only: those of one +/// protection that follow each other by one change ([`alias_runs`], +/// [`one_protection`]), the others each with [`protect_alias`]. The blocks +/// that are not read-only after. fn protect_alias_run(g: &Guards, from: usize, to: usize) -> Vec { + let mut failed = Vec::new(); + let mut at = from; + while at < to { + let end = if to - at > 1 { one_protection(at, to) } else { at }; + if end - at < 2 { + // Alone, or not as we leave guarded memory: as before. + if !protect_alias(g, at) { + failed.push(at); + } + at += 1; + continue; + } + failed.extend(protect_alias_span(g, at, end)); + at = end; + } + failed +} + +/// The end of the blocks from `from` (up to `to`) that are one region of +/// committed memory, read-write or read-only all of it: `from` if `from` is +/// not. One change of protection answers with the first block's protection +/// only; block by block each was looked at, and one that is not ours (no +/// access, a guard page, code) kept its protection. Asking first keeps it +/// so for a run too, without telling every core to forget the pages. +fn one_protection(from: usize, to: usize) -> usize { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READONLY, PAGE_READWRITE, VirtualQuery, + }; + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery((from * BLOCK) as *const _, &mut info, size_of_val(&info)) }; + if n == 0 || info.State != MEM_COMMIT || !matches!(info.Protect, PAGE_READWRITE | PAGE_READONLY) { + return from; + } + ((info.BaseAddress as usize).saturating_add(info.RegionSize) / BLOCK).clamp(from, to) +} + +/// [`protect_alias_run`] for blocks `[from, to)` of one protection, by one +/// change. +fn protect_alias_span(g: &Guards, from: usize, to: usize) -> Vec { use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; let each = |from: usize, to: usize| (from..to).filter(|&block| !protect_alias(g, block)).collect::>(); - if to - from == 1 { - return each(from, to); - } // Ahead of the protection. (from..to).for_each(|block| PROTECTED.set(block)); let mut old = 0; @@ -3361,7 +3400,8 @@ fn protect_alias_run(g: &Guards, from: usize, to: usize) -> Vec { let mut failed = Vec::new(); let mut first = from; if !matches!(old, PAGE_READWRITE | PAGE_READONLY) { - // The first is other memory's, and keeps its protection. + // The first is other memory's since it was asked about, and keeps + // its protection. // SAFETY: as it was. unsafe { VirtualProtect((from * BLOCK) as *const _, BLOCK, old, &mut old) }; PROTECTED.clear(from); @@ -5705,6 +5745,23 @@ mod tests { // SAFETY: as it was made. assert_ne!(unsafe { VirtualProtect(other as *const _, BLOCK, PAGE_READWRITE, &mut old) }, 0); drop_views(section, &[guarded, other], SIZE); + + // A block in the middle that is not as we left it keeps its + // protection too (one change answers for the first block only). + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + // SAFETY: the other view's third block. + assert_ne!(unsafe { VirtualProtect((other + 2 * BLOCK) as *const _, BLOCK, PAGE_NOACCESS, &mut old) }, 0); + assert_eq!(guard(guarded, guarded + SIZE), Some((0..4).map(pages).collect())); + assert_eq!(protection(other + 2 * BLOCK), PAGE_NOACCESS, "not ours: as it was"); + assert!(!PROTECTED.any(other / BLOCK + 2, other / BLOCK + 3)); + for b in [0, 1, 3] { + assert_eq!(protection(other + b * BLOCK), PAGE_READONLY, "block {b}"); + } + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(2)])); + // SAFETY: as it was made. + assert_ne!(unsafe { VirtualProtect((other + 2 * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }, 0); + drop_views(section, &[guarded, other], SIZE); } /// A write of the runtime's own, told at one view of the pages