Merge fork main 8dd30ab: writes through one view of a page are seen at its other views

The fork's guard over every view of a physical page is kept on our own block
bits, known holes, kernel writes and changing blocks; what both had, ours.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-25 00:38:57 -06:00
commit c45d109380
23 files changed
+4164 -221

No files matched your search

+22
View File
@@ -749,6 +749,22 @@ fn log_memory() {
let [textures, staging] = crate::pool::memory();
tracing::info!("memory in blocks (VICTORY_TEXTURE_POOL=0 turns them off): {textures} MB of textures, {staging} MB of their staging buffers");
}
let targets = crate::resource::targets_census();
tracing::info!(
"host copies the sweep never lets go: {} the host renders to or writes {:.0} MB ({} of them placed {:.0} MB); of them {} have title memory that is not mapped now {:.0} MB, {} were not used for 30 s and are held by no list and no slot {:.0} MB, {} are both {:.0} MB; and {} copies of textures the title fills that the host copied into {:.0} MB",
targets[0],
mb(targets[1]),
targets[10],
mb(targets[11]),
targets[2],
mb(targets[3]),
targets[4],
mb(targets[5]),
targets[6],
mb(targets[7]),
targets[8],
mb(targets[9]),
);
tracing::info!(
"memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \
{:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \
@@ -1128,6 +1144,12 @@ pub(crate) fn log(frames: f64) {
c[C::GpuWritesLeftOut as usize],
mb(c[C::GpuWritesLeftOutBytes as usize]),
);
let [together, written, mapped] =
[0, 1, 2].map(|n| crate::watch::ALIASES[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"
);
// Where the wall clock of a frame goes: the phases of a frame, the
// processor time of the whole process, and what each submitting and
// recording thread did.
+34 -10
View File
@@ -367,7 +367,11 @@ struct Views {
shape_index: std::collections::BTreeMap<Shape, u32>,
}
static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views {
/// Read far more often than written: every slot a draw reads through a
/// table is looked up here, on several recording threads at once in the
/// world. Readers share it; only a view not seen before (a new table entry
/// or shape) and a released resource take it alone.
static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views {
list: Vec::new(),
index: std::collections::BTreeMap::new(),
by_resource: std::collections::BTreeMap::new(),
@@ -494,6 +498,12 @@ impl Views {
Some(View::Placed(unordered, resource, desc))
}
/// The record words of `view` as a table entry, if it has one.
fn entry_of(&self, view: &View) -> Option<[u32; 2]> {
let &i = self.index.get(view)?;
Some([i, self.list[i as usize].1])
}
/// The record words of `view` as a table entry: its entry (a new or a
/// freed one if the view is not there yet) and that entry's generation.
fn entry(&mut self, view: View) -> [u32; 2] {
@@ -536,8 +546,10 @@ fn words_for(view: View) -> [u32; 2] {
View::Placed(unordered, resource, desc) => {
let (shape, address) = shape_of(*unordered, resource, desc);
if address >> PLACED_ADDRESS_BITS == 0 {
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
if let Some(shape) = views.shape(shape) {
// Nearly every placed view has a shape seen before.
let known = views_read().shape_index.get(&shape).copied();
let shape = known.or_else(|| views_write().shape(shape));
if let Some(shape) = shape {
NAMED_WHOLE[1].fetch_add(1, Relaxed);
return placed_words(shape, address);
}
@@ -546,7 +558,19 @@ fn words_for(view: View) -> [u32; 2] {
_ => {}
}
}
VIEWS.lock().unwrap_or_else(|e| e.into_inner()).entry(view)
// A view written before keeps its entry and generation.
if let Some(words) = views_read().entry_of(&view) {
return words;
}
views_write().entry(view)
}
fn views_read() -> std::sync::RwLockReadGuard<'static, Views> {
VIEWS.read().unwrap_or_else(|e| e.into_inner())
}
fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> {
VIEWS.write().unwrap_or_else(|e| e.into_inner())
}
/// For the memory line: the distinct views kept ([`Views`]), those of them
@@ -560,7 +584,7 @@ fn words_for(view: View) -> [u32; 2] {
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) fn views_kept() -> [u64; 8] {
use std::sync::atomic::Ordering::Relaxed;
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let views = views_read();
let each = size_of::<(View, u32)>() as u64;
let shape = size_of::<Shape>() as u64;
let (mut constants, mut placed) = (0, 0);
@@ -711,7 +735,7 @@ pub(crate) fn forget(resource: usize) {
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&resource);
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let mut views = views_write();
let Some(entries) = views.by_resource.remove(&resource) else {
return;
};
@@ -736,12 +760,12 @@ pub(crate) fn forget(resource: usize) {
fn view_at(i: u32, generation: u32) -> Option<View> {
match generation >> KIND_SHIFT {
0 => {
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let views = views_read();
let (view, current) = views.list.get(i as usize)?;
(*current == generation).then(|| view.clone())
}
CONSTANT => Some(constant_of(i, generation)),
PLACED => VIEWS.lock().unwrap_or_else(|e| e.into_inner()).placed_of(i, generation),
PLACED => views_read().placed_of(i, generation),
_ => None,
}
}
@@ -1118,8 +1142,8 @@ mod tests {
View::Placed(_, r, _) => *r == resource,
_ => false,
};
let entries = || VIEWS.lock().unwrap().list.iter().filter(|(v, _)| mine(v)).count();
let shapes = || VIEWS.lock().unwrap().shapes.iter().filter(|s| s.1 == resource).count();
let entries = || VIEWS.read().unwrap().list.iter().filter(|(v, _)| mine(v)).count();
let shapes = || VIEWS.read().unwrap().shapes.iter().filter(|s| s.1 == resource).count();
for n in 0..20_000u64 {
let address = 0x6_0000_0000 + n * 0x100;
create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at);
+507 -7
View File
@@ -85,7 +85,66 @@ pub(crate) struct HostHeap {
/// by slot and by address ([`Spans`]): which slots a newer view of
/// other memory there makes stale, and which to look at again when the
/// runtime maps, unmaps or writes memory ([`remapped`]).
placed: Mutex<Spans>,
placed: std::sync::Arc<Mutex<Spans>>,
}
/// The spans of every view heap made ([`HostHeap::placed`]), for the
/// texture code, which has no heap at hand ([`next_start`],
/// [`first_viewed`]).
static PLACED_SPANS: Mutex<Vec<std::sync::Weak<Mutex<Spans>>>> = Mutex::new(Vec::new());
/// Where the next texture placed inside `[start, end)` starts, past the
/// first bytes of the one at `start` ([`HEAD`]): what is there of the
/// texture at `start` ends there, whatever its full size. `None`: no view
/// in a slot shaders pick by index describes memory in that range.
pub(crate) fn next_start(start: u64, end: u64) -> Option<u64> {
let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner());
heaps
.iter()
.filter_map(std::sync::Weak::upgrade)
.filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).next_start(start, end))
.min()
}
/// The lowest level that a view of the placed texture at `start` shows,
/// over the slots shaders pick by index that hold one now. The title
/// views a texture from the first level it holds. `None`: no such slot.
pub(crate) fn first_viewed(start: u64) -> Option<u32> {
let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner());
heaps
.iter()
.filter_map(std::sync::Weak::upgrade)
.filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).first_viewed(start))
.min()
}
/// Levels on demand (`crate::tiles`): where the placed textures start
/// whose first level with memory changed since a texture pass last took
/// them ([`HostHeap::texture_views_remade`]).
static RESHOWN: Mutex<Vec<u64>> = Mutex::new(Vec::new());
/// The first level with memory of the placed texture at `start` changed:
/// its slots are made again at the next texture pass.
pub(crate) fn levels_changed(start: u64) {
RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).push(start);
}
/// Levels on demand (`crate::tiles`): where the placed textures start
/// whose last upload left a held level without tiles (the card had no
/// room, or no heap could be had), and when (`crate::host::moment`). A
/// texture pass makes their slots due again once the card has room
/// ([`HostHeap::texture_slots_waiting`]).
static WAITING: Mutex<std::collections::BTreeMap<u64, u64>> = Mutex::new(std::collections::BTreeMap::new());
/// The last upload of the placed texture at `start` left a held level
/// without tiles. A texture picked by index is uploaded once and then
/// only when its memory is found changed, and its staging buffer goes
/// with the upload: without this the level stayed empty (the texture
/// blurred, or black if no level had tiles) for as long as the title left
/// its memory alone, where a texture refused for want of room is tried
/// again.
pub(crate) fn levels_waiting(start: u64) {
WAITING.lock().unwrap_or_else(|e| e.into_inner()).insert(start, crate::host::moment());
}
/// Title memory by the placed texture views that describe it: per span of
@@ -110,6 +169,8 @@ pub(crate) struct Spans {
rule: Rule,
by_start: std::collections::BTreeMap<u64, (u64, std::collections::BTreeSet<u32>)>,
by_slot: std::collections::HashMap<u32, u64>,
/// The level each slot's view starts at ([`Spans::shows`]).
first: std::collections::HashMap<u32, u32>,
/// The bytes a placed texture takes, by resource description: worked
/// out once for each (a title writes the views of a few thousand
/// descriptions, thousands of times a frame).
@@ -227,8 +288,30 @@ impl Spans {
stale
}
/// The view in slot `index` starts at level `first` of its texture.
fn shows(&mut self, index: u32, first: u32) {
self.first.insert(index, first);
}
/// The lowest level a view of the texture at `start` starts at.
fn first_viewed(&self, start: u64) -> Option<u32> {
self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).min().copied()
}
/// The first span that starts inside `[start, end)` past the first
/// [`HEAD`] bytes of it.
fn next_start(&self, start: u64, end: u64) -> Option<u64> {
self.by_start.range(start.saturating_add(HEAD)..end).next().map(|(at, _)| *at)
}
/// The slots that hold a view of the texture at `start`.
fn slots_at(&self, start: u64) -> Vec<u32> {
self.by_start.get(&start).map(|span| span.1.iter().copied().collect()).unwrap_or_default()
}
/// Slot `index` holds no placed texture view any more.
fn forget(&mut self, index: u32) {
self.first.remove(&index);
let Some(start) = self.by_slot.remove(&index) else {
return;
};
@@ -248,6 +331,76 @@ impl Spans {
.flat_map(|span| span.1.iter().copied())
.collect()
}
/// The slots of the textures that hold bytes of `[start, end)`, for a
/// write there: as [`Spans::slots_in`], but when a texture starts at
/// `start` itself the one before it is left out (it ends where that
/// one starts, and a request that fills a texture begins at its first
/// byte: `slots_in` would name its neighbour with every such write).
fn slots_holding(&self, start: u64, end: u64) -> Vec<u32> {
if end <= start {
return Vec::new();
}
let before = if self.by_start.contains_key(&start) {
None
} else {
self.by_start.range(..start).next_back().filter(|(_, span)| span.0 > start).map(|(_, span)| span)
};
before
.into_iter()
.chain(self.by_start.range(start..end).map(|(_, span)| span))
.flat_map(|span| span.1.iter().copied())
.collect()
}
}
/// Title memory written behind the guards' back whose bytes are there
/// (DirectStorage's reads into physical pages, at the addresses the title
/// has them mapped; `crate::watch::title_memory_written`), since a texture
/// pass last took the ranges ([`page_written`]). Kept apart from
/// [`REMAPPED`] so that what such writes do is counted by itself.
static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
/// Since the start: such ranges kept for a pass; ranges dropped because no
/// pass took them; slots of placed textures that held bytes of them when a
/// pass took them; of those, the slots whose texture had been uploaded
/// before the write (out of the queue, or in it after an upload): they are
/// the ones that kept the bytes from before, and the ones made due when
/// `VICTORY_PAGE_WRITES` asks for it.
pub(crate) static PAGE_WRITES: [std::sync::atomic::AtomicU64; 4] =
[const { std::sync::atomic::AtomicU64::new(0) }; 4];
/// Frames from the pass that takes a written range to the look at its
/// slots: the levels of one texture arrive in a few requests, and a look
/// two frames on takes those of the next frame with it.
const PAGE_WRITE_AFTER: u64 = 2;
/// The bytes of a write the guards do not see are in title memory `[at,
/// at + len)`: the placed textures there changed with no descriptor
/// written and nothing mapped. Kept for the next texture pass
/// ([`HostHeap::texture_slots_page_written`]), as [`remapped`] keeps its
/// ranges; locks one mutex and calls nothing.
pub(crate) fn page_written(at: usize, len: usize) {
use std::sync::atomic::Ordering::Relaxed;
/// Ranges kept until a pass takes them.
const MOST: usize = 1 << 15;
let (start, end) = (at as u64, at.saturating_add(len) as u64);
if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) {
return;
}
let mut ranges = PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
PAGE_WRITES[0].fetch_add(1, Relaxed);
if let Some(last) = ranges.last_mut()
&& last.1 == start
{
last.1 = end;
return;
}
if ranges.len() >= MOST {
PAGE_WRITES[1].fetch_add(ranges.len() as u64, Relaxed);
ranges.clear();
}
ranges.push((start, end));
}
/// Title memory the runtime mapped, unmapped or is about to write since a
@@ -373,6 +526,10 @@ struct Waiting {
pub(crate) struct TextureQueue {
slots: std::collections::BTreeMap<u32, Waiting>,
writes: u64,
/// Slots held back because the card had no room for the host copy
/// they need ([`TextureQueue::hold`]), each with the write it was
/// held as.
held: std::collections::BTreeMap<u32, u64>,
}
impl TextureQueue {
@@ -449,6 +606,37 @@ impl TextureQueue {
}
}
/// The card has no room for the host copy slot `index` needs: it is
/// not handed out again before frame `due`, or before the card has
/// room again ([`TextureQueue::room`]). Nothing else of it changes: it
/// is not a slot "waiting for its memory", and when it is due it has
/// its old place among the slots never looked at. (It stayed due, so
/// every pass on a full card looked at the same few hundred slots
/// again and stopped there, and the slots behind them were never
/// reached: the ones whose host copy exists and only wants bringing up
/// to date, and the ones whose memory went, which is what lets host
/// copies go and makes room.)
fn hold(&mut self, index: u32, write: u64, due: u64) {
if let Some(w) = self.same(index, write) {
w.due = w.due.max(due);
self.held.insert(index, write);
}
}
/// The card has room again at `frame`: the slots held back for lack of
/// it are due now, as if they had never been held. Returns how many.
fn room(&mut self, frame: u64) -> usize {
let held = std::mem::take(&mut self.held);
let mut back = 0;
for (index, write) in held {
if let Some(w) = self.same(index, write) {
w.due = w.due.min(frame);
back += 1;
}
}
back
}
/// Slot `index` was uploaded with `mapped` bytes of its memory there,
/// not all of it: looked at again from frame `due`.
fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) {
@@ -770,7 +958,16 @@ impl HostHeap {
tabled: (0..if sampler { 0 } else { count })
.map(|_| std::sync::atomic::AtomicU32::new(0))
.collect(),
placed: Mutex::default(),
placed: {
let spans = std::sync::Arc::<Mutex<Spans>>::default();
if !sampler {
PLACED_SPANS
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(std::sync::Arc::downgrade(&spans));
}
spans
},
};
// A slot never written is undefined: shaders reading one (a slot
// the title wrote in a way we do not know, or a table entry no
@@ -985,6 +1182,16 @@ impl HostHeap {
textures.later(index, write, frame, most);
}
/// See [`TextureQueue::hold`].
pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) {
self.textures.lock().unwrap_or_else(|e| e.into_inner()).hold(index, write, due);
}
/// See [`TextureQueue::room`].
pub(crate) fn texture_slots_room(&self, frame: u64) -> usize {
self.textures.lock().unwrap_or_else(|e| e.into_inner()).room(frame)
}
/// Bytes of title slot `index`'s memory that were mapped when it was
/// last uploaded in part (0: not uploaded, or whole).
pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 {
@@ -1003,6 +1210,7 @@ impl HostHeap {
/// whose pass runs first takes them (a title has one view heap).
pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize {
use std::sync::atomic::Ordering::Relaxed;
self.texture_slots_page_written(frame);
let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner()));
if ranges.is_empty() {
return 0;
@@ -1022,6 +1230,54 @@ impl HostHeap {
slots.len()
}
/// Takes the ranges of title memory written behind the guards' back
/// since the last call ([`page_written`]) and finds the slots whose
/// placed texture holds bytes of them ([`Spans::slots_holding`]). A
/// slot whose texture was uploaded before the write shows the bytes
/// from before: with `VICTORY_PAGE_WRITES` (`crate::watch::page_writes`,
/// bit 2) it is due again [`PAGE_WRITE_AFTER`] frames on, as memory
/// mapped under it would make it ([`HostHeap::texture_slots_remapped`]);
/// its host copy exists, so the upload needs no room on the card. A
/// slot still waiting for its first upload is left as it is: that
/// upload takes the bytes that are there by then. Slots tables read
/// are left to their draws. Counted either way; returns how many slots
/// it made due.
fn texture_slots_page_written(&self, frame: u64) -> usize {
let ranges = std::mem::take(&mut *PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()));
if ranges.is_empty() {
return 0;
}
self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2]
}
/// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end):
/// the slots that held bytes of them, those of them uploaded before,
/// and those made due (the latter, if `due`).
fn slots_written_under(&self, ranges: &[(u64, u64)], frame: u64, due: bool) -> [usize; 3] {
use std::sync::atomic::Ordering::Relaxed;
let mut slots: Vec<u32> = {
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect()
};
slots.sort_unstable();
slots.dedup();
slots.retain(|&slot| !self.tabled_lately(slot, frame));
let held = slots.len();
let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
// Uploaded before: out of the queue, or in it after an upload (in
// part, or whole and being looked at again).
slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0));
PAGE_WRITES[2].fetch_add(held as u64, Relaxed);
PAGE_WRITES[3].fetch_add(slots.len() as u64, Relaxed);
if !due {
return [held, slots.len(), 0];
}
for &slot in &slots {
textures.changed(slot, frame, frame + PAGE_WRITE_AFTER);
}
[held, slots.len(), slots.len()]
}
/// Whether host slot `index` is made from the very record the title
/// has at `handle` now. Its host texture then exists (a slot keeps what
/// it views), so bringing that texture up to date takes no memory of
@@ -1052,6 +1308,101 @@ impl HostHeap {
.is_some_and(Option::is_some)
}
/// Levels on demand (`crate::tiles`): makes again the host slots of the
/// placed textures whose first level with memory changed since the
/// last call ([`levels_changed`]), each from the view it was made
/// from, so that it shows the texture from that level ([`make`]). Only
/// slots that are made; a slot draws read through a table is made by
/// its draw. Returns how many it made.
/// shortcut: the starts are kept in one place for all heaps; the heap
/// whose pass runs first takes them (a title has one view heap).
/// Levels on demand (`crate::tiles`): the card has room, so the slots
/// of up to [`Self::WAITING_A_PASS`] placed textures whose upload left
/// a held level without tiles at least a second ago
/// ([`levels_waiting`]) are due again from the next frame, as memory
/// mapped under them would make them
/// ([`HostHeap::texture_slots_remapped`]): the upload then gives the
/// level its tiles. To be called only while the card has room: without
/// it the upload would give nothing again. Slots tables read are left
/// to their draws (`texture.rs` `upload` asks again for those). Returns
/// how many slots it made due.
/// shortcut: kept in one place for all heaps, as the starts below.
pub(crate) fn texture_slots_waiting(&self, frame: u64) -> usize {
if self.sampler {
return 0;
}
let starts: Vec<u64> = {
let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner());
if waiting.is_empty() {
return 0;
}
let starts: Vec<u64> = waiting
.iter()
.filter(|&(_, &since)| crate::host::long_ago(since, 1000, 2))
.map(|(&start, _)| start)
.take(Self::WAITING_A_PASS)
.collect();
for start in &starts {
waiting.remove(start);
}
starts
};
if starts.is_empty() {
return 0;
}
let mut slots: Vec<u32> = {
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
};
slots.sort_unstable();
slots.dedup();
slots.retain(|&slot| !self.tabled_lately(slot, frame));
let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
for &slot in &slots {
textures.changed(slot, frame, frame + 1);
}
crate::tiles::STATS[10].fetch_add(slots.len() as u64, std::sync::atomic::Ordering::Relaxed);
slots.len()
}
/// Textures a pass asks again for their levels
/// ([`HostHeap::texture_slots_waiting`]): the first ones given tiles
/// may take the room the others were asked for, and an upload that
/// gives nothing is a whole texture staged and copied for nothing.
const WAITING_A_PASS: usize = 128;
pub(crate) fn texture_views_remade(&self) -> usize {
if self.sampler {
return 0;
}
let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner()));
if starts.is_empty() {
return 0;
}
let slots: Vec<u32> = {
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
};
let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
let mut remade = 0;
for slot in slots {
let Some(&key) = made.get(slot as usize) else {
continue;
};
if key == 0 {
continue;
}
let Some(view) = view_at(key as u32, (key >> 32) as u32) else {
continue;
};
if let Some(kept) = make(&view, self.cpu(slot)) {
self.keep(slot, kept);
remade += 1;
}
}
remade
}
/// The memory of the texture title slot `index` views is not mapped
/// (any more): a host slot made from it becomes null again, so that
/// the host copy can be let go (`crate::resource::let_go_idle`; a slot
@@ -1215,21 +1566,27 @@ impl HostHeap {
Some(View::Placed(false, resource, desc))
if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) =>
{
Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32))
// (And the level the view starts at: word 4 of a texture
// view's description, after format, dimension, mapping
// and a pad.)
Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32, desc[4]))
}
_ => None,
};
let stale = {
use std::sync::atomic::Ordering::Relaxed;
let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
let span = placed_view
.and_then(|(resource, start)| Some((start, start.saturating_add(placed.bytes(resource)?))));
let span = placed_view.and_then(|(resource, start, first)| {
Some((start, start.saturating_add(placed.bytes(resource)?), first))
});
match span {
Some((start, end)) => {
Some((start, end, first)) => {
SPANNED[0].fetch_min(start, Relaxed);
SPANNED[1].fetch_max(end, Relaxed);
placed.rule = stale_rule();
placed.note(index, start, end, !seen)
let stale = placed.note(index, start, end, !seen);
placed.shows(index, first);
stale
}
None => {
placed.forget(index);
@@ -2124,6 +2481,32 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> {
if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) {
return None;
}
// Levels on demand (`crate::tiles`): a texture made level by
// level is shown from the first level that is the title's
// and has memory, if the title's view starts before it (a
// level without memory reads zeros: a black texture). The
// title's own view mostly starts there already.
if let Some(first) = crate::resource::first_shown(resource)
&& first > 0
{
// SAFETY: a live resource.
let own = unsafe { texture.GetDesc() };
// The texture's own view (the title gave none): all of it.
let whole = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: own.Format,
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
Shader4ComponentMapping: 5768,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Texture2D: D3D12_TEX2D_SRV {
MostDetailedMip: 0,
MipLevels: u32::MAX,
PlaneSlice: 0,
ResourceMinLODClamp: 0.0,
},
},
};
crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels));
}
// SAFETY: a live texture and a slot of our heap.
unsafe {
device.CreateShaderResourceView(
@@ -2229,6 +2612,11 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> {
let len = u64::from(resource[4]) | u64::from(resource[5]) << 32;
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]);
// An empty title buffer: nothing to view, and no host copy to
// look for (#70: such views were in flight at device removals).
if len == 0 {
return None;
}
if *unordered {
buffer_uav(address, len, uav_desc(words), at)
} else {
@@ -2469,6 +2857,29 @@ mod tests {
assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D);
}
/// What the texture code asks of the spans (levels on demand): where
/// the next texture starts inside a span, the lowest level a view of a
/// texture shows, and a texture's slots.
#[test]
fn spans_say_the_next_start_and_the_lowest_level_viewed() {
let mut spans = Spans::default();
// A 512x512 texture of 0x56000 bytes viewed from levels 3 and 1,
// and the next one 0x6000 after it (run 188).
spans.note(1, 0x1_0000, 0x1_0000 + 0x5_6000, true);
spans.shows(1, 3);
spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true);
spans.shows(2, 1);
spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true);
assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000));
assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None);
assert_eq!(spans.first_viewed(0x1_0000), Some(1));
assert_eq!(spans.first_viewed(0x1_6000), None);
assert_eq!(spans.slots_at(0x1_0000), vec![1, 2]);
// The view from level 1 goes: the texture is viewed from level 3.
spans.forget(2);
assert_eq!(spans.first_viewed(0x1_0000), Some(3));
}
/// Views of one placed texture are told from views of others by the
/// address and the resource description, not by what they show.
#[test]
@@ -2615,6 +3026,38 @@ mod tests {
assert!(q.due(16, 100).iter().any(|d| d.0 == 98));
}
/// Slots held back for lack of room on the card are not handed out
/// until their frame, keep their place, are not counted as waiting
/// for their memory, and all come back at once when the card has room;
/// a slot written again meanwhile is the title's new write.
#[test]
fn slots_held_for_lack_of_room_come_back_when_there_is_room() {
let mut q = TextureQueue::default();
for i in 0..4u32 {
q.written(20 + i, 1, 0, false);
}
let due = q.due(1, 100);
assert_eq!(due.len(), 4);
// The card is full: slots 20 and 21 are held back until frame 101.
for &(index, write) in due.iter().filter(|d| d.0 < 22) {
q.hold(index, write, 101);
}
let now: Vec<u32> = q.due(2, 100).into_iter().map(|d| d.0).collect();
assert!(!now.contains(&20) && !now.contains(&21));
assert!(now.contains(&22) && now.contains(&23));
assert_eq!(q.census(2)[2], 0, "held slots do not wait for their memory");
// Due again at their frame, in the order they had.
assert_eq!(q.due(101, 100), due);
// Slot 21 is written again while held: due as written.
q.written(21, 3, 0, false);
assert!(q.due(3, 100).iter().any(|d| d.0 == 21));
// Room again at frame 5: slot 20 is due at once, and only it was
// still held as it was.
assert_eq!(q.room(5), 1);
assert!(q.due(5, 100).iter().any(|d| d.0 == 20));
assert_eq!(q.room(6), 0);
}
/// Textures of which only the smallest levels are held, packed into
/// one another's address range (the three of run 188: 0x2c000 bytes
/// each at full size, their starts 0x2000 and 0x4000 apart): writing
@@ -2708,6 +3151,63 @@ mod tests {
assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]);
}
/// A write names the textures that hold its bytes: the one that
/// starts where the write starts, not the neighbour before it, whose
/// held levels end there.
#[test]
fn a_write_at_the_start_of_a_packed_texture_names_it_alone() {
let mut spans = Spans::default();
let at = 0x7_0000_0000u64;
assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty());
// A request that fills the second texture's held levels.
assert_eq!(spans.slots_in(at + 0x2000, at + 0x6000), [1, 2]);
assert_eq!(spans.slots_holding(at + 0x2000, at + 0x6000), [2]);
// From inside the first one's held levels on: both.
assert_eq!(spans.slots_holding(at + 0x1000, at + 0x3000), [1, 2]);
// A whole 64 KiB page: every texture that starts in it.
assert_eq!(spans.slots_holding(at, at + 0x10000), [1, 2, 3]);
// Past the last start, the last one; past all, or no bytes, none.
assert_eq!(spans.slots_holding(at + 0x20000, at + 0x21000), [3]);
assert_eq!(spans.slots_holding(at + 0x32000, at + 0x33000), [] as [u32; 0]);
assert_eq!(spans.slots_holding(at + 0x2000, at + 0x2000), [] as [u32; 0]);
}
/// A write behind the guards' back under a placed texture: a slot
/// waiting for its first upload is left alone, one uploaded before is
/// counted, and made due two frames on when that is asked for. (The
/// ranges are handed over here, not through the list all heaps share.)
#[test]
fn a_page_write_makes_an_uploaded_texture_slot_due_when_asked() {
let Some(heap) = HostHeap::new(false, 8) else {
return; // no host GPU
};
let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
// 64x64 BC7, one mip, at an address no test and no title uses.
let at = 0x7fed_0000_0000u64;
let mut desc = [0u32; 16];
(desc[10], desc[11]) = (at as u32, (at >> 32) as u32);
let view = View::Placed(false, [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc);
assert!(heap.note_buffer(1, Some(&view), false).is_empty());
let written = [(at, at + 0x1000)];
// Waiting for its first upload: held, not uploaded, nothing done.
assert_eq!(heap.slots_written_under(&written, 50, true), [1, 0, 0]);
let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0];
assert_eq!(queued, 1);
heap.texture_slot_done(1, write, None);
assert_eq!(slots(u64::MAX), []);
// Uploaded and out of the queue. Memory elsewhere: nothing.
assert_eq!(heap.slots_written_under(&[(at + 0x10_0000, at + 0x10_1000)], 60, true), [0, 0, 0]);
// Under it, counted only: it stays out of the queue.
assert_eq!(heap.slots_written_under(&written, 60, false), [1, 1, 0]);
assert_eq!(slots(u64::MAX), []);
// Under it, asked for: due two frames on, not before.
assert_eq!(heap.slots_written_under(&written, 60, true), [1, 1, 1]);
assert_eq!(slots(61), []);
assert_eq!(slots(62), [1]);
}
/// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that
/// overlaps others is left out of the spans, as before.
#[test]
+46 -5
View File
@@ -571,6 +571,20 @@ pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0),
/// new ones, since the start.
pub(crate) static HEAP_TEXTURES_REUPLOADED_FULL: AtomicU64 = AtomicU64::new(0);
/// Whether a pass over the textures picked by index on a full card holds
/// back the slots that need a new host copy (`VICTORY_FULL_CARD_PASS=0`:
/// no, as before: they stay due, each pass looks at the same ones again
/// and stops at the 257th). Held back, such a slot is looked at again
/// after about four seconds or as soon as the card has room, and the pass
/// goes on to the slots behind it: the ones whose host copy exists and
/// only wants bringing up to date, and the ones whose memory went (letting
/// their host copies go is what makes room). What is uploaded while the
/// card has room is the same either way.
fn full_card_pass() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_FULL_CARD_PASS").is_none_or(|v| v != "0"))
}
/// Whether a texture that has its host copy is still brought up to date
/// while the card has no room for new ones (`VICTORY_REUPLOAD_WHEN_FULL=0`:
/// no).
@@ -1802,7 +1816,10 @@ impl State {
static NEXT: AtomicU64 = AtomicU64::new(0);
let now = crate::host::now_ms().max(1);
let next = NEXT.load(Ordering::Relaxed);
let due_now = if next == 0 { !room } else { now >= next };
// (With levels on demand the card may never be without room: the
// lines then start with the first texture made that way.)
let by_level = crate::tiles::STATS[4].load(Ordering::Relaxed) > 0;
let due_now = if next == 0 { !room || by_level } else { now >= next };
if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() {
return;
}
@@ -1906,9 +1923,22 @@ impl State {
once!("textures picked by index: the card has no room for more; they wait");
}
let mut refused = 0;
// Room again: the slots held back while the card was full are due
// now (`full_card_pass`).
if room {
host.texture_slots_room(frame);
}
// Slots whose texture's memory the runtime mapped, unmapped or
// wrote since the last pass are due again.
host.texture_slots_remapped(frame);
// Levels on demand: the slots of textures whose first level with
// memory changed since the last pass are made again from it.
host.texture_views_remade();
// And with room, the textures whose upload left a held level
// without the card's memory are uploaded again.
if room {
host.texture_slots_waiting(frame);
}
let (due, census) = host.texture_slots_due(frame, 4096);
HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed);
for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) {
@@ -2063,7 +2093,15 @@ impl State {
&& heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle));
if !has_its_texture {
refused += 1;
if refused > 256 {
if full_card_pass() {
// Held back for the frames of about four seconds
// (`most`), or until the card has room; the pass
// goes on, within a count that bounds one pass.
host.texture_slot_held(index, write, frame + most);
if refused > 1024 {
break;
}
} else if refused > 256 {
break;
}
continue;
@@ -3559,13 +3597,16 @@ fn view_state(view: Option<&View>) -> String {
memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0))
),
};
format!("placed texture view_format={} {state}", d[0])
// (Last, so that readers of the older lines still find
// theirs: the level the view starts at, and how many it shows.)
format!("placed texture view_format={} {state} view_levels={}+{}", d[0], d[4], d[5] as i32)
}
Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => {
format!(
"texture object {r:#x} view_format={} {}",
"texture object {r:#x} view_format={} {} view_levels={}",
d.as_ref().map_or(0, |d| d[0]),
texture_state(*r as This)
texture_state(*r as This),
d.as_ref().map_or("all".to_owned(), |d| format!("{}+{}", d[4], d[5] as i32))
)
}
Some(v) => format!("{v:?}").chars().take(80).collect(),
+24 -2
View File
@@ -682,7 +682,7 @@ fn create() -> windows::core::Result<Host> {
/// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
/// Reject it before creating a device in diagnostics' software-only mode.
fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
// SAFETY: plain DXGI adapter queries.
unsafe {
let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
@@ -3127,7 +3127,8 @@ fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
/// ([`read_backs`]), the frame's main pass by scissor rectangle with its
/// culling dispatches (`draw.rs`, `walls_census`), the shader-written
/// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
/// copies found stale after their refresh (`shadow.rs`), and, in the
/// copies found stale after their refresh (`shadow.rs`; only with
/// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the
/// runtime, the read requests that fail (with 2: every request).
pub(crate) fn walls_trace() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
@@ -6829,6 +6830,13 @@ fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, us
}
impl Host {
/// The queue everything of ours runs on, for a call that must go to it
/// in order with the lists (`crate::tiles`: a texture's levels are
/// given memory ahead of the list that uploads them).
pub(crate) fn queue(&self) -> &ID3D12CommandQueue {
&self.queue
}
/// A buffer in the upload heap, mapped for writing.
/// A buffer of `size` bytes the card writes and we read (a read back),
/// in the state copies into it need.
@@ -7078,6 +7086,7 @@ impl Meter {
"placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
);
crate::tiles::status();
{
let [queued, due, away, partly, oldest] =
[0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
@@ -7101,6 +7110,19 @@ impl Meter {
crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
);
}
{
let mode = crate::watch::page_writes();
let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed));
let [kept, dropped, slots, uploaded] =
[0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed));
tracing::info!(
"writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset counts, 1 acts, guards, slots, all)",
bytes >> 20,
if mode & 1 != 0 { "opened, taken again" } else { "left as they were" },
if mode & 4 != 0 { "told as well" } else { "counted only" },
if mode & 2 != 0 { "made due again" } else { "left as they were" }
);
}
#[cfg(feature = "diagnostics")]
tracing::info!(
"write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
+116 -3
View File
@@ -267,6 +267,13 @@ pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size:
struct Views {
/// By address: bytes, the section's handle, the offset in it.
views: BTreeMap<usize, (usize, usize, u64)>,
/// By section and byte offset of a 64 KiB page: the address of that
/// page in every view that shows it. A write through one view of a
/// page is a write of the bytes every other view shows
/// (`crate::watch` guards them all).
pages: BTreeMap<(usize, u64), Vec<usize>>,
/// Of those, how many are shown more than once.
pages_twice: usize,
/// Sections by handle: bytes, and whether made committed.
sections: Vec<(usize, u64, bool)>,
/// Our own view of a whole section, by its handle (0: the host gave
@@ -274,7 +281,13 @@ struct Views {
whole: Vec<(usize, usize)>,
}
static VIEWS: Mutex<Views> = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new(), whole: Vec::new() });
static VIEWS: Mutex<Views> = Mutex::new(Views {
views: BTreeMap::new(),
pages: BTreeMap::new(),
pages_twice: 0,
sections: Vec::new(),
whole: Vec::new(),
});
fn views() -> std::sync::MutexGuard<'static, Views> {
VIEWS.lock().unwrap_or_else(|e| e.into_inner())
@@ -310,7 +323,20 @@ pub fn title_memory_section_gone(section: usize) {
/// The runtime mapped `[at, at + len)` as a view of `section` from
/// `offset` on. Call after [`crate::title_memory_remapped`] of the range.
pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) {
views().views.insert(at, (len, section, offset));
{
let mut v = views();
v.views.insert(at, (len, section, offset));
for k in 0..len.div_ceil(K64) {
let shown = v.pages.entry((section, offset + (k * K64) as u64)).or_default();
shown.push(at + k * K64);
let twice = shown.len() == 2;
v.pages_twice += usize::from(twice);
}
}
// This view is writable from now on: a guard over the same bytes at
// another view must look at them again, and the pages are noted written
// there (`crate::watch`).
crate::watch::views_mapped(section, offset, len);
}
/// What `[at, at + len)` showed is gone ([`crate::title_memory_remapped`]):
@@ -325,10 +351,97 @@ pub(crate) fn views_gone(at: usize, len: usize) {
let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base);
let gone: Vec<usize> = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect();
for base in gone {
v.views.remove(&base);
let Some((bytes, section, offset)) = v.views.remove(&base) else {
continue;
};
for k in 0..bytes.div_ceil(K64) {
let key = (section, offset + (k * K64) as u64);
if let Some(pages) = v.pages.get_mut(&key) {
let page = base + k * K64;
let before = pages.len();
pages.retain(|&shown| shown != page);
let after = pages.len();
if after == 0 {
v.pages.remove(&key);
}
v.pages_twice = v.pages_twice.saturating_sub(usize::from(before >= 2 && after < 2));
}
}
}
}
/// The 64 KiB pages of `[start, end)` that the title shows at other
/// addresses too, in address order, each with those; not the ones it shows
/// in very many views (`crate::watch::MANY_VIEWS`).
pub(crate) fn shown_elsewhere(start: usize, end: usize) -> Vec<(usize, Vec<usize>)> {
let v = views();
let mut out = Vec::new();
if start >= end || v.pages_twice == 0 {
return out;
}
let first = v.views.range(..=start).next_back().filter(|(base, view)| *base + view.0 > start).map(|(base, _)| *base);
for (&base, &(bytes, section, offset)) in v.views.range(first.unwrap_or(start)..end) {
let from = start.max(base) & !(K64 - 1);
for page in (from..end.min(base + bytes)).step_by(K64) {
let Some(shown) = v.pages.get(&(section, offset + (page - base) as u64)) else {
continue;
};
if (2..=crate::watch::MANY_VIEWS).contains(&shown.len()) {
out.push((page, shown.iter().copied().filter(|&at| at != page).collect()));
}
}
}
out
}
/// The address of the 64 KiB page shown at `page` in every title view that
/// shows it, `page`'s own address included; empty if `page` is not a view.
pub(crate) fn pages_of(page: usize) -> Vec<usize> {
let v = views();
let Some((&base, &(bytes, section, offset))) = v.views.range(..=page).next_back() else {
return Vec::new();
};
let within = page.wrapping_sub(base);
if within >= bytes || !within.is_multiple_of(K64) {
return Vec::new();
}
v.pages.get(&(section, offset + within as u64)).cloned().unwrap_or_default()
}
/// The title views that show any of the physical bytes `[offset, offset +
/// len)` of `section`, as `(address, bytes)` ranges in address order; not
/// those of a page shown in very many views (`MANY_VIEWS`).
pub(crate) fn views_of_section(section: usize, offset: u64, len: usize) -> Vec<(usize, usize)> {
if len == 0 {
return Vec::new();
}
let v = views();
let end = offset.saturating_add(len as u64);
let mut pages: Vec<usize> = Vec::new();
let mut at = offset - offset % K64 as u64;
while at < end {
if let Some(shown) = v.pages.get(&(section, at))
&& shown.len() <= crate::watch::MANY_VIEWS
{
pages.extend(shown.iter().copied());
}
match at.checked_add(K64 as u64) {
Some(next) => at = next,
None => break,
}
}
pages.sort_unstable();
pages.dedup();
let mut runs: Vec<(usize, usize)> = Vec::with_capacity(pages.len());
for page in pages {
match runs.last_mut() {
Some((first, bytes)) if *first + *bytes == page => *bytes += K64,
_ => runs.push((page, K64)),
}
}
runs
}
/// How many bytes of `[at, at + len)` views of physical pages show; `None`
/// if no view touches it (nothing is mapped there, or memory of another
/// kind). The runtime's own record of what it mapped: no question to the
+4 -1
View File
@@ -60,6 +60,8 @@ pub mod shader_cache;
mod memory;
#[cfg(windows)]
mod shadow;
#[cfg(windows)]
mod tiles;
pub mod signature;
#[cfg(windows)]
mod texture;
@@ -73,5 +75,6 @@ pub use inplace::{title_memory_freeing, title_memory_section, title_memory_secti
#[cfg(windows)]
pub use watch::{
kernel_writing, title_memory_allocated, title_memory_freed, title_memory_reading, title_memory_remapped,
title_memory_remapping, title_memory_unmapping, writing as kernel_will_write,
title_memory_remapping, title_memory_splitting, title_memory_unmapping, title_memory_written,
writing as kernel_will_write,
};
+10
View File
@@ -864,6 +864,9 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) {
// Depth textures shaders also write: what they wrote, first.
list.twin_use(dst, false, true);
list.twin_use(src, false, false);
// A destination made level by level gets its levels' memory
// ahead of this list (`crate::tiles`).
crate::texture::card_writes(list, dst, to, None);
ensure_state(list, dst, COPY_DEST);
ensure_state(list, src, COPY_SOURCE);
crate::texture::host_written(dst);
@@ -997,6 +1000,11 @@ extern "system" fn copy_texture_region(
// A depth texture shaders also write: what they wrote, first (the
// source above too).
list.twin_use(dst.resource, false, true);
// A destination made level by level gets the level's memory ahead
// of this list (`crate::tiles`): the title's bake copies each level
// of its result into a block-compressed texture of that kind, and
// a copy into a level without memory is dropped.
crate::texture::card_writes(list, dst.resource, to, Some(dst.footprint.offset as u32));
ensure_state(list, dst.resource, COPY_DEST);
crate::texture::host_written(dst.resource);
let mut to_location = dst;
@@ -1150,6 +1158,8 @@ extern "system" fn resolve(
// Depth textures shaders also write: what they wrote, first.
list.twin_use(dst, false, true);
list.twin_use(src, false, false);
// As for a copy (`crate::tiles`).
crate::texture::card_writes(list, dst, to, Some(dst_sub));
ensure_state(list, dst, RESOLVE_DEST);
ensure_state(list, src, RESOLVE_SOURCE);
crate::texture::host_written(dst);
+287 -27
View File
@@ -244,22 +244,24 @@ pub(crate) fn pc_format(format: u32) -> u32 {
/// (NVIDIA) refused the whole texture, so every pass that wrote it drew
/// nothing. There 8-bit RGBA stands in: the same channels in the same
/// order, every 4-bit level exact and every 5-bit level within 1/510.
/// The title also renders to R9G9B9E5 (67), which no PC GPU does: 16-bit
/// float RGBA stands in, with at least R9G9B9E5's precision and range.
/// The title's pipelines and views of such targets name the stand-in too
/// ([`view_format`], the host view checks).
/// shortcut: copies between such a target and a texture the title fills
/// itself in the 16-bit format are skipped ([`stands_in`]); convert them
/// if a pass turns out to need one.
pub(crate) fn target_format(format: u32) -> u32 {
const STAND_INS: [(u32, u32); 2] = [(86, 28), (115, 28)];
const STAND_INS: [(u32, u32); 3] = [(86, 28), (115, 28), (67, 10)];
let Some(i) = STAND_INS.iter().position(|&(f, _)| f == format) else {
return format;
};
#[cfg(windows)]
{
use windows::Win32::Graphics::Direct3D12::*;
static REFUSED: std::sync::OnceLock<[bool; 2]> = std::sync::OnceLock::new();
static REFUSED: std::sync::OnceLock<[bool; 3]> = std::sync::OnceLock::new();
let refused = REFUSED.get_or_init(|| {
STAND_INS.map(|(f, _)| {
STAND_INS.map(|(f, to)| {
let Some(host) = crate::host::host() else {
return false;
};
@@ -279,7 +281,7 @@ pub(crate) fn target_format(format: u32) -> u32 {
| D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0;
let refused = asked.is_err() || support.Support1.0 & both != both;
if refused {
tracing::info!(format = f, "the host does not render to this format: 8-bit RGBA stands in");
tracing::info!(format = f, stand_in = to, "the host does not render to this format: a stand-in is used");
}
refused
})
@@ -1131,6 +1133,10 @@ pub(crate) struct HostTexture {
/// Whether its contents come from title memory ([`fills`]): counted in
/// [`KINDS`] while it lives.
filled: bool,
/// Made without memory of its own (`crate::tiles`): the tiles its
/// levels have been given. Its `bytes` are 0: what it holds of the card
/// is counted there.
pub(crate) tiled: Option<crate::tiles::Tiled>,
}
/// What a title texture has on the host: its host copy and, for a depth
@@ -1309,7 +1315,49 @@ fn hosted(this: This, make: bool) -> Option<Made> {
.clear
.as_ref()
.map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast::<c_void>());
let Some(texture) = host_texture(&r.desc, r.host.state, clear) else {
// Levels on demand (`crate::tiles`): a texture the title places in
// memory and fills, of a megabyte or more, that does not hold all
// its levels now, is made without memory and given it level by
// level. It does not hold them all if its memory is not all
// mapped, if the next texture starts inside its span, or if a
// view of it starts below level 0. Every other texture, and this
// one if the card will not have it so, is made as before.
const TEXTURE_2D: u32 = 3;
let mut tiled = None;
let mut texture = None;
let shape_fits = fills(&r.desc)
&& r.desc.dimension == TEXTURE_2D
&& r.desc.depth_or_array_size == 1
&& r.desc.mip_levels > 1
&& r.desc.sample_count <= 1;
if shape_fits && r.host.placed.load(Relaxed) && crate::tiles::wanted() {
let bytes = footprint(&r.desc).map_or(0, |f| f.size);
let start = r.data() as u64;
// What the upload can read: a console layout, no XOR mode
// (`crate::texture` `staging`).
let readable = texture_layout(&r.desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor());
let partly = readable
&& bytes >= crate::tiles::floor()
&& (!crate::texture::committed(r.data().cast_const(), bytes as usize)
|| crate::descriptor::host::next_start(start, start.saturating_add(bytes)).is_some()
|| crate::descriptor::host::first_viewed(start).is_some_and(|first| first > 0));
let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true) } else { None };
let cut = reserved
.as_ref()
.zip(crate::host::host())
.and_then(|(t, host)| crate::tiles::Tiled::make(&host.device, t, u32::from(r.desc.mip_levels)));
// (Both or neither: a reserved texture the card will not cut
// into tiles is dropped here, and the old kind is made below.)
if cut.is_some() {
tiled = cut;
texture = reserved;
}
}
let texture = match texture {
Some(texture) => Some(texture),
None => host_texture(&r.desc, r.host.state, clear),
};
let Some(texture) = texture else {
r.host.refused.store(true, Relaxed);
return None;
};
@@ -1326,7 +1374,10 @@ fn hosted(this: This, make: bool) -> Option<Made> {
);
}
let state = crate::host::legal_state(&texture, crate::host::texture_state(r.host.state));
let mut host = HostTexture::new(texture, state);
let mut host = match tiled {
Some(tiled) => HostTexture::new_tiled(texture, state, tiled),
None => HostTexture::new(texture, state),
};
host.filled = fills(&r.desc);
if host.filled {
KINDS[0].fetch_add(1, Relaxed);
@@ -1388,7 +1439,9 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool {
let mb = std::env::var("VICTORY_TEXTURE_BUDGET_MB").ok()?;
mb.trim().parse::<u64>().ok().map(|mb| mb << 20)
});
let filled = KINDS[1].load(Relaxed);
// (With the tiles of the copies made level by level, whose own bytes
// count as none: `crate::tiles`.)
let filled = KINDS[1].load(Relaxed) + crate::tiles::given_total();
if let Some(limit) = limit {
return filled < limit;
}
@@ -1397,11 +1450,31 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool {
return true;
}
match memory {
Some([budget, used, ..]) => used < budget / 100 * room_percent(),
// What is kept for card copies of title buffers not made yet
// counts as used (`crate::shadow::card_room_kept`; 0 by default).
Some([budget, used, ..]) => used + crate::shadow::card_room_kept() < budget / 100 * room_percent(),
None => filled < WITHOUT_BUDGET,
}
}
/// [`room`] as it was at most a tenth of a second ago, for a question
/// asked of many textures a frame ([`room`] asks the system each time).
#[cfg(windows)]
pub(crate) fn room_lately() -> bool {
use std::sync::atomic::Ordering::Relaxed;
// The tenth of a second of the last asking, counted from 1, and its
// answer in the lowest bit.
static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let tenth = crate::host::now_ms() / 100 + 1;
let last = LAST.load(Relaxed);
if last >> 1 == tenth {
return last & 1 != 0;
}
let room = room(crate::host::host().and_then(|h| h.video_memory()));
LAST.store((tenth << 1) | u64::from(room), Relaxed);
room
}
/// The share of the card's budget, in percent, up to which host copies of
/// textures picked by index are made ([`room`]): 90 unless
/// `VICTORY_TEXTURE_ROOM_PERCENT` says another (50 to 97). At 90 about a
@@ -1492,7 +1565,8 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>,
return;
}
let began = std::time::Instant::now();
let mut copies: Vec<(usize, ResourceDesc, u64)> = Vec::new();
// (The last: made level by level, its bytes are those of its tiles.)
let mut copies: Vec<(usize, ResourceDesc, u64, bool)> = Vec::new();
// Textures the title fills without a host copy: never one, one let go.
let mut without = [0u64; 2];
{
@@ -1505,7 +1579,10 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>,
}
let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
match made.as_ref() {
Some((host, _)) => copies.push((r.data() as usize, r.desc, host.bytes)),
Some((host, _)) => copies.push(match &host.tiled {
Some(tiled) => (r.data() as usize, r.desc, tiled.given_bytes(), true),
None => (r.data() as usize, r.desc, host.bytes, false),
}),
None => without[usize::from(r.host.gone.load(Relaxed))] += 1,
}
}
@@ -1526,9 +1603,16 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>,
// a level not mapped; with the largest level not mapped; with no
// level mapped; copies without a console layout (not asked).
let mut c = [0u64; 7];
for &(memory, desc, bytes) in &copies {
// Of the copies: made level by level, and the bytes of their tiles.
let mut on_demand = [0u64; 2];
for &(memory, desc, bytes, by_level) in &copies {
c[0] += 1;
c[1] += bytes;
if by_level {
on_demand[0] += 1;
on_demand[1] += bytes;
continue;
}
let Some(layout) = texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else {
c[6] += 1;
continue;
@@ -1605,6 +1689,7 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>,
[gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]];
let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]];
let walk_ms = began.elapsed().as_millis() as u64;
let [by_level_n, by_level_mb] = [on_demand[0], on_demand[1] >> 20];
tracing::info!(
"card accounting: room {room}, the card {used_mb} MB in use of a budget of {budget_mb} MB; host copies of textures the title \
fills: {copies_n} alive {copies_mb} MB, of which {unmapped_mb} MB are levels whose title memory is not mapped ({partly} copies \
@@ -1615,7 +1700,8 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>,
all mapped {never_whole_mb} MB, {never_part} in part {never_part_mb} MB mapped, {never_none} not mapped); {gone_n} whose host \
copy was let go ({gone_mb} MB: {gone_whole} all mapped {gone_whole_mb} MB, {gone_part} in part {gone_part_mb} MB mapped, \
{gone_none} not mapped); since the line before: {let_go} host copies let go {let_go_mb} MB, {again} made again {again_mb} MB, \
{made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own"
{made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own; of the host \
copies {by_level_n} are made level by level and hold {by_level_mb} MB of tiles (in the MB alive, not in the levels not mapped)"
);
WALKING.store(false, Relaxed);
};
@@ -1706,6 +1792,66 @@ pub(crate) fn let_go_idle() {
}
}
/// For the memory line: the host copies the sweep never lets go
/// ([`let_go_idle`] takes only copies of textures the title fills that the
/// host never copied into), by what would say they are dead weight. A
/// count and the bytes (twins included) of: the copies the host renders to
/// or writes; of them, those whose title memory is not mapped now (its
/// first page); those nothing has used for 30 seconds and 60 frames and
/// that no list and no slot holds; those that are both; the copies of
/// textures the title fills that the host copied into; and, of the first,
/// the placed ones. Render-target copies grew from 2,319 MB at the world's
/// first frame to 3,075 MB 150 s later in run 197 and never shrank, while
/// 26,517 copies of filled textures were let go to stay under the card's
/// line.
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) fn targets_census() -> [u64; 12] {
use std::sync::atomic::Ordering::Relaxed;
let mut c = [0u64; 12];
let all = textures();
for &at in all.iter() {
// SAFETY: as in `let_go_idle`.
let r = unsafe { &*(at as *const Resource) };
let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
let Some((host, twin)) = made.as_ref() else {
continue;
};
let copied_into = host.filled && crate::texture::host_wrote(at);
if host.filled && !copied_into {
continue;
}
let bytes = host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes);
let mut add = |i: usize| {
c[i] += 1;
c[i + 1] += bytes;
};
if copied_into {
add(8);
continue;
}
add(0);
let placed = r.host.placed.load(Relaxed);
// Its first page: what is there of a texture starts there.
let unmapped = placed && !crate::texture::committed(r.data().cast_const(), 1);
let idle = crate::host::long_ago(r.host.used.load(Relaxed), 30_000, 60)
&& std::sync::Arc::strong_count(host) == 1
&& crate::host::references(&host.texture) == 1;
if unmapped {
add(2);
}
if idle {
add(4);
}
if unmapped && idle {
add(6);
}
if placed {
add(10);
}
}
c
}
/// For the memory line: title textures with a host copy the host renders
/// to or writes and those copies' bytes (twins included); title textures
/// without a host copy and the bytes of title memory they are; host copies
@@ -1790,6 +1936,24 @@ impl HostTexture {
state: std::sync::atomic::AtomicU32::new(state),
bytes,
filled: false,
tiled: None,
}
}
/// A texture made without memory of its own (`crate::tiles`): counted
/// as a host texture of no bytes.
fn new_tiled(
texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource,
state: u32,
tiled: crate::tiles::Tiled,
) -> HostTexture {
HOST_TEXTURES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
HostTexture {
texture,
state: std::sync::atomic::AtomicU32::new(state),
bytes: 0,
filled: false,
tiled: Some(tiled),
}
}
}
@@ -1861,6 +2025,18 @@ fn host_texture(
desc: &ResourceDesc,
state: u32,
clear: *const c_void,
) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
host_texture_as(desc, state, clear, false)
}
/// [`host_texture`]; `reserved`: without memory of its own, to be given
/// tiles level by level (`crate::tiles`).
#[cfg(windows)]
fn host_texture_as(
desc: &ResourceDesc,
state: u32,
clear: *const c_void,
reserved: bool,
) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
use windows::Win32::Graphics::Direct3D12::*;
const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access
@@ -1937,23 +2113,40 @@ fn host_texture(
return Some(t);
}
let mut texture: Option<ID3D12Resource> = None;
// SAFETY: the description has the host layout (checked size, same
// fields); the out pointer is ours.
let made = unsafe {
host.device.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
(&raw const d).cast(),
D3D12_RESOURCE_STATES(
crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
),
// The same layout: format, then color or depth and stencil.
clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()),
&mut texture,
)
let made = if reserved {
// The card's own layout of 64 KiB tiles, which a reserved texture
// must have.
d.layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE.0 as u32;
// SAFETY: as below; a texture the title fills has no clear value.
unsafe {
host.device.CreateReservedResource(
(&raw const d).cast(),
D3D12_RESOURCE_STATES(
crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
),
None,
&mut texture,
)
}
} else {
// SAFETY: the description has the host layout (checked size, same
// fields); the out pointer is ours.
unsafe {
host.device.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
(&raw const d).cast(),
D3D12_RESOURCE_STATES(
crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
),
// The same layout: format, then color or depth and stencil.
clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()),
&mut texture,
)
}
};
if let Err(e) = made {
tracing::warn!(error = %e, desc = ?d, "no host texture");
tracing::warn!(error = %e, desc = ?d, reserved, "no host texture");
}
if let Some(t) = &texture {
crate::host::name(t, || {
@@ -1963,6 +2156,73 @@ fn host_texture(
texture
}
/// The host copy of title texture `this` if it is made and was made
/// without memory of its own (`crate::tiles`); it is not made here.
#[cfg(windows)]
pub(crate) fn host_tiled(this: This) -> Option<OnDemand> {
if this.is_null() || !crate::tiles::wanted() {
return None;
}
hosted(this, false).map(|(host, _)| host).filter(|host| host.tiled.is_some()).map(OnDemand)
}
/// The first level a view of title texture `this` may show, if its host
/// copy is made level by level and some level is held and has memory
/// (`crate::tiles::Tiled::first_shown`).
#[cfg(windows)]
pub(crate) fn first_shown(this: This) -> Option<u32> {
host_tiled(this)?.tiled()?.first_shown()
}
/// A host copy made without memory of its own (`crate::tiles`), as a
/// submission-time step of a list holds it.
#[cfg(windows)]
pub(crate) struct OnDemand(std::sync::Arc<HostTexture>);
// SAFETY: the host texture is named only in queue calls, which any thread
// may make; what it has been given is behind a lock of its own.
#[cfg(windows)]
unsafe impl Send for OnDemand {}
// SAFETY: as above.
#[cfg(windows)]
unsafe impl Sync for OnDemand {}
#[cfg(windows)]
impl OnDemand {
pub(crate) fn tiled(&self) -> Option<&crate::tiles::Tiled> {
self.0.tiled.as_ref()
}
/// [`crate::tiles::Tiled::uploaded`]; `memory`: where the texture's
/// title memory starts (its slots are made again if the first level
/// they may show changed).
/// Held levels get tiles only while the card has room ([`room`]).
/// Returns whether a level is still without its tiles: the caller
/// records the upload again later.
pub(crate) fn uploaded(&self, held: u32, memory: u64) -> bool {
let Some(tiled) = &self.0.tiled else {
return false;
};
let (changed, waiting) = tiled.uploaded(&self.0.texture, held, room(crate::host::host().and_then(|h| h.video_memory())));
if changed {
crate::descriptor::host::levels_changed(memory);
}
if waiting {
crate::tiles::STATS[9].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
waiting
}
/// [`crate::tiles::Tiled::card_wrote`]; `memory` as above.
pub(crate) fn card_wrote(&self, levels: u32, memory: u64) {
if let Some(tiled) = &self.0.tiled
&& tiled.card_wrote(&self.0.texture, levels)
{
crate::descriptor::host::levels_changed(memory);
}
}
}
/// A texture's console memory and description; `None` for buffers.
pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> {
if this.is_null() {
+305 -69
View File
@@ -220,6 +220,40 @@ fn card_limits() -> (u64, u64) {
/// Bytes alive of copies' card sides, and of their "before" twins.
static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
/// Whether the texture queue leaves room on the card for the card copies
/// of title buffers that are not made yet
/// (`VICTORY_CARD_ROOM_FOR_BUFFERS=1`; off by default).
///
/// The copies are made in one burst when the world loads (run 189: 94 of
/// its 95 within two seconds, right before the first world frame), and
/// [`card_for`] makes one only while the card is under eight tenths of its
/// budget. That held as long as the textures picked by index filled the
/// card after the burst. Since the texture queue keeps packed neighbours
/// (52b8060) it fills the card while the world loads: 85% and more at the
/// burst in runs 190 to 192, so one copy of 95 was made, the CPU looked
/// for shader writes in 600 to 720 MB a frame where it had been 30, and
/// the frame went from about 240 to 370-470 ms.
///
/// With the switch, the texture queue's rule (`resource::room`) counts the
/// part of [`card_limits`]' second number that no copy has taken yet as
/// used, and a copy may be made up to nine tenths of the budget: the room
/// it takes was kept for it. After the burst what is kept is what the
/// burst left of the limit (87 MB of 1,024 in run 189).
fn card_room_kept_on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_some_and(|v| v == "1"))
}
/// The bytes of the card's memory the texture queue leaves free for card
/// copies of title buffers not made yet ([`card_room_kept_on`]): 0 with
/// the switch off or without card copies.
pub(crate) fn card_room_kept() -> u64 {
if !card_room_kept_on() || !cards() {
return 0;
}
card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed))
}
/// The copies in the card's memory.
static CARDED: Mutex<Vec<std::sync::Weak<Shadow>>> = Mutex::new(Vec::new());
@@ -270,8 +304,11 @@ fn card_for(size: u64) -> Option<ID3D12Resource> {
// queue's own rule (`resource::room`: nine tenths of the budget) counts
// them, so the card's use stays where it was and the textures' share
// shrinks by the copies' bytes, at most `card_limits`' second number.
// (With `card_room_kept_on` the texture queue kept this copy's room
// free, and the copy may go up to the queue's own line.)
let tenths = if card_room_kept_on() { 9 } else { 8 };
if let Some([budget, used, ..]) = host.video_memory()
&& used + size > budget / 10 * 8
&& used + size > budget / 10 * tenths
{
return None;
}
@@ -942,51 +979,54 @@ 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.
// Fixed-size equality compiles to two SIMD comparisons on Windows x64.
// Only the first or last unequal chunk needs a byte-wise search.
const DIFF_CHUNK: usize = 32;
/// Where `a` and `b` first differ within their common length.
fn first_difference(a: &[u8], b: &[u8]) -> Option<usize> {
let whole = a.len().min(b.len()) / 8 * 8;
let from = a[..whole]
.as_chunks::<8>().0.iter()
.zip(b[..whole].chunks_exact(8))
.position(|(x, y)| x != y)
.map_or(whole, |word| word * 8);
a[from..].iter().zip(&b[from..]).position(|(x, y)| x != y).map(|i| from + i)
let len = a.len().min(b.len());
let (a_chunks, a_tail) = a[..len].as_chunks::<DIFF_CHUNK>();
let (b_chunks, b_tail) = b[..len].as_chunks::<DIFF_CHUNK>();
let (offset, a, b) = match a_chunks.iter().zip(b_chunks).position(|(x, y)| x != y) {
Some(i) => (i * DIFF_CHUNK, &a_chunks[i][..], &b_chunks[i][..]),
None => (len - a_tail.len(), a_tail, b_tail),
};
a.iter().zip(b).position(|(x, y)| x != y).map(|i| offset + i)
}
/// Where `a` and `b` (of one length) last differ.
/// Where `a` and `b` last differ within their common length.
fn last_difference(a: &[u8], b: &[u8]) -> Option<usize> {
let whole = a.len().min(b.len()) / 8 * 8;
if let Some(i) = a[whole..].iter().zip(&b[whole..]).rposition(|(x, y)| x != y) {
return Some(whole + i);
let len = a.len().min(b.len());
let (a_chunks, a_tail) = a[..len].as_chunks::<DIFF_CHUNK>();
let (b_chunks, b_tail) = b[..len].as_chunks::<DIFF_CHUNK>();
if let Some(i) = a_tail.iter().zip(b_tail).rposition(|(x, y)| x != y) {
return Some(len - a_tail.len() + i);
}
let word = a[..whole]
.as_chunks::<8>().0.iter()
.zip(b[..whole].chunks_exact(8))
.rposition(|(x, y)| x != y)?
* 8;
a[word..word + 8]
let chunk = a_chunks.iter().zip(b_chunks).rposition(|(x, y)| x != y)?;
a_chunks[chunk]
.iter()
.zip(&b[word..word + 8])
.zip(&b_chunks[chunk])
.rposition(|(x, y)| x != y)
.map(|i| word + i)
.map(|i| chunk * DIFF_CHUNK + i)
}
#[cfg(test)]
mod difference_tests {
use super::{first_difference, last_difference};
/// The word-wise searches agree with the byte-wise ones they replace.
/// The chunk searches agree with a byte-wise scan across chunk boundaries.
#[test]
fn differences_are_found_as_byte_by_byte() {
let base: Vec<u8> = (0..61u32).map(|i| (i * 7 + 3) as u8).collect();
let same = base.clone();
assert_eq!(first_difference(&base, &same), None);
assert_eq!(last_difference(&base, &same), None);
for len in [0usize, 1, 7, 8, 9, 16, 23, 61] {
let base: Vec<u8> = (0..98u32).map(|i| (i * 7 + 3) as u8).collect();
for len in [0, 1, 31, 32, 33, 63, 64, 65, 97] {
let a = &base[1..1 + len];
let same = a.to_vec();
assert_eq!(first_difference(&same, a), None);
assert_eq!(last_difference(&same, a), None);
for at in 0..len {
for other in at..len {
let (a, mut b) = (&base[..len], base[..len].to_vec());
let mut b = a.to_vec();
b[at] ^= 0x80;
b[other] ^= 0x01;
let first = a.iter().zip(&b).position(|(x, y)| x != y);
@@ -997,6 +1037,19 @@ mod difference_tests {
}
}
}
#[test]
fn differences_ignore_bytes_past_the_shorter_slice() {
let a = [0; 65];
let mut b = [0; 67];
b[65] = 1;
assert_eq!(first_difference(&a, &b), None);
assert_eq!(last_difference(&b, &a), None);
b[32] = 1;
b[64] = 1;
assert_eq!(first_difference(&b, &a), Some(32));
assert_eq!(last_difference(&a, &b), Some(64));
}
}
/// The unit shader writes are looked for and put back in.
@@ -1448,6 +1501,80 @@ mod wide_tests {
}
}
/// What [`Shadow::copy_back`] does with a piece that differs from the
/// snapshot: `host` is the copy's bytes there, `old` the snapshot's. From
/// the first byte that differs to the last, title memory is read into
/// `title` (scratch, sized to that stretch) by `read` (the stretch's offset
/// in the piece, where to), the GPU's bytes are put in and `host` takes the
/// result. The stretch's offset in the piece and its length if that changed
/// title memory; none if nothing differs or title memory is not there.
/// `runs` takes the runs of the stretch (offsets into `title`, lengths)
/// whose bytes are the GPU's and differ from the title's as read: only
/// those are to be written, so a title write that lands between the read
/// and the write elsewhere in the stretch stays (upstream VIctory #2009).
/// `mask` is scratch.
fn back_piece(
host: &mut [u8],
old: &[u8],
title: &mut Vec<u8>,
mask: &mut Vec<u8>,
runs: &mut Vec<(usize, usize)>,
read: impl FnOnce(usize, &mut [u8]) -> bool,
) -> Option<(usize, usize)> {
runs.clear();
// From the first byte that differs to the last: title memory is read
// and written there only (a shader that sets a few words of a piece
// cost a read, a walk and a write of all 64 KiB of it).
let first = first_difference(host, old)?;
let last = last_difference(host, old).unwrap_or(first);
let n = last + 1 - first;
let (host, old) = (&mut host[first..=last], &old[first..=last]);
title.clear();
title.resize(n, 0);
if !read(first, title) {
return None;
}
// Title memory with the GPU's bytes put in; the copy takes the title's
// bytes in turn.
// Without a branch, so the loop runs many bytes at a time: the GPU's
// byte where the copy's byte is not what it was before the submission
// and the title left its byte as it was, else the title's. (With the
// two searches above this was 44 ms a frame for 970 pieces.)
// Where the shader and the title both changed a byte while the GPU ran,
// the title's stays: the shader computed its byte from the copy's older
// data (one cleared a bit of a record the title had already replaced,
// and copying it back broke the title's object: an access violation
// through 0xffffffff00000000; PalmVIDev e0b70476, VIctory f39c6c2).
mask.clear();
mask.resize(n, 0);
let mut differs = 0u8;
for (((t, h), o), m) in title.iter_mut().zip(host.iter_mut()).zip(old).zip(mask.iter_mut()) {
let gpu = if (*h != *o) & (*t == *o) { 0xffu8 } else { 0 };
let merged = (*t & !gpu) | (*h & gpu);
*m = merged ^ *t;
differs |= *m;
*t = merged;
*h = merged;
}
if differs == 0 {
return None;
}
let mut i = 0;
while i < n {
while i < n && mask[i] == 0 {
i += 1;
}
let start = i;
while i < n && mask[i] != 0 {
i += 1;
}
if i > start {
runs.push((start, i - start));
}
}
Some((first, n))
}
/// Since the last frame-rate line, of [`Shadow::merge_under_writes`]: pages
/// compared, changed runs put in, and their bytes.
static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
@@ -1668,7 +1795,94 @@ pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, ti
#[cfg(test)]
mod merge_tests {
use super::{changed_runs, dword_runs, put_changed};
use super::{PIECE, back_piece, changed_runs, dword_runs, put_changed};
/// A piece put back takes the GPU's bytes where the copy changed and
/// the title's everywhere else, reads and writes title memory only from
/// the first change to the last, and its scratch holds that stretch and
/// no more: not the 64 KiB per range it once was.
#[test]
fn a_piece_put_back_reads_only_its_stretch() {
let old: Vec<u8> = (0..PIECE).map(|i| (i * 7 + i / 251) as u8).collect();
// The title wrote 7 and 40,000 since the snapshot; the GPU wrote 5,
// 9 and 40,000 (the GPU's byte wins where both wrote).
let mut title_memory = old.clone();
title_memory[7] ^= 0x11;
title_memory[40_000] ^= 0x22;
let mut host = old.clone();
for at in [5, 9] {
host[at] ^= 0x33;
}
let gpu = host.clone();
let mut scratch = Vec::new();
let (mut mask, mut runs) = (Vec::new(), Vec::new());
let mut asked = None;
let read = |first: usize, into: &mut [u8]| {
asked = Some((first, into.len()));
into.copy_from_slice(&title_memory[first..first + into.len()]);
true
};
assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((5, 5)));
assert_eq!(asked, Some((5, 5)));
let mut wanted = title_memory[5..10].to_vec();
wanted[0] = gpu[5];
wanted[4] = gpu[9];
assert_eq!(scratch, wanted);
assert_eq!(host[5..10], wanted);
// Only the GPU's two bytes are written back (upstream #2009).
assert_eq!(runs, [(0, 1), (4, 1)]);
// The copy outside the stretch is left as it was.
assert!(host[..5] == gpu[..5] && host[10..] == gpu[10..]);
assert!(scratch.capacity() < PIECE / 2, "scratch of {} bytes for a stretch of 5", scratch.capacity());
// Nothing differs: title memory is not read.
let mut same = old.clone();
assert_eq!(back_piece(&mut same, &old, &mut scratch, &mut mask, &mut runs, |_, _| unreachable!()), None);
// Title memory not there: nothing to write, the copy unchanged.
let mut host = gpu.clone();
assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, _| false), None);
assert!(host == gpu);
// The GPU wrote what the title holds already: nothing to write.
let mut title_memory = old.clone();
title_memory[5] = gpu[5];
title_memory[9] = gpu[9];
let mut host = gpu.clone();
let read = |first: usize, into: &mut [u8]| {
into.copy_from_slice(&title_memory[first..first + into.len()]);
true
};
assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), None);
// A whole piece changed: the scratch grows to it.
let mut host: Vec<u8> = old.iter().map(|b| !b).collect();
assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, into| into.len() == PIECE), Some((0, PIECE)));
assert_eq!(scratch.len(), PIECE);
}
/// A byte the shader and the title both changed while the GPU ran keeps
/// the title's (the shader computed it from the copy's older data); a
/// byte only the shader changed goes back, and only such bytes are in
/// the runs to write (PalmVIDev e0b70476, upstream #2009).
#[test]
fn a_byte_both_changed_keeps_the_titles_and_only_gpu_bytes_are_written() {
let old = vec![1u8, 2, 3, 4, 5, 6];
let mut host = old.clone();
host[1] = 20; // the GPU alone
host[3] = 40; // both
host[4] = 50; // the GPU alone
let mut title_memory = old.clone();
title_memory[3] = 44;
title_memory[5] = 66; // the title alone
let (mut scratch, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new());
let read = |first: usize, into: &mut [u8]| {
into.copy_from_slice(&title_memory[first..first + into.len()]);
true
};
assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((1, 4)));
assert_eq!(scratch, [20, 3, 44, 50], "the title's byte where both changed");
assert_eq!(host[1..5], [20, 3, 44, 50], "the copy takes the result");
assert_eq!(runs, [(0, 1), (3, 1)], "the GPU's bytes only");
}
/// What shaders wrote reaches a page that is away only while the runtime
/// changes a mapping; a page that stays away loses it, and nothing else.
@@ -1889,6 +2103,51 @@ mod piece_tests {
}
}
/// The pages of `[a, e)` (title addresses, `a < e`) that a copy whose
/// first page is `base` must take from title memory before it holds the
/// title's bytes: those it never took (`copied` 0), whether or not the
/// title wrote them since tracking began, and those `written` (as
/// `crate::watch::writes` gives it, by page in order) shows written after
/// the copy took them. As [`Shadow::copy_stale`] decides it.
///
/// [`Shadow::stale_under_writes`] and [`Shadow::merge_under_writes`] looked
/// at `written` alone, so a page of a range shaders may be writing that the
/// copy never took, and the title had not written lately, was neither
/// merged nor a reason to settle; the refresh leaves such ranges alone, and
/// shaders read zeros there (fxceless/victory-fork#206: missing geometry
/// with `VICTORY_LATE_WAIT`/`VICTORY_RELAY`).
fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec<usize> {
(a / PAGE..e.div_ceil(PAGE))
.filter(|&page| page >= base)
.filter(|&page| match copied.get(page - base) {
None => false,
Some(0) => true,
Some(&at) => written
.binary_search_by_key(&page, |&(p, _)| p)
.is_ok_and(|i| written[i].1 > at),
})
.collect()
}
#[cfg(test)]
mod stale_tests {
use super::*;
#[test]
fn pages_never_taken_are_stale_written_or_not() {
let base = 0x100;
let copied = [5, 0, 5, 5];
let at = |page: usize| page * PAGE;
// Page 0x101 was never taken; page 0x102 was written after it was
// taken, page 0x103 before.
let written = [(0x102, 6), (0x103, 4)];
assert_eq!(stale_pages_in(base, &copied, at(0x100), at(0x104), &written), [0x101, 0x102]);
// Part of a page counts as the page; pages outside the copy do not.
assert_eq!(stale_pages_in(base, &copied, at(0x101) + 8, at(0x101) + 16, &[]), [0x101]);
assert!(stale_pages_in(base, &copied, at(0x104), at(0x106), &[(0x104, 9)]).is_empty());
}
}
/// Copies of windows outside buffers let go since the start, and their
/// bytes.
static LET_GO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
@@ -2327,43 +2586,24 @@ impl Shadow {
for &(at, n) in &differing {
self.changed(at, at + n);
}
let mut title = vec![0u8; PIECE];
// Sized to each stretch read (`back_piece`): a zeroed 64 KiB per
// range, most of whose ranges differ nowhere, was most of the
// work for small ranges.
let (mut title, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new());
for (at, n) in differing {
// SAFETY: inside the mapping; only the submitting thread
// writes it.
let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
let old = &before[at - from..at - from + n];
// From the first byte that differs to the last: title
// memory is read and written there only (a shader that sets
// a few words of a piece cost a read, a walk and a write of
// all 64 KiB of it).
let Some(first) = first_difference(host, old) else {
let read = |first: usize, title: &mut [u8]| crate::host::read_into((start + at + first) as *const u8, title);
let Some((first, n)) = back_piece(host, old, &mut title, &mut mask, &mut runs, read) else {
continue;
};
let last = last_difference(host, old).unwrap_or(first);
let (at, n) = (at + first, last + 1 - first);
let (host, old) = (&mut host[first..=last], &old[first..=last]);
let title = &mut title[..n];
if !crate::host::read_into((start + at) as *const u8, title) {
continue;
}
// Title memory with the GPU's bytes put in; the copy takes
// the title's bytes in turn.
// Without a branch, so the loop runs many bytes at a time:
// the GPU's byte where the copy's byte is not what it was
// before the submission, else the title's. (With the two
// searches above this was 44 ms a frame for 970 pieces.)
let mut differs = 0u8;
let was = title.to_vec();
for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) {
let gpu = if *h != *o { 0xffu8 } else { 0 };
let merged = (*t & !gpu) | (*h & gpu);
differs |= merged ^ *t;
*t = merged;
*h = merged;
}
if differs != 0 {
written += put_changed(start + at, &was, title);
// Title memory as read, beside it with the card's bytes put
// in: only the dwords that differ are written.
let was: Vec<u8> = title.iter().zip(&mask).map(|(now, changed)| now ^ changed).collect();
if !runs.is_empty() {
written += put_changed(start + at + first, &was[..n], &title[..n]);
}
}
// Our write shows as a title write at the copy's next refresh,
@@ -2625,9 +2865,7 @@ impl Shadow {
let base = start / PAGE;
let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) {
Some((_, written)) => written.into_iter().any(|(page, write)| {
page >= base && copied.get(page - base).is_none_or(|&at| at == 0 || write > at)
}),
Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(),
None => true,
})
}
@@ -2689,11 +2927,7 @@ impl Shadow {
};
let stale: Vec<usize> = {
let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
written
.into_iter()
.filter(|&(page, write)| page >= base && copied.get(page - base).is_none_or(|&at| at == 0 || write > at))
.map(|(page, _)| page)
.collect()
stale_pages_in(base, &copied, a, e, &written)
};
for page in stale {
let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e));
@@ -2888,7 +3122,7 @@ impl Shadow {
/// title's that arrived between the refresh and the look.
fn refresh_check(&self, from: usize, to: usize) {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1") || crate::host::walls_trace()) {
if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1")) {
return;
}
const SAMPLE: usize = 256;
@@ -3268,6 +3502,8 @@ impl Shadow {
title.resize(n, 0);
let mut written = 0;
if crate::host::read_into((start + at) as *const u8, title) {
// The stretch as read: what the card did not change is the
// title's, and may have been written again since.
// As in `copy_back`: the card's byte where it is not what it
// was before the submission, else the title's.
let mut differs = 0u8;
+264 -2
View File
@@ -61,6 +61,19 @@ pub(crate) struct Staging {
uploaded: std::sync::atomic::AtomicBool,
/// When a list last recorded a use of it (`crate::host::moment`).
used: std::sync::atomic::AtomicU64,
/// Levels on demand (`crate::tiles`): the texture's host copy was made
/// without memory of its own when the staging buffer was made.
on_demand: bool,
/// For such a texture: the levels that were the title's at the last
/// detiling (a bit a level; the staging buffer holds zeros for the
/// others), and what that was judged by ([`Staging::judgement`]).
detiled: std::sync::atomic::AtomicU32,
judged: [std::sync::atomic::AtomicU64; 2],
/// For such a texture: when an upload last left a held level without
/// tiles (`crate::host::moment`, never 0; 0: none did). The upload is
/// recorded again about a second later if the card has room by then
/// ([`upload`]).
waiting: std::sync::atomic::AtomicU64,
}
/// What a texture's staging buffer holds: the hash of the memory detiled
@@ -255,6 +268,7 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool {
if !first && before.is_none() {
return true;
}
card_writes(list, placed, to, None);
crate::list::ensure_state(list, placed, COPY_DEST);
let part = |texture: &ID3D12Resource, index: usize| D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
@@ -606,6 +620,32 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
};
use std::sync::atomic::Ordering::Relaxed;
staging.used.store(crate::host::moment(), Relaxed);
// Levels on demand: a view of the texture now starts at another
// level, or another texture now starts inside its span, with no byte
// of its memory changed. The levels are judged anew: detiled again at
// this list's submission, and uploaded by this list.
if staging.on_demand && staging.judgement() != staging.judged() {
staging.forget();
staging.dirty.store(true, Relaxed);
}
// Levels on demand: the last upload left a held level without tiles
// (the card had no room, or no heap could be had), and nothing else
// would record an upload again until the title writes the texture: the
// level stayed empty, the texture blurred or black. Asked again about
// once a second, and only when the card has room; the staging buffer
// still holds the level's bytes.
if staging.on_demand {
let since = staging.waiting.load(Relaxed);
if since != 0 && crate::host::long_ago(since, 1000, 2) {
if crate::resource::room_lately() {
staging.waiting.store(0, Relaxed);
staging.dirty.store(true, Relaxed);
crate::tiles::STATS[10].fetch_add(1, Relaxed);
} else {
staging.waiting.store(crate::host::moment().max(1), Relaxed);
}
}
}
// The host texture has the staging buffer's contents: only the check
// at submission is left, and what it finds changed the next list that
// samples the texture uploads (a frame late where every list of the
@@ -699,11 +739,207 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
staging.dirty.store(false, Relaxed);
});
}
// Once per submission however many of its lists sample the texture.
list.defer_texture(staging);
// Levels on demand (`crate::tiles`): after the check below, in the
// order of this list's steps, and before the list is executed, the
// levels the staging buffer holds as the title's are given the card's
// memory if they have none. The list copies every level, so each one
// given here is written whole by it (the rest are copies into no
// memory, which the card drops).
let on_demand = if staging.on_demand { crate::resource::host_tiled(resource) } else { None };
let Some(on_demand) = on_demand else {
// Once per submission however many of its lists sample the texture.
list.defer_texture(staging);
return;
};
list.defer_texture(staging.clone());
list.defer_host(move || {
let waiting = on_demand.uploaded(staging.detiled.load(Relaxed), staging.memory as u64);
staging.waiting.store(if waiting { crate::host::moment().max(1) } else { 0 }, Relaxed);
// A texture picked by index has no staging buffer after this
// upload: its slots are made due again by the texture pass.
if waiting {
crate::descriptor::host::levels_waiting(staging.memory as u64);
}
});
}
/// Levels on demand: the levels a list claimed for its zeros
/// (`crate::tiles::Tiled::claim`), held by the list's submission-time
/// step. A list that is reset without having been submitted gives the
/// claim up, or the next list that writes those levels would send no zeros
/// and what its write does not cover would be what the tiles' last owner
/// left.
struct Claimed {
on_demand: crate::resource::OnDemand,
fresh: u32,
ran: std::sync::atomic::AtomicBool,
}
impl Drop for Claimed {
fn drop(&mut self) {
if self.fresh != 0
&& !*self.ran.get_mut()
&& let Some(tiled) = self.on_demand.tiled()
{
tiled.unclaim(self.fresh);
}
}
}
/// Levels on demand (`crate::tiles`): the card itself is about to write
/// title texture `resource` in `list` (a copy or a resolve into level
/// `level`, or into every level). If its host copy `texture` was made
/// without memory, the levels written get theirs when the list is
/// submitted, ahead of it on the queue; the ones that have none yet are
/// first written with zeros, here in the same list, so that what the
/// card's write does not cover is not what the tiles' last owner left.
/// To be called before the list is brought to the state of that write.
/// shortcut: two lists that write the same new level, submitted in the
/// other order than recorded, lose the first one's write under the zeros
/// of the other; so does an upload recorded and not yet submitted.
pub(crate) fn card_writes(list: &HostList, resource: This, texture: &ID3D12Resource, level: Option<u32>) {
let Some(on_demand) = crate::resource::host_tiled(resource) else {
return;
};
let Some(tiled) = on_demand.tiled() else {
return;
};
let levels = match level {
Some(level) => tiled.with_level(level),
None => tiled.every_level(),
};
if levels == 0 {
return;
}
let fresh = tiled.claim(levels);
// Of them, the ones whose zeros could not be recorded.
let mut unzeroed = if host().is_none() { fresh } else { 0 };
if fresh != 0
&& let Some(host) = host()
{
const COPY_DEST: u32 = 0x400;
crate::list::ensure_state(list, resource, COPY_DEST);
// SAFETY: a live resource.
let d = unsafe { texture.GetDesc() };
for level in (0..u32::from(d.MipLevels).min(32)).filter(|&level| fresh & (1u32 << level) != 0) {
let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
let mut bytes = 0u64;
// SAFETY: outputs for one subresource.
unsafe {
host.device
.GetCopyableFootprints(&d, level, 1, 0, Some(&mut footprint), None, None, Some(&mut bytes));
}
let Some((buffer, data)) = list.upload(host, bytes) else {
// (With the levels that share its tiles, if it is one of
// the small ones.)
unzeroed |= tiled.with_level(level);
continue;
};
// SAFETY: a mapped buffer of `bytes` bytes, just made.
unsafe { std::ptr::write_bytes(data, 0, bytes as usize) };
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: level },
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above; the list holds the buffer until it is reset.
pResource: unsafe { std::mem::transmute_copy(&buffer) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint },
};
// SAFETY: an open list; both locations name live resources.
unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
}
}
// A new level without its zeros gets no tiles from this list: the
// card's write into it is lost (the level reads zeros, as before the
// write), which is less wrong than a part write over what the tiles'
// last owner left. The next list that writes it claims it again.
unzeroed &= fresh;
if unzeroed != 0 {
tiled.unclaim(unzeroed);
}
let levels = levels & !unzeroed;
if levels == 0 {
return;
}
let memory = crate::resource::texture_memory(resource).map_or(0, |(memory, _)| memory as u64);
let step = Claimed {
on_demand,
fresh: fresh & !unzeroed,
ran: std::sync::atomic::AtomicBool::new(false),
};
list.defer_host(move || {
step.ran.store(true, std::sync::atomic::Ordering::Relaxed);
step.on_demand.card_wrote(levels, memory);
});
}
impl Staging {
/// Levels on demand: what says, beside the mapping, which levels of
/// the texture are the title's now. First the lowest level a live view
/// of the texture shows (0 without a view that says): the title's own
/// word, a texture it holds from level 3 on is viewed from level 3.
/// Then where the next texture placed in this one's span starts, in
/// bytes from this one's start (`u64::MAX`: none does): for a texture
/// viewed from level 0 although a neighbour sits where its large
/// levels would be.
fn judgement(&self) -> [u64; 2] {
let start = self.memory as u64;
let first = crate::descriptor::host::first_viewed(start).map_or(0, u64::from);
let limit = crate::descriptor::host::next_start(start, start.saturating_add(self.layout.size))
.map_or(u64::MAX, |at| at - start);
[first, limit]
}
/// What [`Staging::judgement`] said at the last detiling.
fn judged(&self) -> [u64; 2] {
use std::sync::atomic::Ordering::Relaxed;
[self.judged[0].load(Relaxed), self.judged[1].load(Relaxed)]
}
/// Levels on demand: the levels that are the title's now, a bit a
/// level. A level is held if no view starts above it, its bytes end
/// before the next texture starts, and all of them are mapped. The
/// smallest levels share the texture's first block and are held
/// together. (The console layout: that block first, then the other
/// levels from the smallest up, level 0 last:
/// `victory_formats::texture::Layout`.) A texture this cannot tell
/// the levels of holds them all.
fn held_levels(&self, [first, limit]: [u64; 2]) -> u32 {
let mips = &self.layout.mips;
if self.layout.slices != 1 || mips.is_empty() || mips.len() > 32 {
return u32::MAX;
}
let tail = (self.layout.first_tail_mip as usize).min(mips.len());
let there = |from: u64, to: u64| {
to > from && to <= limit && committed(self.memory.wrapping_add(from as usize), (to - from) as usize)
};
let mut held = 0u32;
for (level, m) in mips.iter().enumerate().take(tail) {
let end = if level == 0 { self.layout.slice_size } else { mips[level - 1].offset };
if level as u64 >= first && there(m.offset, end) {
held |= 1 << level;
}
}
if tail < mips.len() && there(0, self.layout.alignment.min(self.layout.slice_size)) {
for level in tail..mips.len() {
if level as u64 >= first {
held |= 1 << level;
}
}
}
held
}
/// Forgets what the staging buffer was last filled from: the next
/// refresh detiles anew, whether the memory changed or not.
fn forget(&self) {
*self.last.lock().unwrap_or_else(|e| e.into_inner()) = Last::default();
}
/// The title memory the texture is read from: address and bytes.
pub(crate) fn memory(&self) -> (usize, usize) {
(self.memory as usize, self.layout.size as usize)
@@ -909,6 +1145,20 @@ impl Staging {
/// Detiles `tiled` (the texture's memory) into the staging buffer.
fn detile(&self, tiled: &[u8]) {
self.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
// Levels on demand: which levels are the title's is judged here,
// once, for what the staging buffer holds from now on. The step
// that gives levels their memory goes by this answer.
let held = if self.on_demand {
use std::sync::atomic::Ordering::Relaxed;
let judged = self.judgement();
self.judged[0].store(judged[0], Relaxed);
self.judged[1].store(judged[1], Relaxed);
let held = self.held_levels(judged);
self.detiled.store(held, Relaxed);
held
} else {
u32::MAX
};
#[cfg(feature = "diagnostics")]
if tiled.iter().all(|&b| b == 0) {
tracing::debug!(
@@ -926,6 +1176,11 @@ impl Staging {
let linear = unsafe {
std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len)
};
if mip < 32 && held & (1 << mip) == 0 {
// Not the title's: zeros, not what lies in that memory.
linear.fill(0);
continue;
}
if let Err(e) =
self.layout
.detile(tiled, mip, slice, linear, pitch, pitch * rows as usize)
@@ -1179,6 +1434,9 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 {
/// The staging state of a title texture, made on first use.
fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
// Asked before the table is locked: the sweep lets go of a staging
// buffer with its texture's host side locked, in that order.
let on_demand = crate::resource::host_tiled(resource).is_some();
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
let map = map.get_or_insert_with(HashMap::new);
if let Some(s) = map.get(&(resource as usize)) {
@@ -1254,6 +1512,10 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
dirty: std::sync::atomic::AtomicBool::new(true),
uploaded: std::sync::atomic::AtomicBool::new(false),
used: std::sync::atomic::AtomicU64::new(crate::host::moment()),
on_demand,
detiled: std::sync::atomic::AtomicU32::new(0),
judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2],
waiting: std::sync::atomic::AtomicU64::new(0),
});
map.insert(resource as usize, s.clone());
Some(s)
File diff suppressed because it is too large. Load diff
+606 -34
View File
@@ -14,11 +14,17 @@
//! wholly uncommitted are skipped while they remain so; one query can
//! confirm a whole region, including ordinary reservations between views.
//!
//! shortcut: writes into physical pages through another view (xmem's
//! `write_physical`, DirectStorage's page destinations) are not seen at
//! the guarded addresses; they go to the texture pool, whose textures are
//! hashed, not guarded. A system call writing into a guarded block fails
//! (none is known to).
//! The title shows one physical page at several addresses, and writes it
//! through one while the card reads it at another. So a block is clean, and
//! known by its bit, only while every view of its page is read-only
//! ([`cover`]): a write through any of them faults, opens them all and takes
//! clean and bit from all of them ([`open`]). A view mapped anew of a page
//! that is guarded elsewhere has the others looked at again
//! ([`views_mapped`]). What we write ourselves is told at one address and
//! counts at all ([`writing`], [`landed_beside`], [`wrote`]). Not so for a
//! page shown in more than [`MANY_VIEWS`] places (what the title shows where
//! it has nothing). `VICTORY_VIEW_GUARD=0`: each address for itself, as
//! before.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Condvar, Mutex, RwLock};
@@ -352,6 +358,18 @@ pub(crate) fn wrote(at: usize, len: usize) {
for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) {
j.written.insert(page, now);
}
for (_, others) in elsewhere(at, len) {
j.written.extend(others.into_iter().map(|other| (other / PAGE, now)));
}
}
/// The blocks of `[at, at + len)` whose pages the title shows at other
/// addresses too, and there.
fn elsewhere(at: usize, len: usize) -> Vec<(usize, Vec<usize>)> {
if !view_guard() || len == 0 {
return Vec::new();
}
crate::inplace::shown_elsewhere(at / BLOCK * BLOCK, at.saturating_add(len))
}
/// One kernel asking for `pieces` (page ranges in order); by halves if it
@@ -797,6 +815,11 @@ struct Guards {
/// left as they are by [`guard`], which reports them written.
kernel: Vec<(usize, usize)>,
changing: Vec<(usize, usize)>,
/// Blocks whose page is shown at other addresses too and that were made
/// 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
/// these are looked up.)
aliased: BTreeSet<usize>,
}
impl Guards {
@@ -813,6 +836,7 @@ static GUARDS: Mutex<Guards> = Mutex::new(Guards {
foreign: BTreeSet::new(),
kernel: Vec::new(),
changing: Vec::new(),
aliased: BTreeSet::new(),
});
fn guards() -> std::sync::MutexGuard<'static, Guards> {
@@ -850,8 +874,14 @@ 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);
for page in at / 4096..=(at + len.max(1) - 1) / 4096 {
landed.insert(page, frame);
let (first, last) = (at / KERNEL_PAGE, (at + len.max(1) - 1) / KERNEL_PAGE);
landed.extend((first..=last).map(|page| (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)));
}
}
}
writing(at, len);
@@ -878,6 +908,9 @@ pub(crate) fn landing(at: usize, len: usize) {
pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, Vec<(usize, u64)>) {
let mut before = Vec::with_capacity(spans.len());
let noted;
// The same pages at other addresses: copies of the memory there have not
// what was put in either.
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());
@@ -885,6 +918,12 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64,
for &page in pages {
landed.insert(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)));
}
}
}
{
let mut j = journal_mut();
@@ -898,11 +937,17 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64,
last = block;
}
}
for (_, others) in &elsewhere {
j.written.extend(others.iter().map(|other| (other / PAGE, now)));
}
}
for &(at, len) in spans {
// A placed texture there changes with no descriptor written.
crate::descriptor::host::remapped(at, len);
}
for other in elsewhere.into_iter().flat_map(|(_, others)| others) {
crate::descriptor::host::remapped(other, BLOCK);
}
(noted, before)
}
@@ -927,14 +972,16 @@ pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool {
/// the title, or by us putting a flight's shader writes into it, if not
/// beside the guard, [`landed_beside`].) Not for
/// blocks no copy ever took, which were never guarded: the caller's range
/// lies in a copy a flight was given, which took all of it.
/// lies in a copy a flight was given, which took all of it. (Nor for blocks
/// read-only by way of another view of their page: whether they were written
/// since is not known.)
pub(crate) fn written_since_taken(at: usize, len: usize) -> bool {
if len == 0 {
return false;
}
let g = guards();
(at / BLOCK..=(at + len - 1) / BLOCK)
.all(|b| !g.clean.contains(&b) && !g.absent.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
@@ -1013,8 +1060,11 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
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.
g.clean.insert(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;
@@ -1073,8 +1123,100 @@ fn is_view(start: usize, end: usize) -> bool {
/// Makes blocks `[from, to)` read-only and notes them guarded and clean;
/// block by block if they span views, leaving out any that fail, and
/// noting those not committed (unmapped) absent.
/// noting those not committed (unmapped) absent. The same physical pages
/// at every other view of them are made read-only too: a write through
/// 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.
fn protect(g: &mut Guards, from: usize, to: usize) {
protect_here(g, from, to);
cover(g, from, to);
}
/// Views of one page past which its views are not guarded together.
pub(crate) const MANY_VIEWS: usize = 64;
/// Whether all the views of a guarded page are guarded together
/// (`VICTORY_VIEW_GUARD`).
fn view_guard() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_GUARD").is_none_or(|v| v != "0"))
}
/// Diagnostics: blocks guarded together with their other views, blocks
/// opened because another view of theirs was written, and blocks opened
/// because a view of theirs was mapped; since the start.
#[cfg(feature = "diagnostics")]
pub(crate) static ALIASES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
/// Of the blocks `[from, to)`, which are read-only by our hand where they
/// can be: every other view of their pages is made read-only too. Where one
/// cannot be (the kernel writes through it now, or the runtime is changing
/// it), a write through it would not be seen: that block is not clean, and
/// told as written at every asking, until it can. Whether all are covered.
fn cover(g: &mut Guards, from: usize, to: usize) -> bool {
let mut all = true;
for (page, others) in elsewhere(from * BLOCK, (to - from) * BLOCK) {
let block = page / BLOCK;
if !g.protected.contains(&block) {
continue; // not there, or not ours to guard
}
#[cfg(feature = "diagnostics")]
ALIASES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
g.aliased.insert(block);
let mut covered = true;
for other in others {
covered &= protect_alias(g, other / BLOCK);
}
if !covered {
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
/// 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: &mut Guards, block: usize) -> bool {
use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect};
g.aliased.insert(block);
if g.protected.contains(&block) {
return true;
}
if g.left_alone(block) {
return false;
}
// Ahead of the protection.
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((block * BLOCK) as *const _, BLOCK, PAGE_READONLY, &mut old) } != 0;
#[cfg(feature = "diagnostics")]
{
tally(5, 1);
tally(8, started.elapsed().as_nanos() as u64);
}
if done && matches!(old, PAGE_READWRITE | PAGE_READONLY) {
g.protected.insert(block);
return true;
}
if done {
// Not for us to guard: as it was.
// SAFETY: as above.
unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, old, &mut old) };
}
PROTECTED.clear(block);
false
}
/// [`protect`] for one range, without the other views of its pages.
fn protect_here(g: &mut Guards, from: usize, to: usize) {
use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect};
let set = |from: usize, to: usize| {
let mut old = 0;
@@ -1152,21 +1294,49 @@ fn uncommitted_end(block: usize) -> usize {
}
/// Gives write access back to the guarded blocks of `[start, end)` and
/// notes them written; true if any was guarded.
/// notes them written; true if any was guarded. The same physical pages at
/// every other view of them are opened too: the write that faulted (or is
/// ours, `crate::host::copy_mapped`) goes through one view, and every
/// guard over the pages must copy them again.
fn open(g: &mut Guards, start: usize, end: usize) -> bool {
let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
if first >= last {
return false;
}
let mut blocks: Vec<usize> = g.protected.range(first..last).copied().collect();
let here = blocks.len();
if !g.aliased.is_empty() {
let aliased: Vec<usize> = g.aliased.range(first..last).copied().collect();
for block in aliased {
g.aliased.remove(&block);
for other in crate::inplace::pages_of(block * BLOCK) {
let other = other / BLOCK;
g.aliased.remove(&other);
if !(first..last).contains(&other) && g.protected.contains(&other) {
blocks.push(other);
}
}
}
#[cfg(feature = "diagnostics")]
ALIASES[1].fetch_add((blocks.len() - here) as u64, std::sync::atomic::Ordering::Relaxed);
}
unguard(g, &blocks);
here != 0
}
/// Gives write access back to `blocks`, guarded ones.
fn unguard(g: &mut Guards, blocks: &[usize]) {
use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect};
let blocks: Vec<usize> = g
.protected
.range(start / BLOCK..end.div_ceil(BLOCK))
.copied()
.collect();
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
for &block in &blocks {
g.protected.remove(&block);
g.clean.remove(&block);
// Before the block can be written.
PUBLISHED.clear(block);
// All of them before the first can be written: a write through one is a
// write of the others' bytes.
for block in blocks {
g.protected.remove(block);
g.clean.remove(block);
PUBLISHED.clear(*block);
}
for &block in blocks {
let mut old = 0;
// SAFETY: a block we made read-only.
unsafe {
@@ -1184,7 +1354,6 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool {
if !blocks.is_empty() {
tally(8, started.elapsed().as_nanos() as u64);
}
!blocks.is_empty()
}
/// Before our own write into title memory `[at, at + len)` through the
@@ -1249,6 +1418,121 @@ impl Drop for KernelWrite {
}
}
/// What `VICTORY_PAGE_WRITES` asks to be done with a write the guards do
/// not see once its bytes are there ([`title_memory_written`]), as bits:
/// 1, the guarded blocks under it are opened and count as written (host
/// copies of buffers and textures read through tables take them again);
/// 2, the placed textures picked by index that lie under it are due again;
/// 4, both also for reads to plain addresses when they have finished.
/// Unset or `0`: nothing, counted only. `1`: bits 1 and 2. `guards`: bit 1
/// alone. `slots`: bit 2 alone. `all`: everything.
pub(crate) fn page_writes() -> u8 {
static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
*MODE.get_or_init(|| match std::env::var("VICTORY_PAGE_WRITES").as_deref().map(str::trim) {
Ok("1") => 3,
Ok("guards") => 1,
Ok("slots") => 2,
Ok("all") => 7,
_ => 0,
})
}
/// Since the start: writes into physical pages through the runtime's own
/// views that landed at addresses the title has mapped (one for each run
/// of addresses); their bytes; guarded blocks that lay under them (host
/// copies that would otherwise keep the bytes from before); reads to
/// plain addresses that finished.
pub(crate) static WRITTEN: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
/// The bytes of a write the guards do not see are there: title memory
/// `[at, at + len)`. `pages`: DirectStorage wrote them into physical pages
/// through a view of the runtime's own, and this is an address where the
/// title has those pages mapped (no title address faulted, nothing was
/// mapped or unmapped; the shortcut this file's header names). Otherwise a
/// read to a plain address has finished, of which [`writing`] was told
/// before it began.
///
/// Upstream's c75fdba does the same for its trackers (its `Writing` marks
/// the pages once more when dropped; page destinations are reported at
/// each address showing them). Here it is counted always and acted on as
/// [`page_writes`] says. Called without the runtime's page-table lock;
/// takes the guards' lock, then, alone, the lock of the ranges kept for
/// the texture pass.
pub fn title_memory_written(at: usize, len: usize, pages: bool) {
use std::sync::atomic::Ordering::Relaxed;
if len == 0 {
return;
}
let mode = page_writes();
let end = at.saturating_add(len);
if pages {
WRITTEN[0].fetch_add(1, Relaxed);
WRITTEN[1].fetch_add(len as u64, Relaxed);
} else {
WRITTEN[3].fetch_add(1, Relaxed);
if mode & 4 == 0 {
return;
}
}
{
let mut g = guards();
let guarded = g.protected.range(at / BLOCK..end.div_ceil(BLOCK)).count() as u64;
if pages {
WRITTEN[2].fetch_add(guarded, Relaxed);
}
if mode & 1 != 0 && guarded != 0 {
open(&mut g, at, end);
}
}
// A placed texture there changed with no descriptor written.
crate::descriptor::host::page_written(at, len);
}
/// The runtime mapped a view of the physical bytes `[offset, offset + len)`
/// of `section` (`crate::inplace::title_memory_view`): the view is
/// writable, so the same bytes guarded at another view must be checked
/// again - and are, the pages noted written, which also has the next check
/// guard the new view ([`cover`]).
pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) {
if !view_guard() {
return;
}
let mut ranges = crate::inplace::views_of_section(section, offset, len);
// (A block is noted in `PROTECTED` ahead of the look at its page's views
// that did not find this one yet.)
ranges.retain(|&(at, n)| PROTECTED.any(at / BLOCK, (at + n).div_ceil(BLOCK)));
if ranges.is_empty() {
return;
}
let mut g = guards();
for &(at, n) in &ranges {
let blocks: Vec<usize> = g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).copied().collect();
#[cfg(feature = "diagnostics")]
ALIASES[2].fetch_add(blocks.len() as u64, std::sync::atomic::Ordering::Relaxed);
unguard(&mut g, &blocks);
}
}
/// The runtime is about to unmap a view of which it maps a part again at
/// once ([`title_memory_unmapping`] of all of it comes next): the title's
/// threads may write through that part before we are told of it
/// ([`views_mapped`]). What is guarded of its pages at other views is opened,
/// and not guarded again before the change is done ([`Remapping`]).
pub fn title_memory_splitting(at: usize, len: usize) {
let others: Vec<usize> = elsewhere(at, len).into_iter().flat_map(|(_, others)| others).collect();
if others.is_empty() {
return;
}
let mut g = guards();
for other in others {
open(&mut g, other, other + BLOCK);
if CHANGING.get().0 {
CHANGING.set((true, true));
g.changing.push((other / BLOCK, other / BLOCK + 1));
}
}
}
/// Held shared by a read of title memory in place, and alone by the runtime
/// while it changes what title memory shows.
///
@@ -1551,10 +1835,14 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static,
PUBLISHED.clear(block);
}
}
let foreign: Vec<usize> = g.foreign.range(range).copied().collect();
let foreign: Vec<usize> = g.foreign.range(range.clone()).copied().collect();
for block in foreign {
g.foreign.remove(&block);
}
let aliased: Vec<usize> = g.aliased.range(range).copied().collect();
for block in aliased {
g.aliased.remove(&block);
}
g
}
@@ -2312,6 +2600,242 @@ mod tests {
}
}
/// A pagefile section mapped twice: two views of the same physical
/// pages, the second left for the test; the section handle, the two
/// addresses.
fn two_views(bytes: usize) -> (usize, usize, usize) {
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile,
};
// SAFETY: a fresh pagefile section, mapped twice; the views keep
// the section alive and the handle is closed by the caller.
unsafe {
let section = CreateFileMappingW(
INVALID_HANDLE_VALUE,
std::ptr::null(),
PAGE_READWRITE,
0,
bytes as u32,
std::ptr::null(),
);
assert!(!section.is_null());
let one = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize;
let two = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize;
assert_ne!(one, 0);
assert_ne!(two, 0);
crate::inplace::title_memory_view(one, bytes, section as usize, 0);
crate::inplace::title_memory_view(two, bytes, section as usize, 0);
(section as usize, one, two)
}
}
/// The section of [`two_views`] is closed and its views unmapped; the
/// guard is told they are gone first.
fn drop_views(section: usize, views: &[usize], bytes: usize) {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Memory::{MEMORY_MAPPED_VIEW_ADDRESS, UnmapViewOfFile};
for &view in views {
title_memory_remapped(view, bytes);
// SAFETY: a view of the section mapped by `two_views`.
unsafe {
UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
Value: view as *mut _,
})
};
}
// SAFETY: the section's last reference.
unsafe { CloseHandle(section as *mut std::ffi::c_void) };
}
/// The title wrote the pages of a guarded texture through another view
/// of them: the fault at that view is the guard's to see, and the
/// guarded view's next check reports the pages written.
#[test]
fn a_write_through_another_view_is_reported_at_the_guarded_one() {
const SIZE: usize = 2 * BLOCK;
let (section, guarded, other) = two_views(SIZE);
let pages = |block: usize| (guarded + block * BLOCK) / PAGE;
// The first check takes it in (and every view of its pages).
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet");
// Writing through the other view faults into the handler, which
// opens that view and the guarded one: the next check sees it.
// SAFETY: the second view, read-write once the handler has opened it.
unsafe { ((other + BLOCK + 8) as *mut u8).write(1) };
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)]));
assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()));
drop_views(section, &[guarded, other], SIZE);
}
/// A view of guarded pages is mapped anew: it is writable, so the
/// guarded view checks its pages again (and guards the new view).
#[test]
fn a_view_mapped_beside_a_guarded_one_makes_it_check_again() {
const SIZE: usize = 2 * BLOCK;
let (section, guarded, other) = two_views(SIZE);
let pages = |block: usize| (guarded + block * BLOCK) / PAGE;
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet");
title_memory_remapped(other, SIZE);
crate::inplace::title_memory_view(other, SIZE, section, 0);
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()));
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]
fn a_write_told_at_one_view_is_reported_at_the_others() {
const SIZE: usize = 2 * BLOCK;
let (section, guarded, other) = two_views(SIZE);
let pages = |block: usize| (guarded + block * BLOCK) / PAGE;
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet");
writing(other + BLOCK, BLOCK);
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)]));
assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()));
// Half a page and the next: both blocks, not just the first's.
writing(other + BLOCK / 2, BLOCK);
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
drop_views(section, &[guarded, other], SIZE);
}
/// Both views of the pages are checked, each for a copy of its own
/// (the title shows one physical page at several addresses, and each
/// address has its host copy): a write through either is reported at
/// both, whichever is checked first. Guarding the pages for the first
/// view's check must not note the second view clean, or its copy would
/// keep the bytes from before the write.
#[test]
fn a_write_is_reported_at_every_checked_view() {
const SIZE: usize = 2 * BLOCK;
let (section, one, two) = two_views(SIZE);
let pages = |view: usize, block: usize| (view + block * BLOCK) / PAGE;
assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0), pages(one, 1)]));
assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0), pages(two, 1)]), "the second view's first check");
assert_eq!(guard(one, one + SIZE), Some(Vec::new()), "nothing written yet");
assert_eq!(guard(two, two + SIZE), Some(Vec::new()), "nothing written yet");
// SAFETY: the second view, read-write once the handler has opened it.
unsafe { ((two + BLOCK + 8) as *mut u8).write(1) };
assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 1)]));
assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 1)]), "written through this view, checked second");
// SAFETY: the first view, as above.
unsafe { ((one + 8) as *mut u8).write(1) };
assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0)]));
assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0)]), "written through this view, checked second");
assert_eq!(guard(one, one + SIZE), Some(Vec::new()));
assert_eq!(guard(two, two + SIZE), Some(Vec::new()));
drop_views(section, &[one, two], SIZE);
}
/// 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.
#[test]
fn bits_go_at_every_view() {
const SIZE: usize = 2 * BLOCK;
let (section, one, two) = two_views(SIZE);
let ask = |at: usize| writes(at, at + SIZE, true).expect("a view");
for at in [one, two, one, two] {
ask(at);
}
assert!(published(one, one + SIZE) && published(two, two + SIZE));
let (before, _) = ask(two);
// SAFETY: the first view, opened by the handler.
unsafe { ((one + BLOCK + 8) as *mut u8).write(1) };
assert!(published(one, one + BLOCK) && published(two, two + BLOCK), "the other block is as it was");
assert!(!published(one + BLOCK, one + SIZE) && !published(two + BLOCK, two + SIZE));
let told = |at: usize| ask(at).1.iter().find(|w| w.0 == (at + BLOCK) / PAGE).map_or(0, |w| w.1);
assert!(told(two) > before && told(one) > before);
drop_views(section, &[one, two], SIZE);
}
/// While the kernel writes through one view, the same page at another
/// is told as written at every asking, and the first is not guarded.
#[test]
fn what_the_kernel_writes_through_is_not_guarded_for_another_view() {
let (section, one, two) = two_views(BLOCK);
let page = one / PAGE;
assert_eq!(guard(one, one + BLOCK), Some(vec![page]));
assert_eq!(guard(one, one + BLOCK), Some(Vec::new()));
let writing = kernel_writing(two, 100);
for _ in 0..3 {
assert_eq!(guard(one, one + BLOCK), Some(vec![page]), "the kernel may be writing it");
assert!(writable(two));
}
assert!(!written_since_taken(one, 8), "by whom is not known");
drop(writing);
assert_eq!(guard(one, one + BLOCK), Some(vec![page]));
assert!(!writable(two));
assert_eq!(guard(one, one + BLOCK), Some(Vec::new()));
// SAFETY: opened by the handler.
unsafe { ((two + 8) as *mut u8).write(1) };
assert_eq!(guard(one, one + BLOCK), Some(vec![page]));
drop_views(section, &[one, two], BLOCK);
}
/// What shaders wrote, put in past the guards and told at one view, is
/// told at the others, whose copies have not got it; and so is what we
/// wrote while a submission's one asking stands.
#[test]
fn what_is_put_in_beside_the_guards_is_told_at_every_view() {
let (section, one, two) = two_views(BLOCK);
writes(two, two + BLOCK, true).expect("a view");
let (before, _) = writes(two, two + BLOCK, true).expect("a view");
assert!(published(two, two + BLOCK));
landed_beside(&[one / 4096 + 3], &[(one + 3 * 4096, 16)]);
let (_, told) = writes(two, two + BLOCK, true).expect("a view");
assert!(told.iter().any(|w| w.0 == two / PAGE && w.1 > before), "{told:?} after {before}");
assert!(landed_lately(two + 3 * 4096, 16, 1) && !landed_lately(two + 4 * 4096, 16, 1));
drop_views(section, &[one, two], BLOCK);
}
/// A view is cut in two by the runtime: until that is done, its pages
/// count as written wherever else they are shown.
#[test]
fn a_view_being_split_leaves_its_pages_unguarded_elsewhere() {
const SIZE: usize = 3 * BLOCK;
let (section, one, two) = two_views(SIZE);
let pages: Vec<usize> = (0..3).map(|k| one / PAGE + k).collect();
assert_eq!(guard(one, one + SIZE), Some(pages.clone()));
assert_eq!(guard(one, one + SIZE), Some(Vec::new()));
let changing = title_memory_remapping();
title_memory_splitting(two, SIZE);
title_memory_unmapping(two, SIZE);
for _ in 0..2 {
assert_eq!(guard(one, one + SIZE), Some(pages.clone()), "written through the part that stays");
}
// The first and last page stay mapped.
for k in [0, 2] {
title_memory_remapped(two + k * BLOCK, BLOCK);
crate::inplace::title_memory_view(two + k * BLOCK, BLOCK, section, (k * BLOCK) as u64);
}
drop(changing);
assert_eq!(guard(one, one + SIZE), Some(pages));
assert_eq!(guard(one, one + SIZE), Some(Vec::new()));
assert!(!writable(two) && writable(two + BLOCK) && !writable(two + 2 * BLOCK));
drop_views(section, &[one, two], SIZE);
}
/// A page shown in more than `MANY_VIEWS` views is guarded at each by
/// itself: the others stay writable, and nothing looks through them all.
#[test]
fn a_page_of_many_views_is_guarded_one_view_at_a_time() {
let (section, one, two) = two_views(BLOCK);
let filler = one + (1 << 45);
for n in 0..MANY_VIEWS {
crate::inplace::title_memory_view(filler + n * BLOCK, BLOCK, section, 0);
}
assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE]));
assert!(writable(two), "another view of it is left alone");
// SAFETY: the guarded view, opened by the handler.
unsafe { ((one + 8) as *mut u8).write(1) };
assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE]));
title_memory_remapped(filler, MANY_VIEWS * BLOCK);
drop_views(section, &[one, two], BLOCK);
}
/// A write or mapping that runs past the end of the address space (a
/// title's `fread` with a huge count) covers up to the end; the sum used
/// to overflow. Up there no test has guarded blocks.
@@ -2426,10 +2950,24 @@ mod many_askers_tests {
/// again between.
#[test]
fn no_write_to_views_is_lost_between_askers() {
writes_to_views_are_not_lost::<1>();
}
/// The same of pages shown at three addresses, each of which has copies
/// of its own: a write through any of them, or put past the guards, is
/// told at all. A fourth view comes and goes meanwhile, and is written
/// too. (The first assertion fails within a few rounds if a guard holds
/// for one address only, `VICTORY_VIEW_GUARD=0`.)
#[test]
fn no_write_through_another_view_is_lost_between_askers() {
writes_to_views_are_not_lost::<3>();
}
fn writes_to_views_are_not_lost<const VIEWS: usize>() {
const PAGES: usize = 12;
const THREADS: usize = 8;
// SAFETY: a view of a section of our own.
let at = unsafe {
// SAFETY: views of a section of our own.
let (section, all): (usize, [usize; VIEWS]) = unsafe {
let section = CreateFileMappingW(
-1isize as _,
std::ptr::null(),
@@ -2438,20 +2976,51 @@ mod many_askers_tests {
(PAGES * PAGE) as u32,
std::ptr::null(),
);
let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, PAGES * PAGE).Value as usize;
crate::title_memory_section(section as usize, (PAGES * PAGE) as u64, true);
super::title_memory_remapped(at, PAGES * PAGE);
crate::title_memory_view(at, PAGES * PAGE, section as usize, 0);
at
let all = std::array::from_fn(|_| {
let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, PAGES * PAGE).Value as usize;
assert!(at != 0 && at.is_multiple_of(PAGE));
super::title_memory_remapped(at, PAGES * PAGE);
crate::title_memory_view(at, PAGES * PAGE, section as usize, 0);
at
});
(section as usize, all)
};
assert!(at != 0 && at.is_multiple_of(PAGE));
let by_bits = std::sync::atomic::AtomicUsize::new(0);
let past = std::sync::atomic::AtomicUsize::new(0);
std::thread::scope(|s| {
if VIEWS > 1 {
s.spawn(move || {
let mut last = [0u64; VIEWS];
for round in 0..300usize {
let (page, asked) = (round * 5 % PAGES, round % VIEWS);
// SAFETY (all): a view of one page of the section,
// this thread's alone.
let one = unsafe {
MapViewOfFile(section as _, FILE_MAP_WRITE, 0, (page * PAGE) as u32, PAGE).Value as usize
};
assert_ne!(one, 0);
super::title_memory_remapped(one, PAGE);
crate::title_memory_view(one, PAGE, section, (page * PAGE) as u64);
unsafe { ((one + THREADS * 8) as *mut u64).write_volatile(round as u64) };
let (now, written) =
writes(all[asked] + page * PAGE, all[asked] + (page + 1) * PAGE, true).expect("a view");
let number = written.first().map_or(0, |w| w.1);
assert!(number > last[asked], "page {page}, through a new view: {number} is not after {}", last[asked]);
last[asked] = now.max(last[asked]);
{
let _changing = super::title_memory_remapping();
super::title_memory_unmapping(one, PAGE);
unsafe { UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: one as *mut _ }) };
}
last = [last[asked]; VIEWS];
}
});
}
for t in 0..THREADS {
let (by_bits, past) = (&by_bits, &past);
s.spawn(move || {
let mut last = [0u64; PAGES];
let mut last = [[0u64; PAGES]; VIEWS];
let mut seed = t as u64 * 7919 + 1;
let mut next = |n: usize| {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
@@ -2461,10 +3030,13 @@ mod many_askers_tests {
let page = next(PAGES);
let from = page - next(page.min(3) + 1);
let to = page + 1 + next((PAGES - page).min(3));
// Written through one view, asked about at another.
let (through, asked) = (all[next(VIEWS)], next(VIEWS));
let (at, last) = (all[asked], &mut last[asked]);
if next(4) != 0 {
// As in the test above, or after a word of ours,
// or past the guard.
let word = at + page * PAGE + t * 8;
let word = through + page * PAGE + t * 8;
// SAFETY (both): as above.
// (Waited for: other tests hold changes of mapping.)
let reading = (next(3) == 0).then(super::title_memory_reading);