victory-gta6: this fork's changes on top of VIctory main (ffe310e)

World rendering, lighting, frame-rate and memory work for Grand Theft Auto VI
(Xbox Series X profile) on one Windows PC with an NVIDIA RTX 4070. The README
describes the state, the changes and the credits. Based on VIctory by Marvisak
and contributors (GPL-3.0-or-later); XCL by ivall and contributors was used as
a reference. No game files are included.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
fxcelessandClaude Fable 5.2 committed 2026-11-24 13:02:18 -05:00
1 parent 45c6e80601
commit 6fa814fba5
61 files changed
+32259 -1274

No files matched your search

+193 -7
View File
@@ -20,18 +20,139 @@ pub(crate) fn folder() -> Option<&'static PathBuf> {
/// too, and their draws traced at debug level.
pub(crate) fn listed(n: u64) -> bool {
static LIST: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new();
LIST.get_or_init(|| {
let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default();
let named = LIST
.get_or_init(|| {
let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default();
list.split(',')
.filter_map(|f| f.trim().parse().ok())
.collect()
})
.contains(&n);
// `VICTORY_CAPTURE_WORLD`: also the 2nd and the 6th frame after the first
// one that ran 500 draws or more (a title's first 3D frames: their
// numbers depend on how long the menus were shown), and the 30th and
// the 80th (Grand Theft Auto VI opens with a cutscene made in the
// engine: later shots of it, in case the first is dark by design).
//
// `VICTORY_CAPTURE_WORLD_ALSO` (comma-separated): more frames counted
// from that first one (Grand Theft Auto VI's blue patches show from
// about the 118th frame on, when the window's model has arrived and
// the reflections hold values: none of the four above has them).
static ALSO: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new();
let also = ALSO.get_or_init(|| {
let list = std::env::var("VICTORY_CAPTURE_WORLD_ALSO").unwrap_or_default();
list.split(',')
.filter_map(|f| f.trim().parse().ok())
.collect()
})
.contains(&n)
});
let first = WORLD.load(std::sync::atomic::Ordering::Relaxed);
let after = n.wrapping_sub(first);
named || first != u64::MAX && ([2, 6, 30, 80].contains(&after) || also.contains(&after))
}
/// With a capture folder, for the frames [`listed`]: `what` is added to
/// the frame's `frame-<n>-ops.txt`, one line per draw, dispatch, copy or
/// drop in the order recorded (the title records on several threads, so
/// lines of different lists interleave; each names its list). The file
/// says which pass writes which target, to find the pass whose output
/// stays empty.
#[cfg(feature = "diagnostics")]
pub(crate) fn op(list: usize, what: impl FnOnce() -> String) {
use std::io::Write;
let frame = crate::queue::presented() + 1;
if !listed(frame) {
// Before the world: the last lines are kept, and written out when
// it starts (`before-world-ops.txt`): what the title drew just
// before (Grand Theft Auto VI shows a title card there, whose text
// did not show).
if world_on() && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX {
// At most 300 lines of a frame: the world's first frame alone
// (thousands of operations, recorded before it is known to be
// the world's) pushed everything before it out.
static IN_FRAME: std::sync::Mutex<(u64, u32)> = std::sync::Mutex::new((0, 0));
{
let mut in_frame = IN_FRAME.lock().unwrap_or_else(|e| e.into_inner());
if in_frame.0 != frame {
*in_frame = (frame, 0);
}
in_frame.1 += 1;
if in_frame.1 > 300 {
return;
}
}
let what = what();
let mut ring = RING.lock().unwrap_or_else(|e| e.into_inner());
if ring.len() >= RING_LINES {
ring.pop_front();
}
ring.push_back(format!("frame {frame} list {list:#x} {what}"));
}
return;
}
let Some(folder) = folder() else {
return;
};
static FILE: std::sync::Mutex<Option<(u64, u64, std::fs::File)>> = std::sync::Mutex::new(None);
let what = what();
let mut file = FILE.lock().unwrap_or_else(|e| e.into_inner());
if file.as_ref().is_none_or(|f| f.0 != frame) {
let Ok(made) = std::fs::File::create(folder.join(format!("frame-{frame}-ops.txt"))) else {
return;
};
*file = Some((frame, 0, made));
}
if let Some((_, n, f)) = file.as_mut() {
*n += 1;
let _ = writeln!(f, "{n} list {list:#x} {what}");
}
}
/// The last lines of [`op`] before the world.
#[cfg(feature = "diagnostics")]
static RING: std::sync::Mutex<std::collections::VecDeque<String>> =
std::sync::Mutex::new(std::collections::VecDeque::new());
#[cfg(feature = "diagnostics")]
const RING_LINES: usize = 6000;
/// Whether `VICTORY_CAPTURE_WORLD` is set.
fn world_on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_CAPTURE_WORLD").is_some())
}
/// The first frame that ran 500 draws or more (`VICTORY_CAPTURE_WORLD`).
static WORLD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX);
/// At the present of `frame`: the draws run on the host so far.
pub(crate) fn frame_drew(frame: u64, drawn: u64) {
use std::sync::atomic::Ordering::Relaxed;
static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let before = LAST.swap(drawn, Relaxed);
if world_on()
&& drawn.saturating_sub(before) >= 500
&& WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed).is_ok()
{
tracing::info!(frame, "the first frame of 500 draws or more: frames {} and {} are captured", frame + 2, frame + 6);
#[cfg(feature = "diagnostics")]
if let Some(folder) = folder() {
let lines: Vec<String> = std::mem::take(&mut *RING.lock().unwrap_or_else(|e| e.into_inner())).into();
let _ = std::fs::write(folder.join("before-world-ops.txt"), lines.join("
"));
}
}
}
/// Whether frame `n` is saved.
pub(crate) fn wanted(n: u64) -> bool {
folder().is_some() && (n.is_power_of_two() || listed(n))
// Before the world, with `VICTORY_CAPTURE_WORLD`: every 16th frame too
// (small pictures of menus, loading screens and title cards).
let before_world = world_on() && n % 16 == 0 && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX;
// In the world: every 8th frame's picture, a timeline of the opening
// cutscene (its shots do not fall on the same frame numbers from run to
// run, so single frames cannot be compared between runs).
let first = WORLD.load(std::sync::atomic::Ordering::Relaxed);
let in_world = world_on() && first != u64::MAX && n > first && (n - first) % 8 == 0;
folder().is_some() && (n.is_power_of_two() || listed(n) || before_world || in_world)
}
/// Saves 8-bit RGBA or BGRA rows (`pitch` bytes apart) as frame `n`.
@@ -281,6 +402,26 @@ fn dump_one(
}
let pitch = f.RowPitch as usize;
let rows = std::slice::from_raw_parts(data.cast::<u8>(), pitch * f.Height as usize);
// A 24-bit depth plane comes back as 32-bit words: which depth values
// (low 24 bits) and which top bytes it holds, the most common first.
if matches!(d.Format.0, 44..=47) {
let mut depths = std::collections::HashMap::<u32, u32>::new();
let mut tops = std::collections::HashMap::<u32, u32>::new();
for y in 0..f.Height as usize {
for x in 0..f.Width as usize {
let at = y * pitch + x * 4;
let w = u32::from_le_bytes(rows[at..at + 4].try_into().unwrap_or([0; 4]));
*depths.entry(w & 0xff_ffff).or_default() += 1;
*tops.entry(w >> 24).or_default() += 1;
}
}
let most = |m: std::collections::HashMap<u32, u32>| {
let mut v: Vec<(u32, u32)> = m.into_iter().collect();
v.sort_by_key(|e| std::cmp::Reverse(e.1));
(v.len(), v.into_iter().take(12).collect::<Vec<_>>())
};
tracing::info!(?resource, depths = ?most(depths), top_bytes = ?most(tops), "24-bit depth plane values (value, texels)");
}
if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) {
let name = format!(
"frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}",
@@ -384,9 +525,54 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option
(0.0, finite.fold(0.0f32, f32::max))
};
let range = (high - low).max(1e-20);
tracing::info!(format, low, high, "target values");
// How much of the target holds anything: a lit scene and one bright
// lamp on black have the same highest value.
let above = values.iter().filter(|v| v.iter().any(|c| c.is_finite() && *c > low)).count();
let nonzero_percent = above as f32 * 100.0 / values.len().max(1) as f32;
tracing::info!(format, low, high, nonzero_percent, "target values");
// Small float colour targets (the 1x1 luminance and exposure targets):
// every texel's four channels as numbers. The picture has no alpha and
// eight bits a channel.
if matches!(format, 1..=2 | 9..=10) && w * h <= 16 {
for y in 0..h {
for x in 0..w {
let b = px(x, y, n);
let texel: [f32; 4] = if n == 16 {
[0, 1, 2, 3].map(|i| f32::from_bits(u32_at(b, i)))
} else {
[0, 1, 2, 3].map(|i| half(u16_at(b, i)))
};
tracing::info!(format, x, y, ?texel, "target texel");
}
}
}
// R32_UINT targets hold packed light (the title reads them back as
// R9G9B9E5): as floats their low, high and share above the lowest say
// nothing. How many texels hold any bit, and the highest channel value
// of the packed reading.
if format == 42 {
let (mut set, mut packed_high) = (0usize, 0f32);
for y in 0..h {
for x in 0..w {
let v = u32_at(px(x, y, 4), 0);
set += usize::from(v != 0);
let scale = 2f32.powi((v >> 27) as i32 - 24);
for k in 0..3 {
packed_high = packed_high.max((v >> (9 * k) & 0x1ff) as f32 * scale);
}
}
}
let nonzero_bits_percent = set as f32 * 100.0 / (w * h).max(1) as f32;
tracing::info!(format, nonzero_bits_percent, packed_high, "target values as packed light");
}
// Float colours (scene light) go through a cube root: scaled linearly,
// a night scene under one lamp of 50 units came out all black.
let curved = matches!(format, 1..=2 | 9..=10 | 26);
for v in values {
let c = v.map(|c| (((c - low) / range).clamp(0.0, 1.0) * 255.0) as u8);
let c = v.map(|c| {
let t = ((c - low) / range).clamp(0.0, 1.0);
((if curved { t.cbrt() } else { t }) * 255.0) as u8
});
out.extend([c[0], c[1], c[2], 255]);
}
Some(out)
File diff suppressed because it is too large. Load diff
+433 -36
View File
@@ -99,6 +99,13 @@ impl Heap {
.as_ref()
}
/// The handle of descriptor `index` of this heap.
#[cfg(windows)]
pub(crate) fn handle(&self, index: u32) -> Option<u64> {
let step = u64::from(increment(self.desc.kind)?);
(index < self.desc.count).then(|| self.start + u64::from(index) * step)
}
/// The descriptor index of `handle` in this heap, if it lies in it.
pub(crate) fn index(&self, handle: u64) -> Option<u32> {
let step = u64::from(increment(self.desc.kind)?);
@@ -231,7 +238,8 @@ impl RtvRecord {
0,
]
};
words[0] = crate::resource::pc_format(words[0]);
// A target or depth view: of a target, in its stand-in format.
words[0] = crate::resource::target_format(crate::resource::pc_format(words[0]));
// SAFETY: both host view descriptions are 24 bytes in this layout.
Some(unsafe { (&raw const words).cast::<T>().read_unaligned() })
}
@@ -318,9 +326,21 @@ impl View {
/// generation, so descriptors (and host slots made from them) naming the
/// old one go stale instead of naming whatever is made at the same address
/// next.
/// shortcut: views without a resource object (constant buffers, memory
/// views, samplers) are kept for the run; they are bounded by the title's
/// memory and sampler states.
///
/// Views without a resource object have nothing that releases them, and a
/// title copies descriptors as bytes, so nothing says when the last
/// descriptor naming an entry is gone: such entries were kept for the run.
/// Grand Theft Auto VI writes some 14,000 constant buffer views a frame,
/// each at the address its constants have that frame: 2,450,139 entries
/// after four minutes of play, 1,047 MB with the index, and 11,000 more
/// every second (run 65). So the two kinds that carry an address are not
/// entries any more: their records name them whole ([`constant_words`],
/// [`placed_words`]), and the table holds only what is bounded: views of
/// resource objects (freed with the resource), samplers (as many as there
/// are sampler states), and the shapes of placed views (their descriptions
/// without the address: as many as the title has kinds of textures and
/// buffers, however often it moves them).
/// `VICTORY_VIEW_INLINE=0`: every view is an entry, as before.
struct Views {
/// Each entry's view and generation.
list: Vec<(View, u32)>,
@@ -328,6 +348,9 @@ struct Views {
/// Entries naming each resource.
by_resource: std::collections::BTreeMap<usize, Vec<u32>>,
free: Vec<u32>,
/// The shapes of views of placed memory, and where each is.
shapes: Vec<Shape>,
shape_index: std::collections::BTreeMap<Shape, u32>,
}
static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views {
@@ -335,9 +358,220 @@ static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views {
index: std::collections::BTreeMap::new(),
by_resource: std::collections::BTreeMap::new(),
free: Vec::new(),
shapes: Vec::new(),
shape_index: std::collections::BTreeMap::new(),
});
const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE");
/// A record is the tag and two words, `i` and `generation` (the host keeps
/// them as one 64-bit key per slot). The top two bits of `generation` say
/// what the other 62 bits are: 0, entry `i` of the table at that
/// generation; [`CONSTANT`], a constant buffer view, whole; [`PLACED`], a
/// view of placed memory: its address and the number of its shape.
const KIND_SHIFT: u32 = 30;
/// Table generations stay below the kind bits (and above 0).
const GENERATIONS: u32 = (1 << KIND_SHIFT) - 1;
const CONSTANT: u32 = 1;
const PLACED: u32 = 2;
/// Bits of a constant buffer view's address in its record: any address a
/// program can have. The 15 bits above them are its size.
const CONSTANT_ADDRESS_BITS: u32 = 47;
/// Bits of a placed view's address in its record: placed memory is title
/// memory, which lies below 1 TiB. The 22 bits above them number its shape.
const PLACED_ADDRESS_BITS: u32 = 40;
const SHAPES: usize = 1 << (62 - PLACED_ADDRESS_BITS);
/// A view of placed memory without its address: whether it is unordered
/// access, the resource description, and the view's words but the two that
/// hold the address (10 and 11).
type Shape = (bool, [u32; 14], [u32; 14]);
/// Whether constant buffer views and views of placed memory are named whole
/// in their records ([`Views`]). On by default; `VICTORY_VIEW_INLINE=0`
/// makes every view a table entry, as before.
fn inline() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_INLINE").is_none_or(|v| v != "0"))
}
/// Views named whole in their records since the start: constant buffer
/// views, views of placed memory (for the memory line).
static NAMED_WHOLE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
/// The two record words of the 62 bits `payload` of kind `kind`.
fn kind_words(kind: u32, payload: u64) -> [u32; 2] {
[payload as u32, kind << KIND_SHIFT | (payload >> 32) as u32]
}
/// The 62 bits two record words carry beside their kind.
fn payload(i: u32, generation: u32) -> u64 {
u64::from(generation & GENERATIONS) << 32 | u64::from(i)
}
/// The record words that name the constant buffer view of `size` bytes at
/// `address` whole; `None` if they cannot: an address past 47 bits, or a
/// size of 16 KiB or more that is no multiple of 256 or reaches 4 MiB (the
/// size has 15 bits: bytes below 16 KiB, else units of 256 bytes). Such a
/// view is a table entry.
fn constant_words(address: u64, size: u32) -> Option<[u32; 2]> {
if address >> CONSTANT_ADDRESS_BITS != 0 {
return None;
}
let code = if size < 1 << 14 {
u64::from(size)
} else if size.is_multiple_of(256) && size >> 8 < 1 << 14 {
1 << 14 | u64::from(size >> 8)
} else {
return None;
};
Some(kind_words(CONSTANT, code << CONSTANT_ADDRESS_BITS | address))
}
/// The constant buffer view [`constant_words`] named.
fn constant_of(i: u32, generation: u32) -> View {
let payload = payload(i, generation);
let code = (payload >> CONSTANT_ADDRESS_BITS) as u32;
let size = if code >> 14 == 0 { code } else { (code & 0x3fff) << 8 };
View::Constant(payload & ((1 << CONSTANT_ADDRESS_BITS) - 1), size)
}
/// A placed view's shape and its address.
fn shape_of(unordered: bool, resource: &[u32; 14], desc: &[u32; 16]) -> (Shape, u64) {
let mut rest = [0u32; 14];
rest[..10].copy_from_slice(&desc[..10]);
rest[10..].copy_from_slice(&desc[12..]);
(
(unordered, *resource, rest),
u64::from(desc[10]) | u64::from(desc[11]) << 32,
)
}
/// The record words that name the view of placed memory at `address` with
/// shape number `shape`.
fn placed_words(shape: u32, address: u64) -> [u32; 2] {
kind_words(PLACED, u64::from(shape) << PLACED_ADDRESS_BITS | address)
}
impl Views {
/// The number of `shape`, a new one if it is not there yet; `None` when
/// the shapes are full (the view is then a table entry).
fn shape(&mut self, shape: Shape) -> Option<u32> {
if let Some(&at) = self.shape_index.get(&shape) {
return Some(at);
}
if self.shapes.len() >= SHAPES {
return None;
}
let at = self.shapes.len() as u32;
self.shapes.push(shape);
self.shape_index.insert(shape, at);
Some(at)
}
/// The view of placed memory [`placed_words`] named.
fn placed_of(&self, i: u32, generation: u32) -> Option<View> {
let payload = payload(i, generation);
let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1);
let &(unordered, resource, rest) = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?;
let mut desc = [0u32; 16];
desc[..10].copy_from_slice(&rest[..10]);
(desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
desc[12..].copy_from_slice(&rest[10..]);
Some(View::Placed(unordered, resource, desc))
}
/// 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] {
let i = match self.index.get(&view) {
Some(&i) => i,
None => {
let i = match self.free.pop() {
Some(i) => {
self.list[i as usize].0 = view.clone();
i
}
None => {
self.list.push((view.clone(), 1));
self.list.len() as u32 - 1
}
};
for r in view.resources().into_iter().filter(|&r| r != 0) {
self.by_resource.entry(r).or_default().push(i);
}
self.index.insert(view, i);
i
}
};
[i, self.list[i as usize].1]
}
}
/// The two words that name `view` in a record: the view itself where its
/// kind allows ([`Views`]), else its table entry.
fn words_for(view: View) -> [u32; 2] {
use std::sync::atomic::Ordering::Relaxed;
if inline() {
match &view {
View::Constant(address, size) => {
if let Some(words) = constant_words(*address, *size) {
NAMED_WHOLE[0].fetch_add(1, Relaxed);
return words;
}
}
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) {
NAMED_WHOLE[1].fetch_add(1, Relaxed);
return placed_words(shape, address);
}
}
}
_ => {}
}
}
VIEWS.lock().unwrap_or_else(|e| e.into_inner()).entry(view)
}
/// For the memory line: the distinct views kept ([`Views`]), those of them
/// free for reuse, and the bytes the table and its index hold for them (an
/// estimate: an entry of the table, and one of the index with its share of
/// a tree node; the shapes likewise); then the entries that are constant
/// buffer views and views of placed memory (those that did not fit a
/// record, or all of them with `VICTORY_VIEW_INLINE=0`), the shapes of
/// placed views kept, and the views named whole in their records since the
/// start: constant buffer views, views of placed memory.
#[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 each = size_of::<(View, u32)>() as u64;
let shape = size_of::<Shape>() as u64;
let (mut constants, mut placed) = (0, 0);
for (view, _) in &views.list {
match view {
View::Constant(..) => constants += 1,
View::Placed(..) => placed += 1,
_ => {}
}
}
[
views.list.len() as u64,
views.free.len() as u64,
views.list.capacity() as u64 * each
+ views.index.len() as u64 * each * 3 / 2
+ views.shapes.capacity() as u64 * shape
+ views.shape_index.len() as u64 * shape * 3 / 2,
constants,
placed,
views.shapes.len() as u64,
NAMED_WHOLE[0].load(Relaxed),
NAMED_WHOLE[1].load(Relaxed),
]
}
impl View {
/// The resource objects the view names.
fn resources(&self) -> [usize; 2] {
@@ -347,43 +581,122 @@ impl View {
_ => [0, 0],
}
}
/// The texture object the view is of, if that texture has no host copy
/// yet (`crate::resource::host_waits`): a slot written with such a
/// view is left null until the texture is first used.
#[cfg(windows)]
fn waiting_texture(&self) -> Option<usize> {
match *self {
View::Shader(r, _) | View::Unordered(r, _, _)
if crate::resource::host_waits(r as This) =>
{
Some(r)
}
_ => None,
}
}
}
/// Title slots (their handles) written with a view of a texture object
/// that had no host copy then, by texture. A title texture gets its host
/// copy on first use (`resource.rs` `Hosted`), and Grand Theft Auto VI
/// writes each texture's views into its view heap when it creates the
/// texture: making those host slots would make every host copy at once.
/// They are made when the texture is: translated shaders index the heap
/// directly, so a slot is not always made again by the draw that reads it.
#[cfg(windows)]
static WAITING: std::sync::Mutex<std::collections::BTreeMap<usize, Vec<u64>>> =
std::sync::Mutex::new(std::collections::BTreeMap::new());
/// Textures given their host copy since [`make_waiting`] last ran.
#[cfg(windows)]
static MADE_LATE: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
/// Title texture `resource` was given its host copy (called under that
/// texture's own lock: nothing else is locked here).
#[cfg(windows)]
pub(crate) fn texture_made(resource: usize) {
MADE_LATE
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(resource);
}
/// The slot at `handle` was written with a view of texture `resource`,
/// which has no host copy: it waits for one.
#[cfg(windows)]
fn wait_for(resource: usize, handle: u64) {
/// A texture with more slots waiting than this is in use for all we
/// know (its views are being copied about): its host copy is made.
const MOST: usize = 64;
let many = {
let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner());
let slots = waiting.entry(resource).or_default();
if !slots.contains(&handle) {
slots.push(handle);
}
slots.len() > MOST
};
if many {
// Makes it, and notes it made.
let _ = crate::resource::host_copy(resource as This);
} else if !crate::resource::host_waits(resource as This) {
// Made by another thread since the slot was looked at: that making
// may have been taken by `make_waiting` before this slot was noted.
texture_made(resource);
}
}
/// Makes the host slots that waited for a texture's host copy, for the
/// textures made since the last call. Called before a submission runs, by
/// the thread that submits: a slot is read when a list runs.
#[cfg(windows)]
pub(crate) fn make_waiting() {
let made = std::mem::take(&mut *MADE_LATE.lock().unwrap_or_else(|e| e.into_inner()));
for resource in made {
let handles = WAITING
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&resource);
for handle in handles.into_iter().flatten() {
// Only if the slot still holds a view of that texture: the
// title may have written it since (and a view of another
// texture without a host copy must go on waiting).
// (Looked up first: the handle is read only while its heap is
// there.)
let Some((heap, index)) = shader_slot(handle) else {
continue;
};
let same = match view(handle) {
Some(View::Shader(r, _) | View::Unordered(r, _, _)) => r == resource,
_ => false,
};
if same && let Some(Some(host)) = heap.host.get() {
host.mirror(index, handle, true);
}
}
}
}
fn record(handle: u64, view: View) {
if handle == 0 {
return;
}
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let i = match views.index.get(&view) {
Some(&i) => i,
None => {
let i = match views.free.pop() {
Some(i) => {
views.list[i as usize].0 = view.clone();
i
}
None => {
views.list.push((view.clone(), 1));
views.list.len() as u32 - 1
}
};
for r in view.resources().into_iter().filter(|&r| r != 0) {
views.by_resource.entry(r).or_default().push(i);
}
views.index.insert(view, i);
i
}
};
let generation = views.list[i as usize].1;
let [i, generation] = words_for(view);
// SAFETY: the handle is a descriptor slot, at least 16 bytes.
unsafe { (handle as *mut [u32; 3]).write_unaligned([VIEW_TAG, i, generation]) };
drop(views);
#[cfg(windows)]
mirror(handle);
}
/// The title released `resource`: the views naming it go stale.
pub(crate) fn forget(resource: usize) {
#[cfg(windows)]
WAITING
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&resource);
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let Some(entries) = views.by_resource.remove(&resource) else {
return;
@@ -396,19 +709,27 @@ pub(crate) fn forget(resource: usize) {
continue;
}
views.index.remove(&view);
views.list[i as usize].1 = generation.wrapping_add(1).max(1);
// (Below the bits that say a record is no table entry.)
views.list[i as usize].1 = ((generation + 1) & GENERATIONS).max(1);
// The view's other resource (a counter) keeps a stale entry, which
// `forget` of that resource skips.
views.free.push(i);
}
}
/// The view of entry `i` if `generation` is still its own.
#[cfg(windows)]
/// The view the record words `i` and `generation` name: the one they hold
/// whole, or the view of entry `i` if `generation` is still its own.
fn view_at(i: u32, generation: u32) -> Option<View> {
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let (view, current) = views.list.get(i as usize)?;
(*current == generation).then(|| view.clone())
match generation >> KIND_SHIFT {
0 => {
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
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),
_ => None,
}
}
/// The view recorded at `handle`, if one is (and its resource is alive).
@@ -418,9 +739,10 @@ pub(crate) fn view(handle: u64) -> Option<View> {
}
// SAFETY: the handle is a descriptor slot the title passes back.
let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let (view, current) = views.list.get(i as usize)?;
(tag == VIEW_TAG && *current == generation).then(|| view.clone())
if tag != VIEW_TAG {
return None;
}
view_at(i, generation)
}
/// A description of `N` words, if the title passes one.
@@ -741,6 +1063,81 @@ mod tests {
heap[0] = 0;
}
/// Constant buffer views are named whole in their records: any address
/// a program can have, any size below 16 KiB, multiples of 256 bytes
/// up to 4 MiB; what does not fit says so.
#[test]
fn constant_views_fit_their_records() {
let top = (1u64 << CONSTANT_ADDRESS_BITS) - 1;
for address in [0u64, 0x100, 0x2602_0000, 0xd_6b60_0000, 0x7ffd_a34f_0000, top] {
for size in [0u32, 1, 255, 256, 4000, (1 << 14) - 1, 1 << 14, 65536, (1 << 22) - 256] {
let [i, generation] = constant_words(address, size).expect("fits");
assert_eq!(generation >> KIND_SHIFT, CONSTANT);
assert_eq!(view_at(i, generation), Some(View::Constant(address, size)), "{address:#x} {size}");
}
}
assert_eq!(constant_words(top + 1, 256), None, "an address past 47 bits");
assert_eq!(constant_words(0x1000, (1 << 14) + 1), None, "16 KiB or more, no multiple of 256");
assert_eq!(constant_words(0x1000, 1 << 22), None, "4 MiB");
// Different views never share their words.
assert_ne!(constant_words(0x1000, 256), constant_words(0x1000, 512));
assert_ne!(constant_words(0x1000, 256), constant_words(0x1100, 256));
assert_ne!(constant_words(0x1000, 1 << 14), constant_words(0x1000, 64));
}
/// The leak of run 65: a title that writes constant buffer views and
/// views of placed memory at ever new addresses adds nothing to the
/// table; one shape stands for all the placed views alike.
#[test]
fn views_at_new_addresses_add_no_entries() {
if !inline() {
return;
}
let null = std::ptr::null();
let slots = [0u64; 4];
let at = slots.as_ptr() as u64;
// A resource description and a view no other test uses.
let resource: [u32; 14] = std::array::from_fn(|k| 0x5ee0_0000 + k as u32);
let mut desc: [u32; 16] = std::array::from_fn(|k| 0x7a70_0000 + k as u32);
let mine = |v: &View| match v {
View::Constant(address, _) => (0x6_0000_0000..0x6_1000_0000).contains(address),
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();
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);
assert_eq!(view(at), Some(View::Constant(address, 512)));
let placed = 0xd_4940_0000 + n * 0x1_0000;
(desc[10], desc[11]) = (placed as u32, (placed >> 32) as u32);
create_placed_srv(null, &resource, &desc, at);
assert_eq!(view(at), Some(View::Placed(false, resource, desc)));
}
assert_eq!(entries(), 0, "no table entries");
assert_eq!(shapes(), 1, "one shape for 20,000 placed views");
// The same shape, unordered: another shape.
create_placed_uav(null, &resource, &desc, at);
assert_eq!(view(at), Some(View::Placed(true, resource, desc)));
assert_eq!(shapes(), 2);
// Placed memory past 1 TiB (not title memory) is a table entry.
(desc[10], desc[11]) = (0, 0x100);
create_placed_srv(null, &resource, &desc, at);
assert_eq!(view(at), Some(View::Placed(false, resource, desc)));
assert_eq!(entries(), 1);
// A record's words are the same for the same view (the host knows
// a slot's view by them), and differ with the address.
// SAFETY: both handles are slots of 32 bytes above.
let words = |handle: u64| unsafe { *(handle as *const [u32; 3]) };
let other = [0u64; 4];
create_cbv(null, &[0x40, 6, 512, 0], at);
create_cbv(null, &[0x40, 6, 512, 0], other.as_ptr() as u64);
assert_eq!(words(at), words(other.as_ptr() as u64));
create_cbv(null, &[0x140, 6, 512, 0], other.as_ptr() as u64);
assert_ne!(words(at), words(other.as_ptr() as u64));
}
/// A released resource's views go stale; the same view of a new
/// resource at the same address is a new record.
#[test]
File diff suppressed because it is too large. Load diff
+55
View File
@@ -346,6 +346,59 @@ fn feature_levels(data: *mut c_void) -> HRESULT {
}
}
/// Device methods 0x1c8 and 0x218 (`SLOT`). Grand Theft Auto VI calls both
/// (title+0x2477578 and title+0x24800d5) as `(this, description, interface
/// id, out)`, asks for `ID3D12PipelineState`, and on success keeps the
/// object `out` names and draws with it; on failure it goes without that
/// pipeline, silently. What the descriptions hold is not known: the calls
/// fail as they always did, with `out` null, and the first ones log the
/// description's words and what its first word points at, so that the two
/// methods can be written.
/// shortcut: not implemented. Answering `S_OK` here without making the
/// pipeline would hand the title whatever its stack held as an object.
extern "system" fn unknown_pipeline<const SLOT: usize>(
_: This,
desc: *const u8,
_iid: *const Iid,
out: *mut This,
) -> HRESULT {
use std::sync::atomic::{AtomicU32, Ordering};
static CALLS: [AtomicU32; 2] = [const { AtomicU32::new(0) }; 2];
let calls = CALLS[usize::from(SLOT == 0x218)].fetch_add(1, Ordering::Relaxed) + 1;
if !out.is_null() {
// SAFETY: the title's out pointer (a local of its own).
unsafe { *out = std::ptr::null() };
}
if calls <= 4 || calls.is_power_of_two() {
// Sixteen 64-bit words at `at`, read through the kernel: neither
// pointer is known to be mapped.
#[cfg(windows)]
let words = |at: usize| -> Option<Vec<u64>> {
let mut bytes = [0u8; 128];
(at != 0 && crate::host::read_into(at as *const u8, &mut bytes)).then(|| {
bytes
.chunks_exact(8)
.map(|c| c.iter().rev().fold(0u64, |v, &b| v << 8 | u64::from(b)))
.collect()
})
};
#[cfg(not(windows))]
let words = |_: usize| None::<Vec<u64>>;
let description = words(desc as usize);
let first = description
.as_ref()
.and_then(|w| words(w[0] as usize));
tracing::warn!(
slot = format_args!("{:#x}", SLOT),
calls,
description = format_args!("{description:x?}"),
first_points_at = format_args!("{first:x?}"),
"a pipeline creation method that is not implemented: the title goes without this pipeline"
);
}
E_NOTIMPL
}
/// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the
/// methods `ID3D12Device1` to `ID3D12Device8` add, in order: 3, 1, 3, 6, 9,
/// 1, 2, 9 (0x298-0x3a0, the console's own among them), then those of
@@ -382,8 +435,10 @@ static FUNCTIONS: Table<160> = {
f[39] = query::create as *const (); // 0x138
f[41] = signature::create as *const (); // 0x148
f[48] = queue::create_x as *const (); // 0x180
f[57] = unknown_pipeline::<0x1c8> as *const (); // 0x1c8
f[61] = descriptor::create_sampler_x as *const (); // 0x1e8
f[62] = pipeline::create_compute_x as *const (); // 0x1f0
f[67] = unknown_pipeline::<0x218> as *const (); // 0x218
f[69] = object::ignore as *const (); // 0x228 debug error filter
f[70] = descriptor::create_placed_srv as *const (); // 0x230
f[71] = descriptor::create_placed_uav as *const (); // 0x238
File diff suppressed because it is too large. Load diff
+24 -2
View File
@@ -219,6 +219,27 @@ struct Mode {
}
const _: () = assert!(size_of::<Mode>() == 32);
/// The size of the display the console reports: `VICTORY_DISPLAY_MODE=WxH`
/// if set (as a console reports the television it is plugged into: a
/// Series X on a 1080p set lists a 1080p mode), else 3840x2160.
/// shortcut: not yet the host display's own size by default; make it so
/// once a title is seen to render for the mode it is given.
fn display_size() -> (u32, u32) {
static SIZE: std::sync::OnceLock<(u32, u32)> = std::sync::OnceLock::new();
*SIZE.get_or_init(|| {
let asked = std::env::var("VICTORY_DISPLAY_MODE").ok().and_then(|v| {
let (w, h) = v.trim().split_once(['x', 'X'])?;
Some((w.trim().parse::<u32>().ok()?, h.trim().parse::<u32>().ok()?))
});
let size = match asked {
Some((w, h)) if (640..=7680).contains(&w) && (360..=4320).contains(&h) => (w, h),
_ => (3840, 2160),
};
tracing::info!(width = size.0, height = size.1, "display mode reported to the title");
size
})
}
/// The console's mode list: one 4K mode at 60 Hz (Grand Theft Auto VI looks
/// for a 120 Hz one to allow 120 Hz frame intervals).
/// shortcut: fixed mode, not the host display's; report the host's rates if
@@ -242,9 +263,10 @@ extern "system" fn modes(
return MORE_DATA;
}
*count = 1;
let (width, height) = display_size();
let mode = Mode {
width: 3840,
height: 2160,
width,
height,
refresh: [60, 1],
format: 0,
scanlines: 1, // progressive
+22 -2
View File
@@ -75,7 +75,7 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT
extern "system" fn release(this: This) -> u32 {
object::release_boxed::<Fence>(this)
}
extern "system" fn completed(this: This) -> u64 {
pub(crate) extern "system" fn completed(this: This) -> u64 {
fence(this).value.load(Ordering::Acquire)
}
extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT {
@@ -88,6 +88,19 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c
return S_OK;
}
if event.is_null() {
// With submissions sent to the card and not waited for
// (`crate::host::late`) the signal may be behind them: they are
// settled, which sets it.
#[cfg(windows)]
if crate::host::late() {
drop(waiters);
crate::host::settle_for_fence();
if fence.value.load(Ordering::Acquire) >= value {
return S_OK;
}
tracing::warn!(value, "blocking fence wait not implemented");
return E_NOTIMPL;
}
// shortcut: a null event means "block until reached"; nothing can
// reach it while no GPU work runs, so fail instead of hanging.
tracing::warn!(value, "blocking fence wait not implemented");
@@ -96,7 +109,8 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c
waiters.push((value, event as usize));
S_OK
}
pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
/// Moves the fence to `value` and sets the events that waited for it.
pub(crate) fn set(this: This, value: u64) {
let fence = fence(this);
let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner());
fence.value.store(value, Ordering::Release);
@@ -107,6 +121,12 @@ pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
}
!reached
});
}
pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
set(this, value);
// A queue may have waited for it: what it held runs now.
#[cfg(windows)]
crate::queue::release_held(false);
S_OK
}
+21 -1
View File
@@ -126,8 +126,22 @@ pub(crate) extern "system" fn wait(
token: *mut u64,
) -> HRESULT {
let origin = kind == ORIGIN;
let (tick, wait) = next_tick(kind);
let (mut tick, mut wait) = next_tick(kind);
let limit = Duration::from_millis(u64::from(timeout_ms));
// A blocking wait for an event that has happened since the last wait
// for it ended (a frame took longer than a tick) ends at once, on the
// tick that passed: sleeping on to the next one cost 17 ms of every
// 730 ms frame (run 58: "2.0 frame waits sleeping 16.8 ms"). Polls (a
// time-out shorter than a tick) answer as before.
// `VICTORY_LATE_WAITS=1` sleeps to the next tick, as before.
static SLEEP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*SLEEP.get_or_init(|| std::env::var_os("VICTORY_LATE_WAITS").is_some_and(|v| v == "1"))
&& limit >= wait
&& tick > last(kind).load(Ordering::Relaxed) + 1
{
tick -= 1;
wait = Duration::ZERO;
}
let hr = if wait > limit {
std::thread::sleep(limit);
TIMEOUT
@@ -136,6 +150,12 @@ pub(crate) extern "system" fn wait(
last(kind).fetch_max(tick, Ordering::Relaxed);
S_OK
};
#[cfg(all(windows, feature = "diagnostics"))]
{
use crate::copystat::{C, add};
add(C::PaceWaits, 1);
add(C::PaceUs, wait.min(limit).as_micros() as u64);
}
// A frame begun on a time-out takes no tick: its flip still does.
if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) {
// Tokens count frames (consecutive), not ticks.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+9 -1
View File
@@ -31,6 +31,8 @@ pub mod frame;
mod host;
#[cfg(windows)]
mod indirect;
#[cfg(windows)]
mod inplace;
pub mod list;
pub mod object;
pub mod pipeline;
@@ -45,6 +47,8 @@ mod sampler;
#[cfg(windows)]
pub mod shader_cache;
#[cfg(windows)]
mod memory;
#[cfg(windows)]
mod shadow;
pub mod signature;
#[cfg(windows)]
@@ -55,4 +59,8 @@ mod watch;
#[cfg(windows)]
pub use host::on_failure;
#[cfg(windows)]
pub use watch::{title_memory_remapped, writing as kernel_will_write};
pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view};
#[cfg(windows)]
pub use watch::{
title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write,
};
File diff suppressed because it is too large. Load diff
+319
View File
@@ -0,0 +1,319 @@
//! Title memory by address, for translated shaders that read and write
//! through raw 40-bit addresses (`victory_shader::emit::SLOT_MEMORY`: the
//! console's ray-tracing structure builder and the programs that walk its
//! structures; the structures themselves lie in plain title memory, in no
//! buffer object).
//!
//! The copies are the ones every other access uses ([`crate::shadow`]: a
//! title buffer's copy, or the 4 MiB window of memory outside buffers), so
//! a root view and a raw address reach the same host bytes. This module
//! keeps what a shader needs to find them:
//!
//! - the **directory**: per 64 KiB page of title address space the number
//! of the copy that holds the page (0: none) and the page's byte offset
//! in it; one buffer for all lists, entries only ever go from empty to
//! filled;
//! - per view heap a run of slots with a raw unordered access view of each
//! numbered copy (slot 0 of the run: a null view, for pages without a
//! copy);
//! - the **faults**: the page numbers shaders found empty, read back here
//! once a frame, so the copies exist from the next frame on. A pointer a
//! shader takes out of memory cannot be known before it runs; the
//! addresses a dispatch is given as root views are made ready before it.
//!
//! **A page that is not there when a shader touches it is a lost access**:
//! the read gives 0, the store is dropped, and the fault note only helps
//! the next frame. For the structure builder that is the same as a dropped
//! stage, so before a dispatch the host makes ready everything it can see
//! the dispatch name: the whole copy around each root view, around each
//! pair of root constants that is a title address and around each root
//! constant that is one in 256-byte units (the builder passes structures
//! all three ways), and the 4 MiB after each (a structure may cross a
//! window's end).
//! shortcut: what a stage reaches only through pointers it reads out of
//! memory (InitHeaders' table of structure addresses, LoadInstances'
//! instance records) is not made ready unless something else named it;
//! the fault count in the log says whether that happens. The whole answer
//! is the extent of the title's allocation around an address, which the
//! memory module of the layer knows and this one does not ask yet.
//!
//! shortcut: a copy that is numbered is kept for the rest of the run, and
//! there are at most [`COPIES`] of them (4 MiB windows mostly: 4 GiB at
//! most). Every dispatch of such a shader brings all numbered copies up to
//! date and, if it can store, declares all of them written (the bytes are
//! compared on the CPU afterwards, as for any unordered access view): a
//! dirty-page mask written by the shader would bound both.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use victory_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES};
use windows::Win32::Graphics::Direct3D12::*;
use crate::descriptor::host::HostHeap;
use crate::host::{HostList, host};
use crate::shadow::Shadow;
/// Copies that can be numbered (the run of heap slots is one longer). A
/// listed frame of the opening cutscene names about 50 windows.
const COPIES: u32 = 1023;
/// A window of memory outside buffers (`shadow.rs`).
const CELL: u64 = 4 << 20;
/// A directory page.
const PAGE: u64 = 1 << 16;
struct Memory {
/// Buffer, its mapping, its GPU address.
directory: (ID3D12Resource, *mut u32, u64),
faults: (ID3D12Resource, *mut u32, u64),
/// Copy `n` is `copies[n - 1]`.
copies: Vec<Arc<Shadow>>,
/// Per host view heap (by address): the first slot of its run, and how
/// many copies have their view there.
heaps: HashMap<usize, (u32, u32)>,
/// The frame the faults were last read in.
frame: u64,
/// Pages asked for this frame that are not the title's memory.
refused: std::collections::HashSet<u64>,
}
// SAFETY: the mappings are of buffers the struct owns; all access is under
// the mutex.
unsafe impl Send for Memory {}
static MEMORY: Mutex<Option<Memory>> = Mutex::new(None);
/// What a draw binds.
pub(crate) struct Ready {
pub(crate) directory: u64,
pub(crate) faults: u64,
/// The view heap slot of the null view; copy `n`'s view is `n` further.
pub(crate) base: u32,
}
impl Memory {
fn new() -> Option<Memory> {
let host = host()?;
let make = |dwords: u64, what: &str| {
let (buffer, data) = host.shared_buffer(dwords * 4)?;
crate::host::name(&buffer, || format!("title memory by address: {what}"));
// SAFETY: a fresh mapping of at least that many bytes.
unsafe { std::ptr::write_bytes(data, 0, (dwords * 4) as usize) };
// SAFETY: a live buffer.
let gpu = unsafe { buffer.GetGPUVirtualAddress() };
Some((buffer, data.cast::<u32>(), gpu))
};
tracing::info!("title memory by address: a shader reads or writes through raw addresses");
Some(Memory {
directory: make(u64::from(MEMORY_PAGES) * 2, "directory")?,
faults: make(u64::from(MEMORY_FAULTS), "faults")?,
copies: Vec::new(),
heaps: HashMap::new(),
frame: u64::MAX,
refused: Default::default(),
})
}
/// Gives the page of `address` its copy, if it has none and the memory
/// is the title's.
fn map(&mut self, address: u64) {
let page = address / PAGE;
// The last entry stays empty: addresses past the directory read it.
if page >= u64::from(MEMORY_PAGES) - 1 {
return;
}
// SAFETY: inside the directory's mapping.
let entry = unsafe { self.directory.1.add(page as usize * 2) };
// SAFETY: as above.
if unsafe { entry.read() } != 0 {
return;
}
let start = page * PAGE;
// A shader's pointer, or a constant taken for an address, may be
// anything: only memory the title has.
if self.refused.contains(&page) {
return;
}
if !crate::texture::committed(start as *const u8, PAGE as usize) {
self.refused.insert(page);
return;
}
// The copy a root view at that address would get; a buffer that
// ends inside the page is passed over for what holds all of it.
let whole = |s: &Arc<Shadow>| s.offset_in(start).is_some_and(|_| s.left(start) >= PAGE);
let Some(shadow) = crate::shadow::find(start, 1)
.filter(whole)
.or_else(|| crate::shadow::find(start, PAGE).filter(whole))
else {
return;
};
// SAFETY: a live buffer.
let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
return;
}
let n = match self.copies.iter().position(|c| Arc::ptr_eq(c, &shadow)) {
Some(n) => n,
None if self.copies.len() < COPIES as usize => {
self.copies.push(shadow.clone());
let n = self.copies.len() - 1;
// Every page the copy holds whole, not only the one asked
// for: a structure is more than 64 KiB.
// shortcut: a page of a title buffer inside this one that
// has a copy of its own is given this copy too.
let (first, len) = shadow.span();
let mut at = first.next_multiple_of(PAGE);
while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 {
// SAFETY: inside the directory's mapping.
let other = unsafe { self.directory.1.add((at / PAGE) as usize * 2) };
// SAFETY: as above; the offset first, as below.
unsafe {
if other.read() == 0 {
other.add(1).write_volatile((at - first) as u32);
other.write_volatile(n as u32 + 1);
}
}
at += PAGE;
}
n
}
None => {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros")
});
return;
}
};
let offset = shadow.offset_in(start).unwrap_or(0);
// The offset first: a shader that sees the number sees it too.
// SAFETY: inside the directory's mapping.
unsafe {
entry.add(1).write_volatile(offset as u32);
entry.write_volatile(n as u32 + 1);
}
}
/// The pages shaders found empty since the last frame.
fn take_faults(&mut self) {
let mut pages = Vec::new();
for i in 1..MEMORY_FAULTS as usize {
// SAFETY: inside the faults' mapping; the GPU may be writing,
// a number missed now is written again next frame.
let at = unsafe { self.faults.1.add(i) };
// SAFETY: as above.
let page = unsafe { at.read_volatile() };
if page != 0 {
pages.push(page);
// SAFETY: as above.
unsafe { at.write_volatile(0) };
}
}
if !pages.is_empty() {
// Each is an access that read 0 or was dropped.
static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 50 {
tracing::warn!(
pages = pages.len(),
first = format_args!("{:#x}", u64::from(pages[0]) * PAGE),
"title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now"
);
}
}
for page in pages {
self.map(u64::from(page) * PAGE);
}
}
/// What a dispatch names: the copy around `address` and the 4 MiB
/// after it.
fn name(&mut self, address: u64) {
self.map(address);
self.map((address & !(CELL - 1)) + CELL);
}
}
/// Before a draw whose shader reads title memory by address: what its
/// root arguments name gets its copies (`addresses`: its root views;
/// `constants`: its root constants, see the module), every numbered copy
/// has its view in `heap`'s run and is brought up to date when `list` is
/// submitted (and, with `writes`, copied back after). None if the host
/// cannot hold it; the draw is then dropped.
pub(crate) fn ready(
list: &HostList,
heap: &HostHeap,
addresses: &[u64],
constants: &[u32],
writes: bool,
) -> Option<Ready> {
let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner());
if guard.is_none() {
*guard = Memory::new();
}
let m = guard.as_mut()?;
let frame = crate::frame::current();
if m.frame != frame {
m.frame = frame;
m.refused.clear();
m.take_faults();
}
let numbered = m.copies.len();
for &address in addresses {
m.name(address);
}
// A title address in two constants (low dword, then bits 32 to 39), or
// in one in 256-byte units. A constant that only looks like one names
// memory nothing reads; one that is not the title's memory is refused.
for (i, &c) in constants.iter().enumerate() {
if let Some(&high) = constants.get(i + 1)
&& (1..=0xFF).contains(&high)
&& c >= 0x1_0000
{
m.name(u64::from(c) | u64::from(high) << 32);
}
if c >= 0x0100_0000 {
m.name(u64::from(c) << 8);
}
}
let key = std::ptr::from_ref(heap) as usize;
let (base, made) = match m.heaps.get(&key) {
Some(&run) => run,
None => {
// Held for the heap's life: not given back with a list's slots.
let base = heap.dynamic(COPIES + 1)?;
heap.null_raw_uav_at(base);
(base, 0)
}
};
for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) {
let (_, len) = shadow.span();
heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len);
}
m.heaps.insert(key, (base, m.copies.len() as u32));
// Once per list, and for copies numbered since: the builder alone
// dispatches hundreds of times a frame.
// shortcut: a copy another list numbers meanwhile is brought up to date
// by that list's submission, which may run after this one's.
const READ: usize = usize::MAX - 0x6d;
const WRITE: usize = usize::MAX - 0x6e;
let first_read = list.first_use(READ);
let first_write = writes && list.first_use(WRITE);
for (n, shadow) in m.copies.iter().enumerate() {
let (start, len) = shadow.span();
if first_read || n >= numbered {
shadow.refresh(list, start, len);
}
if writes && (first_write || n >= numbered) {
shadow.gpu_writes(list, start, len);
}
}
if first_read {
list.keep(&m.directory.0);
list.keep(&m.faults.0);
}
Some(Ready {
directory: m.directory.2,
faults: m.faults.2,
base,
})
}
+232 -14
View File
@@ -74,6 +74,28 @@ impl std::fmt::Debug for Shader {
/// Every container seen, by full content hash.
static SHADERS: Mutex<Option<HashMap<[u8; 32], Arc<Shader>>>> = Mutex::new(None);
/// For the memory lines: containers kept and their bytes, translations
/// kept and the bytes of their host code. None of them is ever let go.
static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
/// What the shader table and the pipeline library keep in memory:
/// containers and their bytes, translations and their bytes, the bytes of
/// the library's file (kept whole while the library lives) and what its
/// last save wrote.
#[cfg(windows)]
pub(crate) fn kept() -> [u64; 7] {
use std::sync::atomic::Ordering::Relaxed;
[
KEPT[0].load(Relaxed),
KEPT[1].load(Relaxed),
KEPT[2].load(Relaxed),
KEPT[3].load(Relaxed),
library::BLOB.load(Relaxed),
library::SAVED.load(Relaxed),
library::TRIMMED_BYTES.load(Relaxed),
]
}
/// The shared container for `bytes`.
fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
let full = blake3::hash(bytes);
@@ -82,6 +104,8 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
.get_or_insert_with(HashMap::new)
.entry(*full.as_bytes())
.or_insert_with(|| {
KEPT[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
KEPT[1].fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed);
Arc::new(Shader {
stage,
hash: full.to_hex()[..16].to_owned(),
@@ -98,6 +122,9 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
pub(crate) struct Translated {
pub(crate) host: victory_shader::emit::HostShader,
pub(crate) used: Vec<victory_shader::UsedResource>,
/// Whether the shader's code can store to buffer memory ([`stores`]);
/// true when its code is not known.
pub(crate) stores: bool,
}
#[cfg(windows)]
@@ -108,6 +135,21 @@ impl Shader {
self.translated
.get_or_init(|| {
let done = translate(&self.container);
// `VICTORY_SHADER_SAVE=<dir>`: each shader as the title gave it (`.cdxil`) and as
// translated (`.dxil`), by the hash crash reports name it with
if let Some(dir) = std::env::var_os("VICTORY_SHADER_SAVE") {
let dir = std::path::PathBuf::from(dir);
let _ = std::fs::create_dir_all(&dir);
let stem = format!("{}.{}", self.hash, self.stage);
let _ = std::fs::write(dir.join(format!("{stem}.cdxil")), &self.container);
if let Ok(t) = &done {
let _ = std::fs::write(dir.join(format!("{stem}.dxil")), &t.host.dxil);
}
}
if let Ok(t) = &done {
KEPT[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
KEPT[3].fetch_add(t.host.dxil.len() as u64, std::sync::atomic::Ordering::Relaxed);
}
match &done {
Ok(t) => tracing::info!(
stage = self.stage,
@@ -132,23 +174,170 @@ impl Shader {
#[cfg(windows)]
fn translate(container: &[u8]) -> Result<Translated, String> {
use victory_shader::{Container, FourCC, HwStage};
let host = crate::shader_cache::host_shader(container)?;
// The translation depends on it (a view index past a capped heap).
crate::descriptor::host::probe_view_limit();
let c = Container::parse(container).map_err(|e| e.to_string())?;
let used = match c.part(FourCC::DXIL) {
Some(part) => victory_shader::native_programs(part.data)
.map_err(|e| e.to_string())?
.into_iter()
.find(|p| {
matches!(
p.stage,
HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs
)
})
.map(|p| p.used)
.unwrap_or_default(),
let programs = match c.part(FourCC::DXIL) {
Some(part) => victory_shader::native_programs(part.data).map_err(|e| e.to_string())?,
None => Vec::new(),
};
Ok(Translated { host, used })
let host = crate::shader_cache::host_shader(container)?;
let stores = programs.is_empty() || programs.iter().any(stores);
let used = programs
.into_iter()
.find(|p| {
matches!(
p.stage,
HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs
)
})
.map(|p| p.used)
.unwrap_or_default();
Ok(Translated { host, used, stores })
}
/// The compute pipelines of the console's ray-tracing structure builder
/// (`XboxBvhBuilder.dll`; its programs are the ones with a spilled
/// user-data table) run **all or none**. Its stages feed each other
/// through memory: a stage that runs on what a dropped stage never wrote
/// computes its store offsets from garbage. The structures lie in plain
/// title memory, between the title's own objects, and a root view has no
/// size, so those stores land on the neighbours (run 98, with 14 of 35
/// stages translated: the title died within a second of the first builder
/// submission, on pointers that had become bounding-box bit patterns).
///
/// So a builder dispatch runs only while every builder pipeline the title
/// has created has a host pipeline; the first builder dispatch makes them
/// all on the spot instead of over the next frames (a stage "still being
/// made" would be a dropped stage). One that cannot be made turns the
/// builder off for the rest of the run.
///
/// shortcut: and only with `VICTORY_BVH_BUILDER=1`, until a run has shown
/// the whole builder and the host side of title memory by address
/// (`memory.rs`) working on a card; nothing reads the structures before
/// the programs that walk them translate.
#[cfg(windows)]
struct Builder {
pipelines: Vec<Arc<make::Pending>>,
/// Every one of `pipelines` has a host pipeline.
whole: bool,
/// One could not be made.
off: bool,
}
#[cfg(windows)]
static BUILDER: Mutex<Builder> = Mutex::new(Builder {
pipelines: Vec::new(),
whole: false,
off: false,
});
/// Whether `shaders` are a pipeline of the structure builder.
#[cfg(windows)]
fn of_builder(shaders: &[Arc<Shader>]) -> bool {
use victory_shader::{Container, FourCC};
let [shader] = shaders else { return false };
if shader.stage != "compute" {
return false;
}
let Ok(c) = Container::parse(&shader.container) else {
return false;
};
c.part(FourCC::DXIL)
.and_then(|part| victory_shader::native_programs(part.data).ok())
.is_some_and(|programs| programs.iter().any(victory_shader::spill::is_spilled))
}
/// `VICTORY_BVH_QUARANTINE=1`: what the structure builder's stages store
/// stays in the host's copies and is not copied back into title memory. A
/// check for a first run of the whole builder: a stage that stores where
/// it should not can then not reach the title's own objects (run 98), and
/// the programs that walk the structures read the host's copies anyway.
/// shortcut: not a way to run: the title also reads results back (sizes,
/// counters) and gets none, and a copy's pages are overwritten from title
/// memory when the title writes them.
#[cfg(windows)]
pub(crate) fn builder_quarantined(this: This) -> bool {
static ON: OnceLock<bool> = OnceLock::new();
is_builder(this) && *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_QUARANTINE").is_some_and(|v| v == "1"))
}
/// Whether the title's pipeline `this` is one of the structure builder's.
#[cfg(windows)]
pub(crate) fn is_builder(this: This) -> bool {
!this.is_null() && pipeline(this).builder
}
/// A stage of the builder was dropped after all: none runs from here on.
#[cfg(windows)]
pub(crate) fn builder_off(why: &'static str) {
let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner());
if !b.off {
b.off = true;
tracing::warn!(why, "the ray-tracing structure builder is turned off for the rest of the run: its stages run all or none");
}
}
/// At a dispatch of a builder pipeline: whether the builder runs (see
/// [`Builder`]).
#[cfg(windows)]
pub(crate) fn builder_runs() -> bool {
static ALLOWED: OnceLock<bool> = OnceLock::new();
if !*ALLOWED.get_or_init(|| std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1")) {
return false;
}
let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner());
if b.off {
return false;
}
if b.whole {
return true;
}
let missing = b.pipelines.iter().filter(|p| !make::now(p)).count();
if missing > 0 {
b.off = true;
tracing::warn!(
missing,
of = b.pipelines.len(),
"the ray-tracing structure builder stays off: not all of its programs have a host pipeline, and its stages run all or none"
);
return false;
}
tracing::info!(
pipelines = b.pipelines.len(),
"the ray-tracing structure builder runs: all of its programs have host pipelines"
);
b.whole = true;
true
}
/// Whether a console program can store to buffer memory: it has a buffer,
/// typed-buffer, scalar-memory, flat or global store or atomic, or code
/// that is not all known (an instruction of those kinds outside our table,
/// an indirect jump, code that does not decode). Stores to textures
/// (image instructions) and to the program's own scratch memory do not
/// count: neither reaches a buffer's host copy. After upstream #413,
/// which leaves scalar-memory stores out and counts image stores.
#[cfg(windows)]
fn stores(program: &victory_shader::NativeProgram) -> bool {
use victory_shader::gfx10::{Encoding, decode};
let Ok(code) = decode(&program.code) else {
return true;
};
code.iter().any(|i| {
let name = i.name();
match i.encoding {
Encoding::Mubuf
| Encoding::Mtbuf
| Encoding::Smem
| Encoding::Flat
| Encoding::Global => name.is_none_or(|n| {
(n.contains("store") || n.contains("atomic")) && !n.contains("scratch")
}),
Encoding::Sop1 => name.is_none_or(|n| matches!(n, "s_setpc_b64" | "s_swappc_b64")),
_ => false,
}
})
}
#[repr(C)]
@@ -163,6 +352,9 @@ struct Pipeline {
/// (by a worker: the title may release the pipeline meanwhile).
#[cfg(windows)]
host: Arc<make::Pending>,
/// One of the ray-tracing structure builder's ([`Builder`]).
#[cfg(windows)]
builder: bool,
}
const _: () = assert!(offset_of!(Pipeline, packet) == 0x10);
@@ -274,6 +466,7 @@ pub(crate) fn note_drop(this: This) {
/// Counts a draw or dispatch dropped for `why` (diagnostics).
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) fn note_why(why: String) {
crate::capture::op(0, || format!("DROPPED {why}"));
let mut drops = DROPS.lock().unwrap_or_else(|e| e.into_inner());
*drops.get_or_insert_with(HashMap::new).entry(why).or_default() += 1;
}
@@ -311,11 +504,22 @@ fn hand_out(
let host = Arc::new(make::Pending::new(shaders.clone(), graphics));
#[cfg(windows)]
make::early(&host);
#[cfg(windows)]
let builder = of_builder(&shaders);
#[cfg(windows)]
if builder {
// Another stage: the group is looked at again at its next dispatch.
let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner());
b.pipelines.push(host.clone());
b.whole = false;
}
let pipeline = Box::new(Pipeline {
object: Object::new(&FUNCTIONS),
packet: [0; 8],
#[cfg(windows)]
host,
#[cfg(windows)]
builder,
shaders,
bound: std::sync::atomic::AtomicBool::new(false),
});
@@ -490,6 +694,20 @@ mod library;
#[cfg(windows)]
mod make;
/// Lets the pipeline library's mapped file go from memory when no pipeline
/// has loaded for a while (`library::trim`); called by the host's sweep.
#[cfg(windows)]
pub(crate) fn trim_library() {
library::trim();
}
/// The pipeline library's part of the report when the host device is
/// removed (`library::removal_note`).
#[cfg(windows)]
pub(crate) fn library_removal_note() -> String {
library::removal_note()
}
/// Keeps compiled host pipelines, and the list of title pipelines to start
/// early, in `dir` (a folder of the cache) across runs.
#[cfg(windows)]
+274 -17
View File
@@ -109,6 +109,15 @@ impl GraphicsState {
// pipeline uses the plain description); bring it back
// with a stream if a title enables it.
let d = data.cast::<D3D12_DEPTH_STENCIL_DESC1>().read_unaligned();
if d.DepthBoundsTestEnable.as_bool() {
static SEEN: std::sync::atomic::AtomicU64 =
std::sync::atomic::AtomicU64::new(0);
if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
tracing::warn!(
"a pipeline enables the depth bounds test, which its host pipeline leaves out: its draws pass at every depth"
);
}
}
self.depth = D3D12_DEPTH_STENCIL_DESC {
DepthEnable: d.DepthEnable,
DepthWriteMask: d.DepthWriteMask,
@@ -156,7 +165,9 @@ impl GraphicsState {
15 => {
self.targets = data.cast::<D3D12_RT_FORMAT_ARRAY>().read_unaligned();
for f in &mut self.targets.RTFormats {
f.0 = crate::resource::pc_format(f.0 as u32) as i32;
f.0 = crate::resource::target_format(crate::resource::pc_format(
f.0 as u32,
)) as i32;
}
}
16 => {
@@ -243,6 +254,17 @@ pub(crate) struct Input {
const RECTANGLES: i32 = 19;
const QUADS: i32 = 32;
/// Whether the title's root SRVs are bound as one-view tables of the
/// buffer's host copy, whose reads past its end return zeros, rather than
/// as root descriptors, which have no size: a mesh shader's vertex fetch
/// has no record limit, and a read past the copy reaches whatever the host
/// placed after it (memory it has freed: the device is removed, upstream
/// PR #493). `VICTORY_ROOT_SRV_DIRECT=1` goes back to root descriptors.
pub(crate) fn bounded_root_srvs() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_ROOT_SRV_DIRECT").is_none())
}
/// One stage of a host pipeline and where its bindings go.
pub(crate) struct Stage {
pub(crate) shader: Arc<Shader>,
@@ -251,6 +273,9 @@ pub(crate) struct Stage {
/// Root parameters of its root views: (title root parameter, ours).
pub(crate) root_cbvs: Vec<(u8, u32)>,
pub(crate) root_srvs: Vec<(u8, u32)>,
/// Root UAVs: one-view tables like the SRVs (or root descriptors with
/// `VICTORY_ROOT_SRV_DIRECT=1`).
pub(crate) root_uavs: Vec<(u8, u32)>,
}
impl Stage {
@@ -273,8 +298,15 @@ pub(crate) struct HostPipeline {
/// The vertex buffer slots it reads (bit per slot).
pub(crate) slots: u32,
pub(crate) inputs: Vec<Input>,
/// Has the geometry stage that completes the console's rectangles
/// (`victory_shader::emit::rect_list_gs`): its rectangle draws go out
/// as the title gives them, three vertices a rectangle.
pub(crate) rects: bool,
/// Its shaders, for reports of slow submissions.
pub(crate) name: String,
/// Its depth, stencil, cull and blend state in short, for the frame
/// listing (empty for compute).
pub(crate) state: String,
}
/// Logs a pipeline that gets no host pipeline, once per reason.
@@ -292,6 +324,9 @@ impl HostPipeline {
/// A host pipeline for vertex and pixel shaders with the graphics
/// state `g`, or for one compute shader.
pub(crate) fn new(shaders: &[Arc<Shader>], g: Option<&GraphicsState>) -> Option<HostPipeline> {
// For the report when the host device is removed: what this thread
// has in the library from here on.
super::library::label(format!("{shaders:?}"));
let find = |stage| shaders.iter().find(|s| s.stage == stage);
let compute = match shaders {
[cs] if cs.stage == "compute" => Some(cs),
@@ -330,6 +365,9 @@ impl HostPipeline {
// The root signature the translated shaders' bindings define.
let mut params: Vec<D3D12_ROOT_PARAMETER1> = Vec::new();
// The ranges table parameters point at, alive until the root
// signature is made.
let mut ranges: Vec<Box<D3D12_DESCRIPTOR_RANGE1>> = Vec::new();
let mut samplers = Vec::new();
let mut bound = Vec::new();
for &(shader, visibility) in &stages {
@@ -339,6 +377,7 @@ impl HostPipeline {
user_data: None,
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
root_uavs: Vec::new(),
};
let dwords = t.user_data_dwords();
if dwords > 0 {
@@ -366,8 +405,55 @@ impl HostPipeline {
D3D12_ROOT_PARAMETER_TYPE_SRV,
&mut stage.root_srvs,
),
(
&t.root_uavs,
D3D12_ROOT_PARAMETER_TYPE_UAV,
&mut stage.root_uavs,
),
] {
for &slot in slots {
let uav = kind == D3D12_ROOT_PARAMETER_TYPE_UAV;
// Ours, not the title's, stay root descriptors: the
// table of strides, the directory of title memory by
// address and its fault notes.
let ours = if uav {
slot == victory_shader::emit::SLOT_FAULTS
} else {
slot == victory_shader::emit::SLOT_STRIDES
|| slot == victory_shader::emit::SLOT_MEMORY
};
if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() {
// A one-view table: the view's size bounds the
// reads (and a root UAV's writes), which a root
// descriptor leaves unbounded.
// (Our own table of strides stays a descriptor.)
ranges.push(Box::new(D3D12_DESCRIPTOR_RANGE1 {
RangeType: if uav {
D3D12_DESCRIPTOR_RANGE_TYPE_UAV
} else {
D3D12_DESCRIPTOR_RANGE_TYPE_SRV
},
NumDescriptors: 1,
BaseShaderRegister: u32::from(slot),
RegisterSpace: ROOT_CBV_SPACE,
Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE
| D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE,
OffsetInDescriptorsFromTableStart: 0,
}));
let range: *const D3D12_DESCRIPTOR_RANGE1 = &**ranges.last()?;
out.push((slot, params.len() as u32));
params.push(D3D12_ROOT_PARAMETER1 {
ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE,
Anonymous: D3D12_ROOT_PARAMETER1_0 {
DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 {
NumDescriptorRanges: 1,
pDescriptorRanges: range,
},
},
ShaderVisibility: visibility,
});
continue;
}
out.push((slot, params.len() as u32));
params.push(D3D12_ROOT_PARAMETER1 {
ParameterType: kind,
@@ -451,6 +537,8 @@ impl HostPipeline {
name: format!("{shaders:?}"),
slots: 0,
inputs: Vec::new(),
rects: false,
state: String::new(),
});
}
let Some(g) = g else {
@@ -458,8 +546,12 @@ impl HostPipeline {
};
let state = g.describe();
if mesh.is_some() {
// "triangles": the stream names its topology since it did not
// load from the library without one (see `mesh_pipeline`); a
// new name keeps such entries, stored before, from being
// looked up again.
let name = super::library::name(
"mesh",
"mesh triangles",
&root_blob,
&[&code_bytes(&code(0)), &code_bytes(&code(1))],
&state,
@@ -483,14 +575,35 @@ impl HostPipeline {
name: format!("{shaders:?}"),
slots: 0,
inputs: Vec::new(),
rects: false,
state: String::new(),
});
}
let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
// A pipeline the title makes for rectangles gets a geometry stage
// that completes each one from the three vertices the vertex
// shader made. Without it (refused here or by the host) the draws
// fall back on what `draw` does for rectangles.
let mut rect_gs = None;
if g.topology.0 == RECTANGLES {
let ps = stages.get(1).and_then(|(s, _)| s.translated());
let vs = &stages[0].0.translated()?.host.dxil;
match victory_shader::emit::rect_list_gs(vs, ps.map(|t| &t.host.dxil[..])) {
Ok(gs) => rect_gs = Some(gs),
Err(e) => tracing::warn!(error = %e, ?shaders, "no rectangle geometry stage"),
}
}
let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
// SAFETY: a borrowed pointer the description never releases.
pRootSignature: unsafe { std::mem::transmute_copy(&root) },
VS: code(0),
PS: code(1),
GS: rect_gs.as_ref().map_or(D3D12_SHADER_BYTECODE::default(), |gs| {
D3D12_SHADER_BYTECODE {
pShaderBytecode: gs.as_ptr().cast(),
BytecodeLength: gs.len(),
}
}),
BlendState: g.blend,
SampleMask: g.sample_mask,
RasterizerState: g.rasterizer,
@@ -512,19 +625,40 @@ impl HostPipeline {
SampleDesc: g.samples,
..Default::default()
};
let name = super::library::name(
"graphics",
&root_blob,
&[&code_bytes(&code(0)), &code_bytes(&code(1))],
&state,
);
let made = super::library::pipeline(
&name,
// SAFETY: the description points at live data.
|library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) },
// SAFETY: as above.
|| unsafe { host.device.CreateGraphicsPipelineState(&desc) },
);
// A pipeline with the geometry stage has a name of its own in the
// library; the others keep theirs.
let name = |gs: Option<&Vec<u8>>| match gs {
Some(gs) => super::library::name(
"graphics rectangles",
&root_blob,
&[&code_bytes(&code(0)), &code_bytes(&code(1)), &gs[..]],
&state,
),
None => super::library::name(
"graphics",
&root_blob,
&[&code_bytes(&code(0)), &code_bytes(&code(1))],
&state,
),
};
let make = |desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, name: &str| {
super::library::pipeline(
name,
// SAFETY: the description points at live data.
|library, name| unsafe { library.LoadGraphicsPipeline(name, desc) },
// SAFETY: as above.
|| unsafe { host.device.CreateGraphicsPipelineState(desc) },
)
};
let mut made = make(&desc, &name(rect_gs.as_ref()));
if made.is_err() && rect_gs.is_some() {
// The host refused the geometry stage: once more without it.
tracing::warn!(?shaders, "host pipeline refused with the rectangle geometry stage");
host.log_messages();
desc.GS = D3D12_SHADER_BYTECODE::default();
rect_gs = None;
made = make(&desc, &name(None));
}
let pso = match made {
Ok(pso) => pso,
Err(e) => {
@@ -553,12 +687,49 @@ impl HostPipeline {
name: format!("{shaders:?}"),
slots: g.slots(),
inputs: g.elements(),
rects: rect_gs.is_some(),
state: {
let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]);
let face = |f: &D3D12_DEPTH_STENCILOP_DESC| {
format!(
"fail {} depth-fail {} pass {} func {}",
f.StencilFailOp.0, f.StencilDepthFailOp.0, f.StencilPassOp.0, f.StencilFunc.0
)
};
format!(
"depth {} write {} func {}; stencil {} read {:#x} write {:#x} front [{}] back [{}]; cull {} front-ccw {}; blend {} src {} dst {} op {} mask {:#x}",
d.DepthEnable.as_bool(),
d.DepthWriteMask.0,
d.DepthFunc.0,
d.StencilEnable.as_bool(),
d.StencilReadMask,
d.StencilWriteMask,
face(&d.FrontFace),
face(&d.BackFace),
r.CullMode.0,
r.FrontCounterClockwise.as_bool(),
b.BlendEnable.as_bool(),
b.SrcBlend.0,
b.DestBlend.0,
b.BlendOp.0,
b.RenderTargetWriteMask
)
},
})
}
}
/// A mesh pipeline from the title's graphics state: the pipeline-state
/// stream form (no input layout or topology).
/// stream form (no input layout).
///
/// The stream names a triangle topology, which D3D12 does not need for a
/// mesh shader: without it the pipeline library refuses to load a stored
/// pipeline with the very stream it was made from (`E_INVALIDARG`; debug
/// layer message 972, "does not match the one used to create the PSO"), so
/// every mesh pipeline was compiled again, and its store then refused (970,
/// "already exists"). The translation makes triangle mesh shaders only
/// (`mesh_prologue` refuses others), and the debug layer wants the two to
/// agree (1323).
fn mesh_pipeline(
device: &ID3D12Device,
root: &ID3D12RootSignature,
@@ -583,6 +754,7 @@ fn mesh_pipeline(
targets: Sub<D3D12_RT_FORMAT_ARRAY>,
dsv: Sub<DXGI_FORMAT>,
samples: Sub<DXGI_SAMPLE_DESC>,
topology: Sub<D3D12_PRIMITIVE_TOPOLOGY_TYPE>,
}
let mut stream = Stream {
root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()),
@@ -595,6 +767,10 @@ fn mesh_pipeline(
targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets),
dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format),
samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples),
topology: Sub(
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
),
};
let desc = D3D12_PIPELINE_STATE_STREAM_DESC {
SizeInBytes: size_of::<Stream>(),
@@ -665,3 +841,84 @@ fn root_signature(
Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec()))
}
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use super::*;
/// A triangle mesh shader of our own and a pixel shader for it.
const MS: &str = "struct V { float4 p : SV_Position; };
[outputtopology(\"triangle\")] [numthreads(1, 1, 1)]
void main(out vertices V v[3], out indices uint3 t[1]) {
SetMeshOutputCounts(3, 1);
v[0].p = float4(0, 0, 0, 1);
v[1].p = float4(1, 0, 0, 1);
v[2].p = float4(0, 1, 0, 1);
t[0] = uint3(0, 1, 2);
}";
const PS: &str = "float4 main() : SV_Target { return 1; }";
/// The PC `dxc.exe` (`VICTORY_PC_DXC`, else the newest Windows SDK's).
fn dxc() -> Option<PathBuf> {
let dxc = match std::env::var_os("VICTORY_PC_DXC") {
Some(p) => PathBuf::from(p),
None => victory_shader::emit::validator::Validator::default_path()?
.with_file_name("dxc.exe"),
};
dxc.exists().then_some(dxc)
}
fn compile(dxc: &Path, dir: &Path, src: &str, profile: &str) -> Vec<u8> {
let (hlsl, out) = (
dir.join(format!("{profile}.hlsl")),
dir.join(format!("{profile}.dxil")),
);
std::fs::write(&hlsl, src).unwrap();
let status = std::process::Command::new(dxc)
.args(["-nologo", "-T", profile, "-E", "main", "-Fo"])
.arg(&out)
.arg(&hlsl)
.status()
.unwrap();
assert!(status.success(), "dxc failed for {profile}");
std::fs::read(out).unwrap()
}
fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE {
D3D12_SHADER_BYTECODE {
pShaderBytecode: bytes.as_ptr().cast(),
BytecodeLength: bytes.len(),
}
}
/// A mesh pipeline made once is loaded from the library the next time,
/// not compiled again (a stream without a topology never loads).
#[test]
fn a_mesh_pipeline_loads_from_the_library() {
let Some(host) = host() else {
return; // no host GPU here
};
let Some(dxc) = dxc() else {
eprintln!("no PC dxc.exe; skipped");
return;
};
let dir = tempfile::tempdir().unwrap();
let ms = compile(&dxc, dir.path(), MS, "ms_6_5");
let ps = compile(&dxc, dir.path(), PS, "ps_6_5");
let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap();
let mut g = GraphicsState::default();
g.targets.NumRenderTargets = 1;
g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
let name = super::super::library::name("mesh test", &root_blob, &[&ms, &ps], &g.describe());
mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, &name).expect("made");
let loaded = super::super::library::LOADED.load(Ordering::Relaxed);
mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, &name).expect("made again");
assert!(
super::super::library::LOADED.load(Ordering::Relaxed) > loaded,
"the mesh pipeline was compiled again instead of loaded from the library"
);
}
}
+632 -48
View File
@@ -12,13 +12,45 @@
//! graphics state); the next run hands those to the workers at
//! creation, during loading.
//!
//! All library calls are serialised: the interface does not promise that
//! stores, loads and serialising may overlap.
//! Library calls overlap: the host documents the library as safe to use
//! from several threads ("The pipeline library is thread-safe to use, and
//! will internally synchronize as necessary", `CreatePipelineLibrary`,
//! Thread Safety), with one exception kept here: two loads of the same
//! pipeline are made one after the other ([`same_name`]). Under one lock of
//! ours for every call, the eight workers made pipelines one at a time:
//! 87 to 96 of 110 looks at each worker found it waiting for that lock
//! (run 49), and an earlier run's 2,300 pipelines, all in the library, were
//! still being loaded 46 s into the opening cutscene.
//! `VICTORY_LIBRARY_LOCK=1`: one call at a time, as before.
//!
//! The library's file is mapped, not read into memory ([`Blob`]): the host
//! keeps pointing into the bytes it was made from for as long as it lives,
//! and read into a buffer they were 1,352 MB of the process's own memory
//! for the whole run (run 60), all of it in physical memory. Mapped, the
//! pages are the file's: only those the host reads are in memory, and the
//! system can drop them without writing them anywhere. A save writes the
//! new library through a mapping of the new file in the same way (a buffer
//! of the library's size was made, filled and written out at each save).
//! `VICTORY_LIBRARY_MAP=0`: read and written through buffers, as before.
//!
//! The mapped file's handle stays open for as long as the mapping lives
//! ([`holds`]). A save renames the new library over the file this run has
//! mapped, and with the handle closed Windows then gives up the old file's
//! contents: every page of the mapping that is not in memory at that
//! moment, or leaves memory later (the trim below, or Windows taking pages
//! back), reads as zeros from then on. The host's library reads such pages
//! as stored pipelines; the driver, handed a pipeline of zeros, removes the
//! device with DXGI_ERROR_DRIVER_INTERNAL_ERROR (runs 72, 73 and 82, each
//! within 5 ms of the first library call after a save and a trim; and the
//! library run 77 saved from such pages was refused by run 78). Measured
//! with a 64 MB file written past the system's cache, mapped and replaced:
//! 16,352 of 16,384 pages read zeros with the handle closed, none with it
//! open (the test below). `VICTORY_LIBRARY_HANDLE=0`: closed, as before.
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::sync::{Mutex, MutexGuard, OnceLock, RwLock};
use windows::Win32::Graphics::Direct3D12::*;
use windows::core::{HSTRING, Interface, PCWSTR};
@@ -35,64 +67,430 @@ pub fn use_pipeline_cache(dir: PathBuf) {
pub(crate) static MADE: AtomicU64 = AtomicU64::new(0);
pub(crate) static LOADED: AtomicU64 = AtomicU64::new(0);
pub(crate) static EARLY: AtomicU64 = AtomicU64::new(0);
/// For the memory lines: the bytes of the library's file, kept in memory
/// while the library lives, and the bytes the last save wrote (a buffer of
/// that size is made, filled and written every time pipelines were added,
/// at most every 20 s).
pub(crate) static BLOB: AtomicU64 = AtomicU64::new(0);
pub(crate) static SAVED: AtomicU64 = AtomicU64::new(0);
/// Whether the library's file is mapped ([`Blob`]) and saved through a
/// mapping. On by default; `VICTORY_LIBRARY_MAP=0` uses buffers, as before.
fn mapped() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_MAP").is_none_or(|v| v != "0"))
}
/// Whether the mapped library file's handle is kept open while it is
/// mapped (see the module's notes: without it a save in the same run turns
/// the mapping's pages into zeros as they leave memory). On by default;
/// `VICTORY_LIBRARY_HANDLE=0` closes it after mapping, as before.
fn holds() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_HANDLE").is_none_or(|v| v != "0"))
}
/// A whole file mapped into memory: read-only (the library's file) or
/// writable (the file a save fills). Unmapped when dropped.
struct Mapped {
at: windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS,
len: usize,
/// The file, for a mapping made by [`Mapped::open`] ([`holds`]): open
/// until after the view is unmapped, so that the file a rename took
/// the name from keeps its contents for the view.
_file: Option<std::fs::File>,
}
impl Mapped {
/// Maps `file` (`len` bytes, not zero) for reading, or for reading and
/// writing.
fn map(file: &std::fs::File, len: usize, write: bool) -> Option<Mapped> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, FILE_MAP_READ, FILE_MAP_WRITE, MapViewOfFile, PAGE_READONLY, PAGE_READWRITE,
};
if len == 0 {
return None;
}
// SAFETY: a file we hold open; the view keeps the file's pages
// after the mapping object and the file are closed.
let at = unsafe {
let mapping = CreateFileMappingW(
file.as_raw_handle(),
std::ptr::null(),
if write { PAGE_READWRITE } else { PAGE_READONLY },
0,
0,
std::ptr::null(),
);
if mapping.is_null() {
return None;
}
let at = MapViewOfFile(mapping, if write { FILE_MAP_WRITE } else { FILE_MAP_READ }, 0, 0, 0);
CloseHandle(mapping);
at
};
(!at.Value.is_null()).then_some(Mapped { at, len, _file: None })
}
/// The file at `path`, mapped for reading; `None` if it is not there,
/// is empty or cannot be mapped.
fn open(path: &std::path::Path) -> Option<Mapped> {
Mapped::open_holding(path, holds())
}
/// As [`Mapped::open`]; `hold` says whether the file stays open with
/// the mapping.
fn open_holding(path: &std::path::Path, hold: bool) -> Option<Mapped> {
// Opened as the standard library opens a file to read: others may
// read, write, rename and delete it meanwhile, so a save still
// renames the new library over this one.
let file = std::fs::File::open(path).ok()?;
let len = usize::try_from(file.metadata().ok()?.len()).ok()?;
let mut mapped = Mapped::map(&file, len, false)?;
if hold {
mapped._file = Some(file);
}
Some(mapped)
}
/// A new file of `len` bytes at `path` (replacing what is there),
/// mapped for writing.
fn create(path: &std::path::Path, len: usize) -> Option<Mapped> {
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(path)
.ok()?;
file.set_len(len as u64).ok()?;
Mapped::map(&file, len, true)
}
fn bytes(&self) -> &[u8] {
// SAFETY: the view holds `len` readable bytes until dropped.
unsafe { std::slice::from_raw_parts(self.at.Value.cast(), self.len) }
}
/// Only for a view made by [`Mapped::create`].
fn bytes_mut(&mut self) -> &mut [u8] {
// SAFETY: a writable view of `len` bytes, ours alone.
unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) }
}
}
impl Drop for Mapped {
fn drop(&mut self) {
// SAFETY: our view.
unsafe { windows_sys::Win32::System::Memory::UnmapViewOfFile(self.at) };
}
}
/// The bytes a library is made from: the host reads them for as long as
/// the library lives, so they are kept beside it.
enum Blob {
/// No file (an empty library).
None,
/// The file read into memory (`VICTORY_LIBRARY_MAP=0`, tests, or a file
/// that could not be mapped).
Held(Vec<u8>),
/// The file itself, mapped.
Mapped(Mapped),
}
impl Blob {
/// The library file in `dir`: a library a save left beside it
/// ([`NEXT_FILE`]) takes its place first.
fn of(dir: &std::path::Path) -> Blob {
let path = dir.join(LIBRARY_FILE);
let next = dir.join(NEXT_FILE);
if next.exists() && std::fs::rename(&next, &path).is_err() {
tracing::warn!("the host pipeline library saved last could not take the old one's place");
}
if mapped()
&& let Some(file) = Mapped::open(&path)
{
return Blob::Mapped(file);
}
match std::fs::read(&path) {
Ok(bytes) if !bytes.is_empty() => Blob::Held(bytes),
_ => Blob::None,
}
}
fn bytes(&self) -> &[u8] {
match self {
Blob::None => &[],
Blob::Held(bytes) => bytes,
Blob::Mapped(file) => file.bytes(),
}
}
}
/// The mapped library file's view (address, bytes; 0: not mapped), when a
/// pipeline was last loaded from the library (`crate::host::now_ms`), and
/// whether the view's pages were let go since ([`trim`]).
static VIEW: [std::sync::atomic::AtomicUsize; 2] = [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
static LOADED_AT: AtomicU64 = AtomicU64::new(0);
static TRIMMED: AtomicBool = AtomicBool::new(false);
/// The bytes of the view let go so far, for the memory line.
pub(crate) static TRIMMED_BYTES: AtomicU64 = AtomicU64::new(0);
/// When the view's pages were last let go (`crate::host::now_ms`), and how
/// often and when a save of this run last renamed a new library over the
/// mapped file: for [`removal_note`].
static TRIMMED_AT: AtomicU64 = AtomicU64::new(0);
static REPLACED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
/// The library calls running now: thread, what (load, make, store,
/// serialise), the pipeline, and since when (`crate::host::now_us`).
static CALLS: Mutex<Vec<(u32, &'static str, String, u64)>> = Mutex::new(Vec::new());
thread_local! {
/// The pipeline this thread is making (its shaders), for [`CALLS`].
static LABEL: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) };
}
/// Names the pipeline this thread makes next.
pub(crate) fn label(text: String) {
LABEL.with(|l| *l.borrow_mut() = text);
}
/// A library call of this thread, listed in [`CALLS`] until dropped.
struct Call(u32, u64);
fn call(what: &'static str, name: &str) -> Call {
let (thread, since) = (crate::host::thread_id(), crate::host::now_us());
let label = LABEL.with(|l| l.borrow().clone());
CALLS
.lock()
.unwrap_or_else(|e| e.into_inner())
.push((thread, what, format!("{name} {label}"), since));
Call(thread, since)
}
impl Drop for Call {
fn drop(&mut self) {
CALLS
.lock()
.unwrap_or_else(|e| e.into_inner())
.retain(|c| (c.0, c.3) != (self.0, self.1));
}
}
/// For the report when the host device is removed: the library calls
/// running at that moment, whether this run replaced the mapped file and
/// let its pages go, and how many pages of the mapping read as zeros now.
/// A library holds no page of zeros (the 259 MB one of run 83 has no run of
/// 2,048 zero bytes): each such page is one whose contents were lost (see
/// the module's notes), and a pipeline stored there is what the driver was
/// handed.
pub(crate) fn removal_note() -> String {
use std::fmt::Write;
let now = crate::host::now_us();
let mut text = String::from("pipeline library: ");
{
let calls = CALLS.lock().unwrap_or_else(|e| e.into_inner());
if calls.is_empty() {
text.push_str("no call running");
}
for (i, (thread, what, name, since)) in calls.iter().enumerate() {
let _ = write!(
text,
"{}{what} of {name} running for {:.1} ms on thread {thread}",
if i == 0 { "" } else { ", " },
now.saturating_sub(*since) as f64 / 1000.0
);
}
}
let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed));
if at == 0 {
text.push_str("; its file is not mapped");
return text;
}
let ago = |ms: u64| crate::host::now_ms().saturating_sub(ms) as f64 / 1000.0;
let _ = write!(
text,
"; its file is mapped ({len} bytes), the handle {}",
if holds() { "kept open" } else { "closed (VICTORY_LIBRARY_HANDLE=0)" }
);
match REPLACED[0].load(Ordering::Relaxed) {
0 => text.push_str("; this run has not replaced the file"),
n => {
let _ = write!(
text,
"; this run replaced the file under the mapping {n} times, last {:.1} s ago",
ago(REPLACED[1].load(Ordering::Relaxed))
);
}
}
if TRIMMED_BYTES.load(Ordering::Relaxed) > 0 {
let _ = write!(text, "; its pages were last let go {:.1} s ago", ago(TRIMMED_AT.load(Ordering::Relaxed)));
}
// Within two seconds: pages not in memory come from the disk.
let started = std::time::Instant::now();
// SAFETY: the view lives as long as the library, which is never dropped.
let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, len) };
let (mut zero, mut looked, mut first) = (0u64, 0u64, None);
for (n, page) in bytes.chunks(4096).enumerate() {
if n % 4096 == 0 && started.elapsed() > std::time::Duration::from_secs(2) {
break;
}
looked += 1;
if page.iter().all(|&b| b == 0) {
zero += 1;
if first.is_none() {
first = Some(n);
}
}
}
let _ = write!(text, "; {zero} of the {looked} pages looked at read as zeros now");
if let Some(first) = first {
let _ = write!(text, " (the first is page {first}): the library's contents were lost there");
}
text
}
/// Lets the mapped library file's pages go from the process's memory once
/// no pipeline has been loaded for ten seconds. The host reads nearly the
/// whole file while the early pipelines load (run 65: all 1,490 MB of it
/// were in the process's memory a minute in, and 1,300 MB still at the
/// end, on a PC with 2 GB free); after that it reads the file again only
/// when a new pipeline loads. Pages let go stay in Windows' file cache
/// while nothing else wants the memory, and come back on the next read.
/// Called once a second by the sweep; does its work on a thread of its own
/// (hundreds of thousands of pages), once after each burst of loads.
/// `VICTORY_LIBRARY_TRIM=0`: the pages stay until Windows takes them.
pub(crate) fn trim() {
const QUIET_MS: u64 = 10_000;
static ON: OnceLock<bool> = OnceLock::new();
let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed));
if at == 0
|| TRIMMED.load(Ordering::Relaxed)
|| crate::host::now_ms() < LOADED_AT.load(Ordering::Relaxed) + QUIET_MS
|| !*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_TRIM").is_none_or(|v| v != "0"))
|| TRIMMED.swap(true, Ordering::Relaxed)
{
return;
}
let work = move || {
// SAFETY: the view lives as long as the library, which is never
// dropped. Unlocking pages that are not locked fails, as expected,
// and takes them out of the working set: the documented way to let
// pages of a mapped file go.
unsafe { windows_sys::Win32::System::Memory::VirtualUnlock(at as *const _, len) };
TRIMMED_BYTES.fetch_add(len as u64, Ordering::Relaxed);
TRIMMED_AT.store(crate::host::now_ms(), Ordering::Relaxed);
crate::host::trail(|| format!("pipeline library: the mapped file's pages let go from memory ({len} bytes)"));
};
if std::thread::Builder::new().name("victory-library-trim".into()).spawn(work).is_err() {
TRIMMED.store(false, Ordering::Relaxed);
}
}
struct Library {
library: ID3D12PipelineLibrary1,
/// The blob the library was made from: it must outlive the library.
_blob: Vec<u8>,
_blob: Blob,
/// Pipelines stored since the last save.
added: u64,
added: AtomicU64,
/// Stores share it and a save takes it alone: the size the library
/// asks for must still be its size when it is written out.
saving: RwLock<()>,
}
// SAFETY: D3D12 objects are free-threaded; every call is made under the
// mutex that holds the library.
// SAFETY: D3D12 objects are free-threaded, and the library synchronises
// its own calls (see the module's notes); what it does not, two loads of
// one name, is serialised by `same_name`.
unsafe impl Send for Library {}
// SAFETY: as above; the other fields are an atomic and a lock.
unsafe impl Sync for Library {}
/// Held by a load of the pipeline named `name`: loads of the same name
/// wait for each other (the host's one exception to the library's thread
/// safety: such a load may change that pipeline's entry). Names share 64
/// locks, so two different names seldom wait.
fn same_name(name: &str) -> MutexGuard<'static, ()> {
static LOADING: [Mutex<()>; 64] = [const { Mutex::new(()) }; 64];
let at = name.bytes().fold(0usize, |h, b| h.wrapping_mul(31).wrapping_add(usize::from(b)));
LOADING[at % LOADING.len()].lock().unwrap_or_else(|e| e.into_inner())
}
/// With `VICTORY_LIBRARY_LOCK=1`: held by every library call, as before.
fn one_call() -> Option<MutexGuard<'static, ()>> {
static ON: OnceLock<bool> = OnceLock::new();
static CALLING: Mutex<()> = Mutex::new(());
ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_LOCK").is_some_and(|v| v == "1"))
.then(|| CALLING.lock().unwrap_or_else(|e| e.into_inner()))
}
const LIBRARY_FILE: &str = "host-pipelines.bin";
/// A saved library that could not replace [`LIBRARY_FILE`] while this run
/// had it mapped (a system that refuses to replace a mapped file): the next
/// start renames it over the library first ([`Blob::of`]).
const NEXT_FILE: &str = "host-pipelines.next";
const EARLY_FILE: &str = "early-pipelines.txt";
/// Title pipelines listed for an early start, at most.
const EARLY_MAX: usize = 8192;
fn library() -> Option<&'static Mutex<Library>> {
static LIBRARY: OnceLock<Option<Mutex<Library>>> = OnceLock::new();
fn library() -> Option<&'static Library> {
static LIBRARY: OnceLock<Option<Library>> = OnceLock::new();
LIBRARY
.get_or_init(|| {
let device = crate::host::host()?.device.cast::<ID3D12Device1>().ok()?;
let blob = DIR
.get()
.and_then(|d| std::fs::read(d.join(LIBRARY_FILE)).ok())
.unwrap_or_default();
let blob = DIR.get().map_or(Blob::None, |d| Blob::of(d));
let library = open(&device, blob);
if library.is_none() {
tracing::warn!("no host pipeline library: pipelines are not kept");
}
library.map(Mutex::new)
library
})
.as_ref()
}
/// The library in `blob`, or an empty one if the host rejects the blob (an
/// adapter or driver change, damage).
fn open(device: &ID3D12Device1, blob: Vec<u8>) -> Option<Library> {
fn open(device: &ID3D12Device1, blob: Blob) -> Option<Library> {
let make = |bytes: &[u8]| -> windows::core::Result<ID3D12PipelineLibrary1> {
// SAFETY: the bytes outlive the library (kept beside it).
unsafe {
device.CreatePipelineLibrary::<ID3D12PipelineLibrary>(bytes)?.cast()
}
};
if !blob.is_empty() {
match make(&blob) {
if !blob.bytes().is_empty() {
match make(blob.bytes()) {
Ok(library) => {
tracing::info!(bytes = blob.len(), "host pipeline library loaded");
return Some(Library { library, _blob: blob, added: 0 });
let bytes = blob.bytes().len();
BLOB.store(bytes as u64, Ordering::Relaxed);
tracing::info!(bytes, mapped = matches!(blob, Blob::Mapped(_)), "host pipeline library loaded");
if let Blob::Mapped(file) = &blob {
VIEW[1].store(file.len, Ordering::Relaxed);
VIEW[0].store(file.at.Value as usize, Ordering::Relaxed);
LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed);
}
return Some(Library {
library,
_blob: blob,
added: AtomicU64::new(0),
saving: RwLock::new(()),
});
}
Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"),
}
} else {
tracing::info!("no host pipeline library yet; starting an empty one");
}
// The rejected bytes are let go (a mapped file is unmapped) before the
// empty library is made: nothing reads them any more.
drop(blob);
let library = make(&[]).ok()?;
Some(Library { library, _blob: Vec::new(), added: 0 })
Some(Library {
library,
_blob: Blob::None,
added: AtomicU64::new(0),
saving: RwLock::new(()),
})
}
/// A pipeline's name in the library: the hash of what its host
@@ -118,18 +516,47 @@ pub(crate) fn pipeline(
MADE.fetch_add(1, Ordering::Relaxed);
return create();
};
if let Ok(pso) = load(&library.lock().unwrap_or_else(|e| e.into_inner()).library, PCWSTR(wide.as_ptr())) {
LOADED.fetch_add(1, Ordering::Relaxed);
return Ok(pso);
}
// Compiled outside the lock: compiles take up to seconds.
let pso = create()?;
let began = std::time::Instant::now();
let loaded = {
let _all = one_call();
let _one = same_name(name);
let _call = call("load", name);
load(&library.library, PCWSTR(wide.as_ptr()))
};
// The load read the library's file (see `trim`).
LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed);
TRIMMED.store(false, Ordering::Relaxed);
let refused = match loaded {
Ok(pso) => {
LOADED.fetch_add(1, Ordering::Relaxed);
crate::host::trail(|| {
let label = LABEL.with(|l| l.borrow().clone());
format!("pipeline library: loaded {label} in {:.1} ms", began.elapsed().as_secs_f64() * 1e3)
});
return Ok(pso);
}
Err(e) => e,
};
// Compiled outside any lock: compiles take up to seconds.
let pso = {
let _call = call("make", name);
create()?
};
MADE.fetch_add(1, Ordering::Relaxed);
let mut l = library.lock().unwrap_or_else(|e| e.into_inner());
crate::host::trail(|| {
let label = LABEL.with(|l| l.borrow().clone());
format!(
"pipeline library: made {label} in {:.1} ms (the library did not load it: {refused})",
began.elapsed().as_secs_f64() * 1e3
)
});
let _all = one_call();
let _stores = library.saving.read().unwrap_or_else(|e| e.into_inner());
let _call = call("store", name);
// SAFETY: a live pipeline; a name already stored (a description that
// differs) is refused, which leaves the library as it was.
if unsafe { l.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() {
l.added += 1;
if unsafe { library.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() {
library.added.fetch_add(1, Ordering::Relaxed);
}
Ok(pso)
}
@@ -147,34 +574,60 @@ pub(crate) fn save(now: bool) {
}
*last = Some(std::time::Instant::now());
}
let blob = {
let mut l = library.lock().unwrap_or_else(|e| e.into_inner());
if l.added == 0 && !USED_CHANGED.swap(false, Ordering::Relaxed) {
if let Err(e) = std::fs::create_dir_all(dir) {
tracing::warn!(error = %e, "host pipeline library not saved");
return;
}
let tmp = dir.join(LIBRARY_FILE).with_extension("tmp");
// The bytes of the library written to `tmp`; 0 when no pipeline was
// added: the library on disk is then what it was, and only the early
// list is written (a title pipeline first drawn with wrote all 1,352 MB
// of the library again: run 60's second save).
let bytes = {
let _all = one_call();
// No store between asking the size and writing; loads go on.
let _alone = library.saving.write().unwrap_or_else(|e| e.into_inner());
let added = library.added.load(Ordering::Relaxed);
if !USED_CHANGED.swap(false, Ordering::Relaxed) && added == 0 {
return;
}
// SAFETY: a buffer of the size the library asks for.
let bytes = unsafe {
let mut bytes = vec![0u8; l.library.GetSerializedSize()];
l.library.Serialize(&mut bytes).map(|()| bytes)
};
match bytes {
Ok(bytes) => {
l.added = 0;
bytes
}
Err(e) => {
if added == 0 {
0
} else {
// SAFETY: a plain query.
let size = unsafe { library.library.GetSerializedSize() };
let _call = call("serialise", "the whole library");
if let Err(e) = serialise(&library.library, &tmp, size) {
tracing::warn!(error = %e, "host pipeline library not serialised");
let _ = std::fs::remove_file(&tmp);
return;
}
library.added.store(0, Ordering::Relaxed);
SAVED.store(size as u64, Ordering::Relaxed);
size
}
};
let used: Vec<String> = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect();
let written = std::fs::create_dir_all(dir)
.and_then(|()| write_atomically(&dir.join(LIBRARY_FILE), &blob))
let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) };
if bytes > 0 && library_written.is_ok() {
// In place unless the system refused and the new one waits beside it.
let in_place = !dir.join(NEXT_FILE).exists();
if in_place && VIEW[0].load(Ordering::Relaxed) != 0 {
REPLACED[1].store(crate::host::now_ms(), Ordering::Relaxed);
REPLACED[0].fetch_add(1, Ordering::Relaxed);
}
crate::host::trail(|| {
format!(
"pipeline library: saved {bytes} bytes, {}",
if in_place { "renamed over the library's file" } else { "left beside the library's file for the next start" }
)
});
}
let written = library_written
.and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes()));
match written {
Ok(()) => tracing::info!(
bytes = blob.len(),
bytes,
early = used.len(),
made = MADE.load(Ordering::Relaxed),
loaded = LOADED.load(Ordering::Relaxed),
@@ -185,6 +638,35 @@ pub(crate) fn save(now: bool) {
}
}
/// Writes the library's `size` serialised bytes to the file `tmp`: through
/// a mapping of that file, so that the bytes are the file's pages and not
/// 1.3 GB more of the process's own memory for the seconds a save takes;
/// through a buffer where the file cannot be mapped (and with
/// `VICTORY_LIBRARY_MAP=0`).
fn serialise(library: &ID3D12PipelineLibrary1, tmp: &std::path::Path, size: usize) -> std::io::Result<()> {
let failed = |e: windows::core::Error| std::io::Error::other(e.to_string());
if mapped()
&& let Some(mut file) = Mapped::create(tmp, size)
{
// SAFETY: a buffer of the size the library asks for.
return unsafe { library.Serialize(file.bytes_mut()) }.map_err(failed);
}
let mut bytes = vec![0u8; size];
// SAFETY: a buffer of the size the library asks for.
unsafe { library.Serialize(&mut bytes) }.map_err(failed)?;
std::fs::write(tmp, &bytes)
}
/// Renames the written library `tmp` over the library's file in `dir`. This
/// run may have that file mapped: Windows 11 replaces a mapped file, and
/// the mapping goes on reading the old one for as long as a handle on it
/// is open ([`holds`]; with none, only the pages in memory at that moment
/// stay: the rest read as zeros). Where a system refuses, the new library
/// is left beside it as [`NEXT_FILE`] for the next start.
fn replace_library(dir: &std::path::Path, tmp: &std::path::Path) -> std::io::Result<()> {
std::fs::rename(tmp, dir.join(LIBRARY_FILE)).or_else(|_| std::fs::rename(tmp, dir.join(NEXT_FILE)))
}
/// Writes `bytes` to a temporary file beside `path`, then renames it over
/// `path`: a reader never sees a part.
fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
@@ -246,9 +728,111 @@ mod tests {
let Some(device) = crate::host::host().and_then(|h| h.device.cast::<ID3D12Device1>().ok()) else {
return; // no host GPU here
};
let library = open(&device, b"not a pipeline library".repeat(16)).expect("an empty library");
let library = open(&device, Blob::Held(b"not a pipeline library".repeat(16))).expect("an empty library");
// SAFETY: a plain query on a live library.
assert!(unsafe { library.library.GetSerializedSize() } > 0);
assert!(library._blob.is_empty());
assert!(matches!(library._blob, Blob::None));
}
/// A mapped file reads as the file's bytes, a file written through a
/// mapping holds what was written, and the library's file can be
/// replaced while it is mapped (or the new one waits as the next).
#[test]
fn the_library_file_is_mapped_and_replaced() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(LIBRARY_FILE);
assert!(matches!(Blob::of(dir.path()), Blob::None), "no file yet");
std::fs::write(&path, b"").unwrap();
assert!(matches!(Blob::of(dir.path()), Blob::None), "an empty file");
let old: Vec<u8> = (0..200_000u32).map(|i| i as u8).collect();
std::fs::write(&path, &old).unwrap();
let blob = Blob::of(dir.path());
assert!(matches!(blob, Blob::Mapped(_)) || !mapped());
assert_eq!(blob.bytes(), &old[..]);
// A save while the old file is mapped.
let tmp = path.with_extension("tmp");
let new: Vec<u8> = (0..300_000u32).map(|i| (i * 7) as u8).collect();
{
let mut file = Mapped::create(&tmp, new.len()).expect("a new file, mapped");
file.bytes_mut().copy_from_slice(&new);
}
assert_eq!(std::fs::read(&tmp).unwrap(), new);
replace_library(dir.path(), &tmp).unwrap();
assert!(!tmp.exists());
// The mapping still reads the old library.
assert_eq!(blob.bytes(), &old[..]);
drop(blob);
// The next start reads the new one, wherever the save left it.
assert_eq!(Blob::of(dir.path()).bytes(), &new[..]);
assert!(!dir.path().join(NEXT_FILE).exists());
}
/// The bytes at `at` of the pattern the test below writes.
fn pattern(at: usize, out: &mut [u8]) {
for (i, word) in out.chunks_exact_mut(4).enumerate() {
let v = ((at / 4 + i) as u32).wrapping_mul(2_654_435_761).wrapping_add(1);
word.copy_from_slice(&v.to_le_bytes());
}
}
/// A file of `len` bytes (whole MiB) of [`pattern`], written past the
/// system's cache: none of its pages is in memory afterwards. False
/// where the folder's file system does not take such writes.
fn write_uncached(path: &std::path::Path, len: usize) -> bool {
use std::io::Write;
use std::os::windows::fs::OpenOptionsExt;
// FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH
const UNCACHED: u32 = 0x2000_0000 | 0x8000_0000;
const CHUNK: usize = 1 << 20;
let Ok(mut file) = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.custom_flags(UNCACHED)
.open(path)
else {
return false;
};
// Such writes want a buffer on a sector boundary.
let mut store = vec![0u8; CHUNK + 4096];
let start = store.as_ptr().align_offset(4096);
for at in (0..len).step_by(CHUNK) {
let chunk = &mut store[start..start + CHUNK];
pattern(at, chunk);
if file.write_all(chunk).is_err() {
return false;
}
}
true
}
/// The device loss of runs 72, 73 and 82: the library's file is
/// replaced while it is mapped, and pages of the mapping that were not
/// in memory then are read afterwards (in the runs: pages the trim let
/// go and Windows gave to something else). With the file's handle kept
/// open they still read as the old file. (With it closed, as before,
/// all but the first few read as zeros on the PC this was found on.)
#[test]
fn a_replaced_library_file_still_reads_from_the_disk() {
const LEN: usize = 8 << 20;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(LIBRARY_FILE);
if !write_uncached(&path, LEN) {
return; // no uncached writes here: nothing to show
}
let mapped = Mapped::open_holding(&path, true).expect("the file, mapped");
// A save: the new library, renamed over the mapped one.
let tmp = path.with_extension("tmp");
{
let mut file = Mapped::create(&tmp, LEN).expect("a new file, mapped");
file.bytes_mut().fill(0xEE);
}
replace_library(dir.path(), &tmp).unwrap();
// Every page of the old mapping, read for the first time now.
let mut expected = vec![0u8; 4096];
for (page, bytes) in mapped.bytes().chunks(4096).enumerate() {
pattern(page * 4096, &mut expected);
assert!(bytes == &expected[..], "page {page} of the replaced library no longer reads as the old file");
}
}
}
+175 -38
View File
@@ -16,7 +16,8 @@
//! guess; a pass the title runs only once and whose pipeline takes longer
//! is lost.
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};
@@ -27,7 +28,7 @@ use super::host::{GraphicsState, HostPipeline};
pub(crate) struct Pending {
shaders: Vec<Arc<Shader>>,
pub(crate) graphics: Option<Box<GraphicsState>>,
queued: AtomicBool,
queue_state: AtomicU8,
made: OnceLock<Option<HostPipeline>>,
/// What identifies it across runs (shader containers and state), and
/// whether a draw has used it yet.
@@ -52,7 +53,7 @@ impl Pending {
Pending {
shaders,
graphics,
queued: AtomicBool::new(false),
queue_state: AtomicU8::new(NOT_QUEUED),
made: OnceLock::new(),
key: key.finalize().to_hex()[..32].to_owned(),
used: AtomicBool::new(false),
@@ -109,22 +110,25 @@ pub(crate) fn waiting() -> u64 {
/// queues it on first use.
pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> {
if p.made.get().is_none() {
start(p);
start(p, REQUESTED);
wait(p, crate::frame::current());
}
let made = p.made.get()?.as_ref();
if made.is_some() && !p.used.swap(true, Ordering::Relaxed) {
// Also one that could not be made (a shader that does not translate):
// the next run then finds that out while loading, like the others,
// instead of in the world's frames, where each first use of such a
// pipeline waits on the frame's budget for nothing.
if !p.used.swap(true, Ordering::Relaxed) {
super::library::note_used(&p.key);
}
made
}
/// Queues `p` for the workers, once.
fn start(p: &Arc<Pending>) {
if !p.queued.swap(true, Ordering::Relaxed) {
PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed);
queue(p.clone());
}
/// Makes `p` on this thread if it is not made yet (waiting for a worker
/// that is making it); whether it has a host pipeline.
pub(crate) fn now(p: &Arc<Pending>) -> bool {
p.make();
p.made.get().is_some_and(|made| made.is_some())
}
/// At the title's creation of a pipeline: starts it at once if an earlier
@@ -132,18 +136,43 @@ fn start(p: &Arc<Pending>) {
pub(crate) fn early(p: &Arc<Pending>) {
if !p.shaders.is_empty() && super::library::wanted_early(&p.key) {
super::library::EARLY.fetch_add(1, Ordering::Relaxed);
start(p);
start(p, EARLY);
}
}
/// Whether the frame's budget is one for all threads together: a thread
/// that waits takes what is left of it and gives back what it did not
/// use. Counted only when a wait had ended, the budget was one per thread:
/// each of the title's five recording threads began its first wait of a
/// frame with nothing counted yet and waited the whole half second, 2.5 s
/// of waiting in every frame in which pipelines were being made (runs
/// 34-49: "2504 ms waiting for pipelines" in each such frame).
/// On by default; `VICTORY_PIPELINE_WAIT_SHARED=0` counts as before.
fn shared_budget() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_SHARED").is_none_or(|v| v != "0"))
}
/// Waits for `p` while frame `frame` has budget left.
fn wait(p: &Pending, frame: u64) {
static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
static WAITED_US: AtomicU64 = AtomicU64::new(0);
if FRAME.swap(frame, Ordering::Relaxed) != frame {
WAITED_US.store(0, Ordering::Relaxed);
// The frame the budget belongs to, and what was waited of it (or is
// taken by a thread waiting now).
static SPENT: Mutex<(u64, Duration)> = Mutex::new((u64::MAX, Duration::ZERO));
let shared = shared_budget();
let left = {
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
if spent.0 != frame {
*spent = (frame, Duration::ZERO);
}
let left = BUDGET.saturating_sub(spent.1);
if shared {
spent.1 += left;
}
left
};
if left.is_zero() {
return;
}
let left = BUDGET.saturating_sub(Duration::from_micros(WAITED_US.load(Ordering::Relaxed)));
let started = Instant::now();
let (lock, done) = &DONE;
let mut held = lock.lock().unwrap_or_else(|e| e.into_inner());
@@ -154,22 +183,115 @@ fn wait(p: &Pending, frame: u64) {
}
held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0;
}
WAITED_US.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
drop(held);
let waited = started.elapsed().min(left);
{
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
// A frame that began meanwhile has its own budget.
if spent.0 == frame {
if shared {
spent.1 = spent.1.saturating_sub(left - waited);
} else {
spent.1 += waited;
}
}
}
#[cfg(feature = "diagnostics")]
crate::copystat::add(
crate::copystat::C::PipelineWaitUs,
started.elapsed().as_micros() as u64,
);
}
/// Hands `p` to the workers (half the logical processors, 2 to 8), started
/// on first use.
fn queue(p: Arc<Pending>) {
static SENDER: OnceLock<std::sync::mpsc::Sender<Arc<Pending>>> = OnceLock::new();
let sender = SENDER.get_or_init(|| {
let (sender, receiver) = std::sync::mpsc::channel::<Arc<Pending>>();
let receiver = Arc::new(Mutex::new(receiver));
const NOT_QUEUED: u8 = 0;
const EARLY: u8 = 1;
const REQUESTED: u8 = 2;
const MAKING: u8 = 3;
struct Queue {
early: VecDeque<Arc<Pending>>,
requested: VecDeque<Arc<Pending>>,
}
impl Queue {
const fn new() -> Self {
Self {
early: VecDeque::new(),
requested: VecDeque::new(),
}
}
/// Queues an unrequested pipeline or promotes one queued at creation.
/// Returns whether it is new to the queue, or `None` if nothing changed.
fn push(&mut self, p: &Arc<Pending>, priority: u8) -> Option<bool> {
let prev = p.queue_state.load(Ordering::Relaxed);
if prev >= priority {
return None;
}
p.queue_state.store(priority, Ordering::Relaxed);
if priority == REQUESTED {
self.requested.push_back(p.clone());
} else {
self.early.push_back(p.clone());
}
Some(prev == NOT_QUEUED)
}
fn pop(&mut self) -> Option<Arc<Pending>> {
let p = self.requested.pop_front().or_else(|| {
// An early entry can have been promoted and claimed already.
std::iter::from_fn(|| self.early.pop_front())
.find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY)
})?;
p.queue_state.store(MAKING, Ordering::Relaxed);
Some(p)
}
}
static QUEUE: Mutex<Queue> = Mutex::new(Queue::new());
static AVAILABLE: Condvar = Condvar::new();
/// Start or promote work for a draw without waiting behind the entire early
/// list. Queue changes and worker claims happen under the same lock.
fn start(p: &Arc<Pending>, priority: u8) {
if p.queue_state.load(Ordering::Relaxed) >= priority {
return;
}
if !workers() {
if p.queue_state.swap(MAKING, Ordering::Relaxed) == NOT_QUEUED {
p.make();
}
return;
}
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
if let Some(new) = queue.push(p, priority) {
if new {
PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed);
}
AVAILABLE.notify_one();
}
}
fn next() -> Arc<Pending> {
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
loop {
if let Some(p) = queue.pop() {
return p;
}
queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner());
}
}
/// Starts the workers (half the logical processors, 2 to 8) on first use.
fn workers() -> bool {
static RUNNING: OnceLock<bool> = OnceLock::new();
*RUNNING.get_or_init(|| {
let mut running = false;
let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8));
for i in 0..workers {
let receiver = receiver.clone();
let spawned = std::thread::Builder::new()
.name(format!("victory-pipelines-{i}"))
.spawn(move || {
.spawn(|| {
// Below the title's own threads (loading, recording).
// SAFETY: a plain call on our own thread.
unsafe {
@@ -177,9 +299,7 @@ fn queue(p: Arc<Pending>) {
let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
}
loop {
let next = receiver.lock().unwrap_or_else(|e| e.into_inner()).recv();
let Ok(p) = next else { return };
p.make();
next().make();
if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 {
drained();
} else {
@@ -189,15 +309,12 @@ fn queue(p: Arc<Pending>) {
});
if let Err(e) = spawned {
tracing::warn!(error = %e, "no pipeline worker");
} else {
running = true;
}
}
sender
});
if let Err(e) = sender.send(p) {
// No worker: made here instead.
e.0.make();
WAITING.fetch_sub(1, Ordering::Relaxed);
}
running
})
}
/// The most pipelines waiting at once since the workers last ran out.
@@ -228,11 +345,31 @@ mod tests {
fn first_use_is_made_by_a_worker() {
let p = Arc::new(Pending::new(Vec::new(), None));
assert!(ready(&p).is_none());
assert!(p.queued.load(Ordering::Relaxed));
assert_ne!(p.queue_state.load(Ordering::Relaxed), NOT_QUEUED);
let started = Instant::now();
while p.made.get().is_none() && started.elapsed() < Duration::from_secs(10) {
std::thread::yield_now();
}
assert!(matches!(p.made.get(), Some(None)));
}
#[test]
fn draws_promote_early_pipelines_without_claiming_them_twice() {
let earlier = Arc::new(Pending::new(Vec::new(), None));
let promoted = Arc::new(Pending::new(Vec::new(), None));
let requested = Arc::new(Pending::new(Vec::new(), None));
let mut queue = Queue::new();
assert_eq!(queue.push(&earlier, EARLY), Some(true));
assert_eq!(queue.push(&promoted, EARLY), Some(true));
assert_eq!(queue.push(&requested, REQUESTED), Some(true));
assert_eq!(queue.push(&promoted, REQUESTED), Some(false));
assert_eq!(queue.push(&promoted, REQUESTED), None);
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &requested));
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &promoted));
assert_eq!(queue.push(&promoted, REQUESTED), None);
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &earlier));
assert!(queue.pop().is_none());
}
}
+6
View File
@@ -11,6 +11,12 @@
//! [`components`] does not know keep the first vertex's value, and so do
//! components past the end of the vertex (an element that reaches into the
//! next one, which the layout allows).
//!
//! A pipeline the title makes for rectangles completes them on the GPU
//! instead, in a geometry stage (`victory_shader::emit::rect_list_gs`):
//! from the vertex shader's outputs, whichever vertex the corner is, for
//! direct, indexed and indirect draws alike. This expansion is what is
//! left for a pipeline that could not get that stage.
/// Expands `rects` rectangles of `stride`-byte vertices from `src` into six
/// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both
+548 -9
View File
@@ -34,9 +34,403 @@ struct Queue {
object: Object,
kind: u32,
desc: QueueDesc,
/// What the queue was given after a wait for a fence that had not been
/// reached, in order; it runs when the fence gets there.
#[cfg(windows)]
held: std::sync::Mutex<Vec<Held>>,
}
const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10);
/// One thing a waiting queue holds back.
#[cfg(windows)]
enum Held {
/// The queue waits for the fence (its address) to reach the value.
Wait(usize, u64),
/// A list of the next submission waits for a memory value.
Value(crate::list::ValueWait),
/// A submission: the lists' host sides, taken from the title's lists
/// (which it may reset meanwhile), and the order they run in.
Run(Vec<crate::list::Detached>, Vec<usize>),
/// A signal of the queue's, due after what it holds before it.
Signal(usize, u64),
}
/// The queues that hold something (their addresses).
#[cfg(windows)]
static WAITING: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
#[cfg(windows)]
fn lock<T>(mutex: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(|e| e.into_inner())
}
/// Whether queues wait for fences. `VICTORY_QUEUE_WAIT=0`: they do not,
/// and every submission runs when it is made (as before).
#[cfg(windows)]
fn waits() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE_WAIT").is_none_or(|v| v != "0"))
}
/// Whether a submission is held list by list: the lists before the first
/// one whose wait for a memory value is not met run at once, and each list
/// that waits is held with the lists after it, behind its own waits.
/// Holding a submission whole made the title's queues wait for each other:
/// a graphics submission was held for a value a compute list writes, and
/// that compute list for a value an earlier list of the same graphics
/// submission writes. Nothing moved until the present forced it, and the
/// title reached its present only after waiting about 2.5 s, every frame
/// (runs 27-30: 2.4-2.9 s from the last submission to the present call,
/// 13-32 ms before waits were honoured; the frame's main graphics
/// submissions, 88 lists, ran forced, the compute lists before them).
/// On by default; `VICTORY_SPLIT_WAITS=0` holds whole submissions, as
/// before.
#[cfg(windows)]
fn split() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_SPLIT_WAITS").is_none_or(|v| v != "0"))
}
/// Whether a list is cut into host lists at its waits for memory values
/// (`crate::list::cut`), and a queue runs a submission part by part: it
/// stands at each wait until the value is in memory, with everything
/// recorded before the wait run and its bottom-of-pipe writes done, as on
/// the console. Held list by list ([`split`]) a wait still held its whole
/// list: the title's lists are chains of jobs, each behind a wait for a
/// value another queue's list writes in the middle of its own chain
/// (frame 858 of run 33: a compute list of 433 commands with 13 waits;
/// graphics lists of the form "341 dispatches, wait, draws"), so two lists
/// each waited for a write behind the other's wait and only the present
/// moved them, in the wrong order.
/// On by default where waits are honoured list by list;
/// `VICTORY_CUT_WAITS=0` holds whole lists, as before.
#[cfg(windows)]
pub(crate) fn cuts() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
waits() && split() && *ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WAITS").is_none_or(|v| v != "0"))
}
/// Whether a present runs what queues still hold (on by default: a wait
/// is not kept across frames). `VICTORY_WAIT_FORCE=0` keeps it held: for
/// finding out whether the title's waits reach across its presents; a
/// wait nothing ever meets then stops the title for good.
#[cfg(windows)]
fn forces() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_WAIT_FORCE").is_none_or(|v| v != "0"))
}
/// A submission to a queue whose lists are cut at their waits ([`cuts`]).
/// The lists before the first one that waits run at once if the queue
/// holds nothing; the rest goes behind what the queue holds, part by part
/// (`crate::list::detach_parts`): the waits of a part, then its host
/// lists. [`release_held`] runs the queue's line as far as the values are
/// there, now and whenever a submission has run.
#[cfg(windows)]
fn submit_cut(this: This, lists: &[This]) {
let Some(host) = crate::host::host() else {
return;
};
let first = if lock(&queue(this).held).is_empty() {
lists
.iter()
.position(|&l| crate::list::cut_list(l))
.unwrap_or(lists.len())
} else {
0
};
#[cfg(feature = "diagnostics")]
crate::capture::op(this as usize, || {
let named: Vec<String> = lists
.iter()
.map(|&l| match crate::list::host_list(l) {
Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize),
None => format!("title {l:?}"),
})
.collect();
format!(
"SUBMIT queue kind {:?} held {} lists {named:?} (the first {first} run at once, the rest part by part)",
Some(queue(this).kind),
first < lists.len()
)
});
if first > 0 && crate::host::late() {
// Sent to the card and not waited for: their host sides are taken
// from the title's lists (which it may reset before they have run)
// and come back, with their tables' slots, when they are settled.
let (taken, order) = crate::list::detach(&lists[..first]);
host.execute_late(taken, order);
} else if first > 0 {
let now: Vec<_> = lists[..first]
.iter()
.filter_map(|&l| crate::list::host_list(l))
.collect();
host.execute(&now);
// They have run: their descriptor tables' slots are free again, as
// on the path without cuts ([`execute`]). This path replaced that
// one without the call, so the lists that run at once kept their
// slots until the title's reset and the ring ran out as before
// (run 45: 3,143 of 15,942 tables refused in one frame).
crate::list::tables_done(&lists[..first]);
}
if first < lists.len() {
let parts = crate::list::detach_parts(&lists[first..]);
static SEEN: AtomicU64 = AtomicU64::new(0);
if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
tracing::info!(
kind = queue(this).kind,
lists = lists.len(),
run_at_once = first,
parts = parts.len(),
waits = parts.iter().map(|p| p.0.len()).sum::<usize>(),
"a submission is given to its queue part by part (its lists wait for memory values)"
);
}
{
let mut held = lock(&queue(this).held);
for (waits, taken, order) in parts {
held.extend(waits.into_iter().map(Held::Value));
held.push(Held::Run(taken, order));
}
}
let mut waiting = lock(&WAITING);
if !waiting.contains(&(this as usize)) {
waiting.push(this as usize);
}
}
// What ran may be what another queue waits for, and what was just
// given to the queue may be free to run already.
release_held(false);
}
/// A submission to a queue that honours waits, list by list ([`split`]).
/// shortcut: a wait still holds its whole list, not only the commands
/// after it; and lists named twice among those held stay in one piece.
#[cfg(windows)]
fn submit_split(this: This, lists: &[This]) {
let Some(host) = crate::host::host() else {
return;
};
let by = crate::list::waits_by_list(lists);
// Behind what the queue already holds, nothing runs now.
let cut = if lock(&queue(this).held).is_empty() {
(0..lists.len())
.find(|&i| by[i].iter().any(|w| !w.met()))
.unwrap_or(lists.len())
} else {
0
};
#[cfg(feature = "diagnostics")]
crate::capture::op(this as usize, || {
let named: Vec<String> = lists
.iter()
.map(|&l| match crate::list::host_list(l) {
Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize),
None => format!("title {l:?}"),
})
.collect();
format!(
"SUBMIT queue kind {:?} held {} lists {named:?} (the first {cut} run at once)",
Some(queue(this).kind),
cut < lists.len()
)
});
if cut > 0 {
let now: Vec<_> = lists[..cut]
.iter()
.filter_map(|&l| crate::list::host_list(l))
.collect();
host.execute(&now);
}
if cut < lists.len() {
static SEEN: AtomicU64 = AtomicU64::new(0);
if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
tracing::info!(
kind = queue(this).kind,
lists = lists.len(),
run_at_once = cut,
waits = ?by[cut],
"lists of a submission are held for a memory value"
);
}
let rest = &lists[cut..];
// A list's host side can be taken once.
let twice = rest.iter().enumerate().any(|(i, l)| rest[..i].contains(l));
let mut pieces: Vec<Held> = Vec::new();
let mut from = cut;
while from < lists.len() {
// Up to the next list that waits for anything (met or not: it
// is looked at again when its turn comes).
let to = if twice {
lists.len()
} else {
(from + 1..lists.len())
.find(|&i| !by[i].is_empty())
.unwrap_or(lists.len())
};
let waits: Vec<crate::list::ValueWait> = by[from..to].concat();
pieces.extend(waits.into_iter().map(Held::Value));
let (taken, order) = crate::list::detach(&lists[from..to]);
pieces.push(Held::Run(taken, order));
from = to;
}
lock(&queue(this).held).extend(pieces);
let mut waiting = lock(&WAITING);
if !waiting.contains(&(this as usize)) {
waiting.push(this as usize);
}
}
// What ran may be what another queue waits for, and what was just held
// may be free to run already.
release_held(false);
}
/// Adds `what()` to what the queue holds, if it holds anything (it waits
/// for a fence): whether it was added.
#[cfg(windows)]
fn hold(this: This, what: impl FnOnce() -> Held) -> bool {
if this.is_null() {
return false;
}
let mut held = lock(&queue(this).held);
if held.is_empty() {
return false;
}
held.push(what());
true
}
/// Runs what waiting queues hold as far as their fences have been reached
/// (`all`: all of it), each queue's in the order it was given. Called
/// where a fence may have moved: after a signal and after a submission (a
/// list's bottom-of-pipe write may be into a fence), never from inside
/// one.
#[cfg(windows)]
pub(crate) fn release_held(all: bool) {
// One caller at a time, so a queue's submissions keep their order.
static RELEASING: std::sync::Mutex<()> = std::sync::Mutex::new(());
if lock(&WAITING).is_empty() {
return;
}
let _one = lock(&RELEASING);
loop {
let queues = lock(&WAITING).clone();
let mut moved = false;
for q in queues {
// SAFETY: a live queue: one released is taken off the list.
let held = unsafe { &(*(q as *const Queue)).held };
let mut held = lock(held);
loop {
match held.first() {
None => break,
Some(&Held::Wait(fence, value))
if !all && crate::fence::completed(fence as This) < value =>
{
break;
}
Some(Held::Value(wait)) if !all && !value_met(wait) => break,
Some(_) => {}
}
match held.remove(0) {
Held::Wait(..) => {}
Held::Value(wait) => {
// Passed at a present without being met: what the
// queue stood at.
if all && !value_met(&wait) {
static SEEN: AtomicU64 = AtomicU64::new(0);
if SEEN.fetch_add(1, Ordering::Relaxed) < 16 {
tracing::warn!(
queue = format_args!("{q:#x}"),
?wait,
"a wait for a memory value was not met at a present: the queue runs on"
);
}
}
}
Held::Run(lists, order) => {
#[cfg(feature = "diagnostics")]
crate::capture::op(q, || {
format!(
"RUN held submission of {} lists (forced {all})",
order.len()
)
});
// Diagnostics: the part behind this one stands at
// waits that are met already, so the two could have
// been one host submission (one wait for the card,
// each range shaders write compared once).
#[cfg(feature = "diagnostics")]
{
let waits = held.iter().take_while(|h| matches!(h, Held::Value(_))).count();
if waits > 0
&& matches!(held.get(waits), Some(Held::Run(..)))
&& held[..waits].iter().all(|h| matches!(h, Held::Value(w) if w.met()))
{
crate::copystat::add(crate::copystat::C::PartsTogether, 1);
}
}
if crate::host::late()
&& let Some(host) = crate::host::host()
{
// Not waited for: the host keeps the lists
// until they are settled.
host.execute_late(lists, order);
} else {
let ran = {
let runs: Vec<&crate::host::HostList> =
order.iter().map(|&i| lists[i].host()).collect();
match crate::host::host() {
Some(host) => {
host.execute(&runs);
true
}
None => false,
}
};
// They have run: their host lists are used again.
if ran {
crate::list::recycle(lists, &order);
}
}
if all {
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::Forced, 1);
static ONCE: AtomicBool = AtomicBool::new(false);
if !ONCE.swap(true, Ordering::Relaxed) {
tracing::warn!(
"a queue still held a submission at a present: its fence was not reached"
);
}
}
}
// Behind what was sent to the card and not waited
// for, if anything was.
Held::Signal(fence, value) => {
if !crate::host::late_signal(fence, value) {
crate::fence::set(fence as This, value);
}
}
}
moved = true;
}
if held.is_empty() {
lock(&WAITING).retain(|&w| w != q);
}
}
if !moved {
break;
}
}
}
/// Whether a queue may pass `wait`: memory holds the value, or, with
/// submissions sent to the card without a wait (`crate::host::late`), it
/// will once those in the air have run.
#[cfg(windows)]
fn value_met(wait: &crate::list::ValueWait) -> bool {
wait.met() || (crate::host::late() && crate::host::late_met(wait))
}
fn queue<'a>(this: This) -> &'a Queue {
// SAFETY: called from queue methods only.
unsafe { &*this.cast::<Queue>() }
@@ -61,6 +455,8 @@ pub(crate) extern "system" fn create(
},
kind: desc.kind,
desc,
#[cfg(windows)]
held: Default::default(),
});
object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out)
}
@@ -107,11 +503,17 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT
)
}
extern "system" fn release(this: This) -> u32 {
object::release_boxed::<Queue>(this)
let left = object::release_boxed::<Queue>(this);
#[cfg(windows)]
if left == 0 {
lock(&WAITING).retain(|&q| q != this as usize);
}
left
}
/// Runs the lists' host lists and waits for them (decision 0007).
extern "system" fn execute(_: This, count: u32, lists: *const This) {
/// Runs the lists' host lists and waits for them (decision 0007). A queue
/// that waits for a fence keeps them until the fence is reached.
extern "system" fn execute(this: This, count: u32, lists: *const This) {
if lists.is_null() {
return;
}
@@ -119,13 +521,64 @@ extern "system" fn execute(_: This, count: u32, lists: *const This) {
if let Some(host) = crate::host::host() {
// SAFETY: the title passes `count` lists.
let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) };
if cuts() && !this.is_null() {
submit_cut(this, lists);
return;
}
if waits() && split() && !this.is_null() {
submit_split(this, lists);
return;
}
// A list that waits for a memory value not there yet: the queue
// holds the submission, as it does behind a fence.
if waits() && !this.is_null() {
let unmet = crate::list::unmet_waits(lists);
if !unmet.is_empty() {
static SEEN: AtomicU64 = AtomicU64::new(0);
if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
tracing::info!(kind = queue(this).kind, ?unmet, "a submission is held for a memory value");
}
lock(&queue(this).held).extend(unmet.into_iter().map(Held::Value));
let mut waiting = lock(&WAITING);
if !waiting.contains(&(this as usize)) {
waiting.push(this as usize);
}
}
}
let kept = hold(this, || {
let (taken, order) = crate::list::detach(lists);
Held::Run(taken, order)
});
// Diagnostics: the order submissions are made in, next to the
// commands of the frame's `ops` file (which are in recording order).
#[cfg(feature = "diagnostics")]
crate::capture::op(this as usize, || {
let kind = (!this.is_null()).then(|| queue(this).kind);
// The lists as the frame's other lines name them (their host sides).
let named: Vec<String> = lists
.iter()
.map(|&l| match crate::list::host_list(l) {
Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize),
None => format!("title {l:?}"),
})
.collect();
format!("SUBMIT queue kind {kind:?} held {kept} lists {named:?}")
});
if kept {
return;
}
let host_lists: Vec<_> = lists
.iter()
.filter_map(|&l| crate::list::host_list(l))
.collect();
host.execute(&host_lists);
crate::list::tables_done(lists);
// What the lists wrote at the bottom of the pipe may be a fence
// another queue waits for.
release_held(false);
return;
}
let _ = this;
static ONCE: AtomicBool = AtomicBool::new(false);
if !ONCE.swap(true, Ordering::Relaxed) {
tracing::warn!(count, "command lists submitted; no host GPU runs them");
@@ -157,15 +610,80 @@ extern "system" fn signal2_x(
}
/// Markers and events only matter to profilers.
extern "system" fn marker(_: This) {}
extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT {
extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT {
if fence.is_null() {
return E_INVALIDARG;
}
// A queue that waits signals after what it holds.
#[cfg(windows)]
if hold(this, || Held::Signal(fence as usize, value)) {
return S_OK;
}
// Behind the submissions sent to the card and not waited for: the
// fence is set when they are settled.
#[cfg(windows)]
if crate::host::late_signal(fence as usize, value) {
return S_OK;
}
let _ = this;
crate::fence::signal(fence, value)
}
/// Nothing runs on the queue, so waiting for a fence never blocks it.
extern "system" fn wait(_: This, fence: This, _value: u64) -> HRESULT {
if fence.is_null() { E_INVALIDARG } else { S_OK }
/// From here on the queue runs nothing it is given until `fence` reaches
/// `value`: how the console orders work between queues (the title's
/// compute queue waits for the depth the graphics queue draws). Our
/// submissions run when they are made, so a wait for a value already
/// reached is nothing; otherwise what the queue is given next is held
/// ([`Held`]) until a signal or a list's bottom-of-pipe write gets the
/// fence there.
extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT {
if fence.is_null() {
return E_INVALIDARG;
}
#[cfg(windows)]
if !this.is_null() {
let now = crate::fence::completed(fence);
// Whether the title uses this at all (the first calls).
{
static CALLS: AtomicU64 = AtomicU64::new(0);
if CALLS.fetch_add(1, Ordering::Relaxed) < 8 {
tracing::info!(kind = queue(this).kind, now, value, "a queue is told to wait for a fence");
}
}
#[cfg(feature = "diagnostics")]
crate::capture::op(this as usize, || format!("WAIT queue kind {} for fence {fence:?} value {value} (now {now})", queue(this).kind));
let behind = {
let mut held = lock(&queue(this).held);
let behind = !held.is_empty() || now < value;
if behind && waits() {
held.push(Held::Wait(fence as usize, value));
}
behind
};
if behind {
static SEEN: AtomicU64 = AtomicU64::new(0);
if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
tracing::info!(
kind = queue(this).kind,
now,
value,
held = waits(),
"a queue waits for a fence not reached yet"
);
}
}
if behind && waits() {
{
let mut waiting = lock(&WAITING);
if !waiting.contains(&(this as usize)) {
waiting.push(this as usize);
}
}
// The fence may have got there meanwhile.
release_held(false);
}
}
let _ = (this, value);
S_OK
}
/// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]).
extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT {
@@ -242,6 +760,24 @@ extern "system" fn present(
plane_parameters: *const Plane,
_parameters: *const u8,
) -> HRESULT {
#[cfg(all(windows, feature = "diagnostics"))]
crate::copystat::present_begins();
// Submissions sent to the card and not waited for are settled first,
// and what that frees runs in its own order, before anything is forced.
#[cfg(windows)]
if crate::host::late() && !crate::host::late_free_present() {
crate::host::settle_for_present();
release_held(false);
crate::host::settle_for_present();
} else if crate::host::late() {
// The present is sent ahead too: what waits for a value a flight
// will write runs behind that flight, and nothing is settled here.
release_held(false);
}
// shortcut: what a queue still holds at a present runs now, whatever
// its fence: a wait is not kept across frames.
#[cfg(windows)]
release_held(forces());
let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1;
if frame.is_power_of_two() {
let (draws, dispatches) = crate::list::take_counts();
@@ -272,8 +808,11 @@ extern "system" fn present(
}
}
#[cfg(all(windows, feature = "diagnostics"))]
if crate::capture::listed(frame) {
crate::capture::dump_targets(frame);
{
crate::capture::frame_drew(frame, crate::draw::drawn());
if crate::capture::listed(frame) {
crate::capture::dump_targets(frame);
}
}
#[cfg(windows)]
if planes > 0
File diff suppressed because it is too large. Load diff
+38 -1
View File
@@ -15,6 +15,7 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use victory_pipeline::{Cache, Converter};
use victory_shader::emit::{HostShader, StaticSampler, UserData};
use victory_shader::resource::RootIndexedView;
use victory_shader::{HwStage, RootType};
static CACHE: OnceLock<Cache> = OnceLock::new();
@@ -53,6 +54,8 @@ fn build() -> &'static [u8; 32] {
match exe {
Ok(mut bytes) => {
bytes.extend_from_slice(&limit.to_le_bytes());
// Which group barriers wait is part of the translation too.
bytes.push(victory_shader::emit::group_sync());
*blake3::hash(&bytes).as_bytes()
}
Err(e) => {
@@ -206,10 +209,22 @@ fn encode(s: &HostShader) -> Vec<u8> {
word(&mut out, v);
}
}
for slots in [&s.root_cbvs, &s.root_srvs] {
for slots in [&s.root_cbvs, &s.root_srvs, &s.root_uavs] {
word(&mut out, slots.len() as u32);
out.extend(slots);
}
word(&mut out, s.root_indexed_views.len() as u32);
for view in &s.root_indexed_views {
for value in [
u32::from(view.table_slot),
u32::from(view.constant_slot),
view.constant_dword,
view.byte_offset,
u32::from(view.shift),
] {
word(&mut out, value);
}
}
out
}
@@ -266,6 +281,18 @@ fn decode(bytes: &[u8]) -> Option<HostShader> {
}
let root_cbvs = r.list()?;
let root_srvs = r.list()?;
let root_uavs = r.list()?;
let n = r.word()? as usize;
let mut root_indexed_views = Vec::with_capacity(n.min(256));
for _ in 0..n {
root_indexed_views.push(RootIndexedView {
table_slot: u8::try_from(r.word()?).ok()?,
constant_slot: u8::try_from(r.word()?).ok()?,
constant_dword: r.word()?,
byte_offset: r.word()?,
shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?,
});
}
r.0.is_empty().then_some(HostShader {
stage,
dxil,
@@ -274,6 +301,8 @@ fn decode(bytes: &[u8]) -> Option<HostShader> {
static_samplers,
root_cbvs,
root_srvs,
root_uavs,
root_indexed_views,
})
}
@@ -300,6 +329,14 @@ mod tests {
])],
root_cbvs: vec![2],
root_srvs: vec![0, 3],
root_uavs: vec![1],
root_indexed_views: vec![RootIndexedView {
table_slot: 1,
constant_slot: 2,
constant_dword: 3,
byte_offset: 32,
shift: 5,
}],
}
}
File diff suppressed because it is too large. Load diff
+841 -18
View File
@@ -43,18 +43,29 @@ pub(crate) struct Staging {
layout: victory_formats::texture::Layout,
/// Mips per array slice.
mips: u32,
/// The staging buffer's bytes (counted in `STAGED` while it lives).
bytes: u64,
memory: *const u8,
last: Mutex<Last>,
/// Whether the staging buffer was detiled since a submitted list last
/// uploaded it, and whether one has uploaded it at all: a list records
/// the upload only then. (Every list that sampled a title texture
/// uploaded all of it again, changed or not: 5,411 subresource copies
/// of 1,120 textures in one frame of run 18.)
dirty: std::sync::atomic::AtomicBool,
uploaded: std::sync::atomic::AtomicBool,
/// When a list last recorded a use of it (`crate::host::moment`).
used: std::sync::atomic::AtomicU64,
}
/// What a texture's staging buffer holds: the hash of the memory detiled
/// (memory not watched), or the write-watch asking it was detiled after,
/// with room to read the memory into.
/// (memory not watched), or the write-watch asking it was detiled after.
#[derive(Default)]
struct Last {
hash: Option<blake3::Hash>,
asked: u64,
read: Vec<u8>,
/// The frame a partly mapped texture was last read in.
partial: Option<u64>,
}
// SAFETY: the staging mapping is written only at submission, under
@@ -65,6 +76,378 @@ unsafe impl Sync for Staging {}
static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None);
/// The buffer a texture the host writes is copied through into the texture
/// of a view the title placed in its memory in another format
/// ([`alias`]): every level of every layer as each of the two formats lays
/// it out for a copy (the same bytes: the texels are as wide), the written
/// texture's layout first.
struct Through {
buffer: ID3D12Resource,
parts: Vec<(
D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
)>,
}
/// The most levels times layers [`alias`] copies (a cube of nine levels).
const ALIAS_PARTS: u32 = 54;
// SAFETY: a device-local buffer only lists record copies with.
unsafe impl Send for Through {}
// SAFETY: as above.
unsafe impl Sync for Through {}
/// The copy buffers of [`alias`], by the placed view's texture.
static THROUGH: Mutex<Option<HashMap<usize, Arc<Through>>>> = Mutex::new(None);
/// Brings `placed`, the texture of a view the title placed in the memory
/// of `source` in another format (`crate::resource::alias_of`), up to date
/// with what the host wrote to `source`: the texels of every level and
/// layer are copied as they are, through a buffer (the host copies between
/// two formats of one texel width in no other way). Recorded the first time
/// the list reads the view
/// and again whenever the list used `source` in another way since (wrote
/// it, or read it itself). Leaves `placed` in the copy destination state,
/// as [`upload`] does. False if the copy cannot be made: the caller fills
/// the texture from title memory, as before.
pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool {
const TARGET_OR_UNORDERED: u32 = 0x4 | 0x8;
const COPY_DEST: u32 = 0x400;
const COPY_SOURCE: u32 = 0x800;
let (Some(to), Some(from)) = (
crate::resource::host_resource(placed),
crate::resource::host_resource(source),
) else {
return false;
};
let Some(host) = host() else { return false };
let through = {
let mut map = THROUGH.lock().unwrap_or_else(|e| e.into_inner());
let map = map.get_or_insert_with(HashMap::new);
match map.get(&(placed as usize)) {
Some(through) => through.clone(),
None => {
// SAFETY: live textures.
let (of_from, of_to) = unsafe { (from.GetDesc(), to.GetDesc()) };
// Levels times layers (a volume's slices are one part).
let count = |d: &D3D12_RESOURCE_DESC| {
let layers = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D {
1
} else {
u32::from(d.DepthOrArraySize)
};
u32::from(d.MipLevels) * layers
};
let parts = count(&of_from);
if parts == 0 || parts > ALIAS_PARTS || parts != count(&of_to) {
return false;
}
let mut rows = [(); 2]
.map(|()| vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); parts as usize]);
let mut bytes = [0u64; 2];
// SAFETY: plain queries; the out pointers are ours and
// hold `parts` layouts each.
unsafe {
host.device.GetCopyableFootprints(
&of_from,
0,
parts,
0,
Some(rows[0].as_mut_ptr()),
None,
None,
Some(&mut bytes[0]),
);
host.device.GetCopyableFootprints(
&of_to,
0,
parts,
0,
Some(rows[1].as_mut_ptr()),
None,
None,
Some(&mut bytes[1]),
);
}
let alike = rows[0].iter().zip(&rows[1]).all(|(a, b)| {
let (fa, fb) = (a.Footprint, b.Footprint);
a.Offset == b.Offset
&& (fa.Width, fa.Height, fa.Depth, fa.RowPitch)
== (fb.Width, fb.Height, fb.Depth, fb.RowPitch)
});
if bytes[0] == 0 || bytes[0] != bytes[1] || !alike {
return false;
}
let Some(buffer) = host.uav_buffer(bytes[0]) else {
return false;
};
crate::host::name(&buffer, || {
format!(
"alias copy {}x{} f{} to f{}",
of_from.Width, of_from.Height, of_from.Format.0, of_to.Format.0
)
});
tracing::info!(
view = ?placed,
texture = ?source,
width = of_from.Width,
height = of_from.Height,
parts,
written_as = of_from.Format.0,
read_as = of_to.Format.0,
"a view placed in the memory of a texture the host writes, in another format: read from that texture by a copy on the host"
);
let [of_written, of_read] = rows;
let through = Arc::new(Through {
buffer,
parts: of_written.into_iter().zip(of_read).collect(),
});
map.insert(placed as usize, through.clone());
through
}
}
};
let first = list.first_use(placed as usize);
// The source's first use in the list records nothing (its prelude
// brings it to the state); a use in another way since the last copy
// shows as a change of state.
let before = list.transition(source, COPY_SOURCE).map(|(texture, before)| {
let state = crate::host::legal_state(texture, COPY_SOURCE);
let barrier = crate::host::transition(
texture,
D3D12_RESOURCE_STATES(before as i32),
D3D12_RESOURCE_STATES(state as i32),
);
// SAFETY: an open list and a live texture.
unsafe { list.list.ResourceBarrier(&[barrier]) };
before
});
if !first && before.is_none() {
return true;
}
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.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: index as u32,
},
};
let rows = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(&through.buffer) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: *row,
},
};
let (common, read, written) = (
D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATE_COPY_DEST,
);
#[cfg(feature = "diagnostics")]
list.note_op(|| format!("alias copy of {source:?} into {placed:?}"));
// SAFETY: an open list and live resources; the buffer is as big as
// the footprints and rests in the common state between copies.
unsafe {
list.list
.ResourceBarrier(&[crate::host::transition(&through.buffer, common, written)]);
for (index, (of_written, _)) in through.parts.iter().enumerate() {
list.list
.CopyTextureRegion(&rows(of_written), 0, 0, 0, &part(from, index), None);
}
list.list
.ResourceBarrier(&[crate::host::transition(&through.buffer, written, read)]);
for (index, (_, of_read)) in through.parts.iter().enumerate() {
list.list
.CopyTextureRegion(&part(to, index), 0, 0, 0, &rows(of_read), None);
}
list.list
.ResourceBarrier(&[crate::host::transition(&through.buffer, read, common)]);
}
list.keep(&through.buffer);
// A draw that also writes the source (a view of it handled before
// this one) needs it in that state again; the next read of the alias
// then copies once more, as it must after a write.
if let Some(before) = before
&& before & TARGET_OR_UNORDERED != 0
{
crate::list::ensure_state(list, source, before);
}
true
}
/// Whether a texture refresh that finds the runtime remapping title memory
/// goes on without waiting for it (`VICTORY_TEXTURE_NO_WAIT=1`; off by
/// default).
///
/// A texture whose memory is all mapped is read in place, under a lock
/// the runtime takes alone while it changes a mapping
/// (`crate::watch::title_memory_reading`), so that no page goes away under
/// the read. While the world streams in the runtime remaps all the time,
/// and each of the frame's 150-360 refreshes waited for it: runs 99-101
/// have 4, 15 and 16 frame lines with over 300 ms of "textures", up to
/// 3,708 ms, and on every one of them the wait for this lock is the whole
/// of it (1,345 of 1,381 ms; 3,630 of 3,708; the write-watch askings 3-12
/// ms, the texture's own lock 0).
///
/// With the switch the refresh asks for the lock without waiting. If the
/// runtime has it, the texture is read through the kernel instead, which
/// needs no lock: it fails if a page is not there, and then the texture is
/// left as it is and read at its next refresh, a frame later. A read
/// through the kernel costs about 0.6 ms a megabyte against 0.3 in place.
///
/// What changes for the picture: a texture that arrives while the runtime
/// is remapping may show a frame later. It never shows partly read.
fn no_wait() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_NO_WAIT").is_some_and(|v| v == "1"))
}
/// Since the last frame-rate line, with [`no_wait`]: refreshes that read
/// through the kernel because title memory was being remapped, and those
/// left for the next refresh because a page was not there.
pub(crate) static UNLOCKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
/// Since the last frame-rate line, of texture refreshes on every thread, in
/// microseconds: waiting for the texture's own lock (another thread is
/// refreshing the same texture), asking the write watch and the guards,
/// waiting for title memory to hold still (the lock the runtime takes
/// alone while it remaps, `crate::watch::title_memory_reading`), and the
/// refreshes in all.
///
/// While the world streams in, the frame line's "textures" is seconds a
/// frame in some runs and tenths in others for the same megabytes (2,566
/// ms for 110 MB in run 93, 314 ms for 132 MB in run 91; before these
/// counters, runs 81, 83, 85 and 94 each had lines of 1.5-2.9 s), and the
/// submitting thread is not running while it lasts (run 93: 240-310 ms of
/// its own time a frame beside 1,100-1,800 ms of "textures"): it waits.
/// These say for what.
pub(crate) static REFRESH_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
/// `f`'s result, its time added to [`REFRESH_WAITS`]' place `slot`.
fn waited<T>(slot: usize, f: impl FnOnce() -> T) -> T {
let started = std::time::Instant::now();
let out = f();
REFRESH_WAITS[slot].fetch_add(started.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed);
out
}
thread_local! {
/// Room to read a texture's memory into: one buffer per submitting
/// thread. Each texture kept its own, a second copy in memory of every
/// write-watched or partly mapped texture ever sampled, for the run.
static READ: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Calls `f` with `size` bytes of this thread's read buffer (their
/// contents are whatever the last texture left).
fn with_read<R>(size: usize, f: impl FnOnce(&mut [u8]) -> R) -> R {
READ.with(|read| {
let mut read = read.borrow_mut();
if read.len() < size {
read.resize(size, 0);
}
f(&mut read[..size])
})
}
/// Whether a texture all of whose memory is mapped is read through the
/// kernel's copy instead of in place (`VICTORY_TEXTURE_COPY=1`; off by
/// default). Round 3 of the memory work read every such texture that way
/// to be safe from pages taken away under the read; it cost 0.6 ms per MB
/// against 0.3 in place (90-105 ms a frame while the world streams in, runs
/// 72 and 73, against 20-40), and both runs with it lost the graphics
/// device, for a reason not found. The read in place is safe now for
/// another reason (`crate::watch::title_memory_reading`); this switch is
/// left to tell whether the copy was what lost the device.
fn through_copy() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_COPY").is_some_and(|v| v == "1"))
}
/// Calls `f` with the `size` bytes of title memory at `memory`, read
/// through the kernel into this thread's read buffer; pages that are not
/// there read as zeros. The bytes are those a read in place would see.
fn with_title<R>(memory: *const u8, size: usize, f: impl FnOnce(&[u8]) -> R) -> R {
with_read(size, |read| {
crate::host::copy_mapped(read.as_mut_ptr(), memory, size, false);
f(read)
})
}
/// Staging buffers alive (also those only a list still holds) and their
/// bytes.
static STAGED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
impl Drop for Staging {
fn drop(&mut self) {
use std::sync::atomic::Ordering::Relaxed;
STAGED[0].fetch_sub(1, Relaxed);
STAGED[1].fetch_sub(self.bytes, Relaxed);
}
}
/// For the memory line: staging buffers alive, their bytes, and how many
/// of them their texture still has (the others wait for a list's reset).
#[cfg(feature = "diagnostics")]
pub(crate) fn memory() -> [u64; 3] {
use std::sync::atomic::Ordering::Relaxed;
let kept = STAGING
.lock()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.map_or(0, |map| map.len() as u64);
[STAGED[0].load(Relaxed), STAGED[1].load(Relaxed), kept]
}
/// Staging buffers let go as idle since the start, and their bytes.
static LET_GO: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
/// For the memory line: staging buffers let go as idle, and their bytes.
#[cfg(feature = "diagnostics")]
pub(crate) fn let_go() -> [u64; 2] {
use std::sync::atomic::Ordering::Relaxed;
[LET_GO[0].load(Relaxed), LET_GO[1].load(Relaxed)]
}
/// Lets go of the staging buffers no list recorded a use of for `IDLE_MS`
/// and `IDLE_FRAMES` frames and no list holds: a staging buffer is system memory the size of its
/// texture, kept so that an unchanged texture is not uploaded again, and
/// those of textures no longer sampled were kept for the run (2,246 of
/// them, 2.1 GB, at the end of run 24). The next list that samples such a
/// texture makes a staging buffer anew, detiles and uploads once more.
/// Called before a submission starts, by the thread that submits.
pub(crate) fn let_go_idle() {
use std::sync::atomic::Ordering::Relaxed;
const IDLE_MS: u64 = 10_000;
const IDLE_FRAMES: u64 = 4;
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
let Some(map) = map.as_mut() else {
return;
};
// A list that recorded an upload or a check holds the staging until it
// is reset: one only the table holds is named by no list, recorded or
// running.
let (mut went, mut bytes) = (0u64, 0u64);
map.retain(|_, s| {
let keep = Arc::strong_count(s) > 1
|| !crate::host::long_ago(s.used.load(Relaxed), IDLE_MS, IDLE_FRAMES);
if !keep {
LET_GO[0].fetch_add(1, Relaxed);
LET_GO[1].fetch_add(s.bytes, Relaxed);
went += 1;
bytes += s.bytes;
}
keep
});
if went > 0 {
crate::host::trail(|| format!("sweep: {went} staging buffers of textures let go ({} KiB), held by no list", bytes >> 10));
}
}
/// Textures the host GPU wrote by a copy or resolve: their contents are on
/// the host, not in title memory, which stays as it was.
static HOST_WRITTEN: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None);
@@ -76,6 +459,17 @@ pub(crate) fn host_written(resource: This) {
.insert(resource as usize);
}
/// Whether the host GPU wrote `resource` by a copy or resolve
/// ([`host_written`]): its host copy cannot be made again from title
/// memory.
pub(crate) fn host_wrote(resource: usize) -> bool {
HOST_WRITTEN
.lock()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.is_some_and(|set| set.contains(&resource))
}
/// The title released a resource.
pub(crate) fn forget(resource: usize) {
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
@@ -86,6 +480,10 @@ pub(crate) fn forget(resource: usize) {
if let Some(set) = set.as_mut() {
set.remove(&resource);
}
let mut through = THROUGH.lock().unwrap_or_else(|e| e.into_inner());
if let Some(through) = through.as_mut() {
through.remove(&resource);
}
}
/// Whether `resource`'s host copy takes its contents from title memory:
@@ -114,6 +512,20 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
let Some(staging) = staging(resource, texture) else {
return;
};
use std::sync::atomic::Ordering::Relaxed;
staging.used.store(crate::host::moment(), 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
// frame was recorded before that check).
if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexSkipped, 1);
list.defer_texture(staging);
return;
}
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexUploads, 1);
const COPY_DEST: u32 = 0x400;
crate::list::ensure_state(list, resource, COPY_DEST);
// The staging buffer lives as long as `staging`, which the deferred
@@ -165,11 +577,26 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
// SAFETY: an open list; both locations name live resources.
unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
}
// When the list is submitted, its copy takes what the staging buffer
// holds by then: noted before the check below, which sets `dirty`
// again if it detiles (the next list then uploads once more).
{
let staging = staging.clone();
list.defer_host(move || {
staging.uploaded.store(true, Relaxed);
staging.dirty.store(false, Relaxed);
});
}
// Once per submission however many of its lists sample the texture.
list.defer_texture(staging);
}
impl Staging {
/// 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)
}
/// Detiles the texture memory into the staging buffer if it changed
/// since the last time (and is mapped at all).
pub(crate) fn refresh(&self) {
@@ -183,35 +610,123 @@ impl Staging {
/// Returns the bytes of title memory read.
fn refresh_now(&self) -> usize {
let whole = std::time::Instant::now();
let read = self.refresh_timed();
REFRESH_WAITS[3].fetch_add(whole.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed);
read
}
fn refresh_timed(&self) -> usize {
let size = self.layout.size as usize;
let start = self.memory as usize;
let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner()));
let last = &mut *last;
if let Some((now, written)) = crate::watch::writes(start, start + size, false) {
if let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) {
if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
return 0;
}
last.asked = now;
// Read through the copy, which stands unmapped pages: memory of
// big pools is too slow to ask page by page.
last.read.resize(size, 0);
crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false);
self.detile(&last.read);
with_read(size, |read| {
crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false);
self.detile(read);
});
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexWatched, size as u64);
return size;
}
if !committed(self.memory, size) {
#[cfg(feature = "diagnostics")]
tracing::debug!(
memory = ?self.memory,
size,
desc = ?self.layout.desc,
"a sampled texture's memory is not committed"
);
return 0;
// View memory has no write-watch, and a texture there was hashed
// whole at every check: 229 MB and 51 ms a frame in a gameplay view
// where two textures change (run 58). It is guarded now, as buffers
// in view memory are: a write of the title's to it faults once and
// is noted, a mapping is announced by the runtime. While neither
// happened the texture is as it was. What the guard cannot see (a
// write to the same pages through another view) is still found by
// the hash, which is taken every eighth frame only, by the
// texture's address, so the textures take turns.
// `VICTORY_TEXTURE_GUARD=0` hashes at every check, as before.
static GUARD: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0"))
&& let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true))
{
const HASH_EVERY: u64 = 8;
let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked);
last.asked = now;
let turn = crate::frame::current().wrapping_add((start >> 16) as u64) % HASH_EVERY == 0;
if unwritten && !turn {
return 0;
}
}
// SAFETY: committed memory of the texture's layout size.
// From here on the texture's memory may be read in place. Held until
// that read is done: the runtime changes what title memory shows
// only with this taken alone, so what `committed` finds mapped
// stays mapped (see `crate::watch::title_memory_reading`; without
// it a page went between the asking and the read in runs 71 and
// 74).
let _mapped = if no_wait() {
// Not waited for: while the runtime remaps title memory the
// texture is read through the kernel instead, whole or not at
// all (`no_wait`).
let Some(mapped) = crate::watch::title_memory_reading_now() else {
return self.refresh_unlocked(last, size);
};
mapped
} else {
waited(2, crate::watch::title_memory_reading)
};
if !committed(self.memory, size) {
// Partly mapped: a streamed texture with only some mips' pages
// there, the usual state while it streams in. Read through the
// copy, which stands unmapped pages (zeros), and upload what
// is there; nothing at all mapped changes nothing.
// shortcut: read again at most every 30 frames (reading around
// unmapped pages is slow, and nothing tells us when pages
// arrive): a mip that streams in shows up to 30 frames late.
let frame = crate::frame::current();
if last.partial.is_some_and(|at| frame < at + 30) {
return 0;
}
last.partial = Some(frame);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
let changed = with_read(size, |read| {
crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false);
let hash = blake3::hash(read);
if last.hash == Some(hash) {
return false;
}
last.hash = Some(hash);
if read.iter().all(|&b| b == 0) {
return false;
}
self.detile(read);
true
});
#[cfg(feature = "diagnostics")]
if changed {
crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
}
let _ = changed;
return size;
}
if through_copy() {
return with_title(self.memory, size, |tiled| {
let hash = blake3::hash(tiled);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
if last.hash == Some(hash) {
return size;
}
last.hash = Some(hash);
self.detile(tiled);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
size
});
}
// SAFETY: committed memory of the texture's layout size, and it
// stays committed while `_mapped` is held.
let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) };
let hash = blake3::hash(tiled);
#[cfg(feature = "diagnostics")]
@@ -226,8 +741,38 @@ impl Staging {
size
}
/// A refresh while the runtime is remapping title memory ([`no_wait`]):
/// the texture is read through the kernel, which fails if a page of it
/// is not there at this moment. Then nothing is taken and the texture
/// is looked at again at its next refresh (what was learnt about writes
/// to it is forgotten, so that it is not passed over as unwritten).
/// Returns the bytes read.
fn refresh_unlocked(&self, last: &mut Last, size: usize) -> usize {
use std::sync::atomic::Ordering::Relaxed;
let read = with_read(size, |read| {
if !crate::host::read_into(self.memory, read) {
return false;
}
let hash = blake3::hash(read);
if last.hash != Some(hash) {
last.hash = Some(hash);
self.detile(read);
}
true
});
if read {
UNLOCKED[0].fetch_add(1, Relaxed);
size
} else {
UNLOCKED[1].fetch_add(1, Relaxed);
last.asked = 0;
0
}
}
/// Detiles `tiled` (the texture's memory) into the staging buffer.
fn detile(&self, tiled: &[u8]) {
self.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
if tiled.iter().all(|&b| b == 0) {
tracing::debug!(
@@ -256,9 +801,109 @@ impl Staging {
}
}
/// Lets go of a title texture's staging buffer (lists that recorded an
/// upload from it hold it until they have run); the next upload makes one
/// anew.
pub(crate) fn unstage(resource: This) {
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
if let Some(map) = map.as_mut() {
map.remove(&(resource as usize));
}
}
/// Whether a title texture has a staging buffer: a list recorded its
/// upload, and the lists that sample it check it at submission.
pub(crate) fn is_staged(resource: This) -> bool {
let map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize)))
}
/// The bytes of a title texture's memory, and whether all of it is mapped,
/// if the texture has been staged for upload.
pub(crate) fn staged(resource: This) -> Option<(u64, bool)> {
let s = {
let map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
map.as_ref()?.get(&(resource as usize))?.clone()
};
let size = s.layout.size as usize;
Some((size as u64, committed(s.memory, size)))
}
/// Whether `[at, at + len)` is committed memory (streamed textures may be
/// unmapped until their pages arrive).
pub(crate) fn committed(at: *const u8, len: usize) -> bool {
if by_query() {
return committed_by_query(at, len);
}
if len == 0 {
return true;
}
let (there, of) = readable(at as usize, len, true);
there == of
}
/// Whether the two questions above and below are put to `VirtualQuery`, as
/// they were (`VICTORY_COMMITTED_QUERY=1`). `VirtualQuery` answers with the
/// length of the run of pages in the same state, which it finds by walking
/// the page tables to the run's end: 8.8 ms for one question in the title's
/// 1.1 GB block (round 6). The pass over the heap's views asks three or
/// more of them for every texture slot that is due, 3,000 slots a frame
/// when the card has no room (run 75): that pass then ran 208-264 ms, and
/// while it ran the submitting thread's write-watch askings waited behind
/// the walks (run 76: 8-22 askings a frame of 6-21 ms each, 46-172 ms).
fn by_query() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_COMMITTED_QUERY").is_some_and(|v| v == "1"))
}
/// Of the kernel's pages that hold `[at, at + len)` (`len > 0`): how many
/// can be read, and how many there are; with `all`, it stops at the first
/// that cannot. One question to the kernel for up to 256 pages at once
/// (`QueryWorkingSetEx`: the state of each page asked about, no walk); a
/// page not in the working set may still be there (never touched, or
/// trimmed), and a one-byte read through the kernel says.
/// A page that is committed and may not be read counts as not there, which
/// is what the callers ask for: they read or write the memory next.
fn readable(at: usize, len: usize, all: bool) -> (usize, usize) {
use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
const KERNEL_PAGE: usize = 4096;
let (first, last) = (at / KERNEL_PAGE, at.saturating_add(len - 1) / KERNEL_PAGE);
let of = last - first + 1;
let mut there = 0;
// SAFETY: plain data.
let mut info: [PSAPI_WORKING_SET_EX_INFORMATION; 256] = unsafe { std::mem::zeroed() };
let mut page = first;
while page <= last {
let n = (last - page + 1).min(info.len());
for (i, entry) in info[..n].iter_mut().enumerate() {
entry.VirtualAddress = ((page + i) * KERNEL_PAGE) as *mut _;
}
// SAFETY: `n` entries of the size given; our own process.
let asked = unsafe {
K32QueryWorkingSetEx(
GetCurrentProcess(),
info.as_mut_ptr().cast(),
(n * size_of::<PSAPI_WORKING_SET_EX_INFORMATION>()) as u32,
)
} != 0;
for (i, entry) in info[..n].iter().enumerate() {
// Bit 0 of the answer: the page is in the working set.
// SAFETY: plain data the query filled in.
let valid = asked && unsafe { entry.VirtualAttributes.Flags } & 1 != 0;
let mut byte = [0u8];
if valid || crate::host::read_into(((page + i) * KERNEL_PAGE) as *const u8, &mut byte) {
there += 1;
} else if all {
return (there, of);
}
}
page += n;
}
(there, of)
}
fn committed_by_query(at: *const u8, len: usize) -> bool {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery};
let mut p = at as usize;
let end = p + len;
@@ -275,6 +920,67 @@ pub(crate) fn committed(at: *const u8, len: usize) -> bool {
true
}
/// How many bytes of `[at, at + len)` are committed memory: all of a
/// texture that is there, some of one streaming in (its smaller mips lie
/// at the start of its memory, and their pages are mapped first), none of
/// one not there. With neither the first nor the last page committed the
/// answer is none without a look at the pages between (two queries for the
/// slots whose texture is away, which are asked again and again).
pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery};
if len == 0 {
return 0;
}
let start = at as usize;
let end = start.saturating_add(len);
if !committed(at, 1) && !committed((end - 1) as *const u8, 1) {
return 0;
}
if !by_query() {
static BY_PAGE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if *BY_PAGE.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_PAGE").is_some_and(|v| v == "1")) {
// By page, without the walk: whole pages, cut to the range.
let (there, _) = readable(start, len, false);
return (there as u64 * 4096).min(len as u64);
}
// By 64 KiB block, one page asked of each: the title's memory is
// mapped in blocks of that size (the console's page), and the
// answer is a measure of how much of a texture has arrived, not a
// promise that every byte can be read (the upload reads through the
// kernel). By page, a texture half there cost a failed kernel read
// for each of its missing pages, every frame it stayed due: 1,663
// textures "uploaded in part" kept the pass over the heap's views at
// 90-160 ms a frame (run 81). `VICTORY_MAPPED_BY_PAGE=1`: by page.
const BLOCK: usize = 64 << 10;
let mut there = 0u64;
let mut block = start & !(BLOCK - 1);
while block < end {
let (lo, hi) = (block.max(start), block.saturating_add(BLOCK).min(end));
if readable(lo, 1, true).0 == 1 {
there += (hi - lo) as u64;
}
block = block.saturating_add(BLOCK);
}
return there;
}
let (mut p, mut there) = (start, 0u64);
while p < end {
// SAFETY: plain data filled in by the query.
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) };
let next = (info.BaseAddress as usize).saturating_add(info.RegionSize).min(end);
if n == 0 || next <= p {
break;
}
if info.State == MEM_COMMIT {
there += (next - p) as u64;
}
p = next;
}
there
}
/// The staging state of a title texture, made on first use.
fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
@@ -327,6 +1033,8 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
)
});
tracing::debug!(?desc, total, "texture contents uploaded from title memory");
STAGED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
STAGED[1].fetch_add(total, std::sync::atomic::Ordering::Relaxed);
let s = Arc::new(Staging {
buffer,
#[cfg(feature = "diagnostics")]
@@ -336,9 +1044,124 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
rows,
layout,
mips: u32::from(d.MipLevels),
bytes: total,
memory,
last: Mutex::default(),
dirty: std::sync::atomic::AtomicBool::new(true),
uploaded: std::sync::atomic::AtomicBool::new(false),
used: std::sync::atomic::AtomicU64::new(crate::host::moment()),
});
map.insert(resource as usize, s.clone());
Some(s)
}
#[cfg(test)]
mod title_memory_tests {
use super::with_title;
/// Title memory whose tail is reserved and not committed reads through
/// the copy as its bytes and then zeros, without a fault; so does
/// memory a page of which is taken away between two reads, and the
/// zeros are zeros whatever the read buffer held before.
#[test]
fn an_uncommitted_tail_reads_as_zeros() {
use windows_sys::Win32::System::Memory::*;
const HEAD: usize = 0xb_0000;
const SIZE: usize = 0x20_0000;
// SAFETY: a private reservation of our own; only committed pages
// are written in place, and nothing else reads them in place.
unsafe {
// The read buffer holds something else first.
let other = vec![0x77u8; SIZE];
with_title(other.as_ptr(), SIZE, |bytes| assert!(bytes.iter().all(|&b| b == 0x77)));
let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
assert!(!base.is_null());
assert_eq!(VirtualAlloc(base.cast(), HEAD, MEM_COMMIT, PAGE_READWRITE), base.cast());
base.write_bytes(0x5a, HEAD);
with_title(base, SIZE, |bytes| {
assert!(bytes[..HEAD].iter().all(|&b| b == 0x5a), "what is mapped");
assert!(bytes[HEAD..].iter().all(|&b| b == 0), "what is not: zeros");
});
// The title takes a page in the middle away: zeros from then
// on, the rest as before.
assert_ne!(VirtualFree(base.add(0x4_0000).cast(), 0x1_0000, MEM_DECOMMIT), 0);
with_title(base, SIZE, |bytes| {
assert!(bytes[..0x4_0000].iter().all(|&b| b == 0x5a));
assert!(bytes[0x4_0000..0x5_0000].iter().all(|&b| b == 0));
assert!(bytes[0x5_0000..HEAD].iter().all(|&b| b == 0x5a));
assert!(bytes[HEAD..].iter().all(|&b| b == 0));
});
assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
}
}
/// The texture both device-loss runs named last (16 texels wide, 4 or 8
/// high, format 10, layout 0x100, console flags 0x300000; its memory
/// began 0x300 into a page in run 73 and 0x700 in run 72, and here also
/// 0xf00, so that a page line runs through it): what the detiling is
/// given and what it writes are the same read in place and read through
/// the copy, and the rows it writes end where the staging buffer the
/// host sizes for it ends (896 bytes for 4 rows of 128 bytes 256 apart,
/// 1,920 for 8).
#[test]
fn the_small_texture_of_runs_72_and_73_detiles_the_same_both_ways() {
use windows_sys::Win32::System::Memory::*;
for (height, within) in [(4u32, 0x300usize), (8, 0x700), (4, 0xf00), (8, 0xf00)] {
// The description as the log printed it, word for word.
let words: [u32; 14] = [3, 0, 0, 0, 16, 0, height, 65537, 10, 1, 0, 256, 3_145_728, 0];
// SAFETY: fourteen words are a resource description (56 bytes,
// plain numbers).
let desc: crate::resource::ResourceDesc = unsafe { std::mem::transmute(words) };
let layout = crate::resource::texture_layout(&desc)
.expect("a console layout")
.planes[0]
.layout
.clone();
let size = layout.size as usize;
let (row, pitch) = (16 * 8, 256usize);
assert!(size >= row * height as usize, "the layout holds every texel");
// Committed pages and a reserved one after them; the texture
// begins `within` bytes into the first, as the title placed it.
// SAFETY: our own reservation; the committed part is written
// and read in place, by this thread alone.
unsafe {
let pages = size.div_ceil(4096) + 1;
let base = VirtualAlloc(std::ptr::null(), (pages + 1) * 4096, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
assert!(!base.is_null());
assert_eq!(VirtualAlloc(base.cast(), pages * 4096, MEM_COMMIT, PAGE_READWRITE), base.cast());
for i in 0..pages * 4096 {
base.add(i).write((i * 7 + i / 251) as u8);
}
let memory = base.add(within);
let in_place = std::slice::from_raw_parts(memory, size);
// The bytes: the same in place and through the copy.
with_title(memory, size, |copied| assert_eq!(copied, in_place));
// What the detiling writes: the same, and inside the bytes
// the host's staging buffer for this texture has.
let staged = (height as usize - 1) * pitch + row;
assert_eq!(staged, if height == 4 { 896 } else { 1920 });
let detile = |tiled: &[u8]| {
// The slice `Staging::detile` hands over: whole rows.
let mut linear = vec![0xeeu8; pitch * height as usize];
layout
.detile(tiled, 0, 0, &mut linear, pitch, pitch * height as usize)
.expect("detiled");
linear
};
let direct = detile(in_place);
let through = with_title(memory, size, |copied| detile(copied));
assert_eq!(direct, through);
for y in 0..height as usize {
assert!(direct[y * pitch..][..row].iter().any(|&b| b != 0xee), "row {y} written");
assert!(direct[y * pitch + row..(y + 1) * pitch].iter().all(|&b| b == 0xee), "nothing past row {y}");
}
// A buffer of exactly the staged bytes is enough.
let mut exact = vec![0u8; staged];
layout
.detile(in_place, 0, 0, &mut exact, pitch, pitch * height as usize)
.expect("the staging buffer's bytes are enough");
assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
}
}
}
}
+747 -20
View File
@@ -10,7 +10,9 @@
//! copy leaves each 64 KiB block it took read-only, and our vectored handler
//! takes the first write to it: it notes the block as written and gives the
//! write access back. The runtime tells us when it maps or unmaps views
//! ([`title_memory_remapped`]), which resets their protection.
//! ([`title_memory_remapped`]), which resets their protection. Blocks found
//! 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
@@ -35,14 +37,264 @@ struct Journal {
written: BTreeMap<usize, u64>,
/// Room for the kernel's answer.
found: Vec<usize>,
/// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`])
/// and the asking that did: `writes` answers for a range inside one
/// from the journal, without another kernel call.
ahead: Vec<(usize, usize)>,
ahead_asked: u64,
/// The ahead asking stands for a whole submission ([`ask_once`]): no
/// other ahead asking is made, and `ahead` stays, until
/// [`ask_once_end`].
kept: bool,
}
static JOURNAL: Mutex<Journal> = Mutex::new(Journal {
asked: 0,
written: BTreeMap::new(),
found: Vec::new(),
ahead: Vec::new(),
ahead_asked: 0,
kept: false,
});
/// Ranges of one submission closer than this are asked about together:
/// walking the pages between them costs less than another kernel call (a
/// call that resets written pages costs 30-70 microseconds whatever the
/// range).
const AHEAD_GAP: usize = (8 << 20) / PAGE;
/// The most one asking covers (its answer needs 8 bytes per 4 KiB page).
const AHEAD_MAX: usize = (1 << 30) / PAGE;
/// Asks the kernel about many ranges `(start, end)` at once, before the
/// [`writes`] of each: ranges close together are one asking, and `writes`
/// then answers from the journal until [`ask_ahead_done`]. The world's
/// submissions refresh thousands of host copies (6,664 askings a frame,
/// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are
/// left to `writes`.
pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) {
let mut pieces: Vec<(usize, usize)> = ranges
.iter()
.filter(|r| r.0 < r.1)
.map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE)))
.collect();
if pieces.len() < 2 {
return;
}
pieces.sort_unstable();
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let j = &mut *j;
// The submission's one asking stands ([`ask_once`]): what it does not
// hold is left to `writes`.
if j.kept {
return;
}
j.asked += 1;
j.ahead_asked = j.asked;
j.ahead.clear();
let mut i = 0;
while i < pieces.len() {
let first = pieces[i].0;
let mut last = pieces[i].1;
let mut k = i + 1;
while k < pieces.len()
&& pieces[k].0 <= last + AHEAD_GAP
&& last.max(pieces[k].1) - first <= AHEAD_MAX
{
last = last.max(pieces[k].1);
k += 1;
}
ask_run(j, &pieces[i..k]);
i = k;
}
}
/// Since the last frame line: the kernel askings that took a millisecond
/// or more, their microseconds, and the longest asking's. An asking walks
/// page tables, some ten microseconds for most ranges; in run 75 the 2,644
/// askings of a frame took 219 ms in the lines where the pass over the
/// heap's views ran long, 25-50 ms in the others. These numbers say
/// whether a few askings wait for something or all of them are slow.
#[cfg(feature = "diagnostics")]
static SLOW: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
#[cfg(feature = "diagnostics")]
fn slow(us: u64) {
use std::sync::atomic::Ordering::Relaxed;
if us >= 1000 {
SLOW[0].fetch_add(1, Relaxed);
SLOW[1].fetch_add(us, Relaxed);
}
SLOW[2].fetch_max(us, Relaxed);
}
/// [`SLOW`], taken.
#[cfg(feature = "diagnostics")]
pub(crate) fn slow_asks() -> [u64; 3] {
[0, 1, 2].map(|i| SLOW[i].swap(0, std::sync::atomic::Ordering::Relaxed))
}
/// The submission's refreshes are done: `writes` asks the kernel again.
pub(crate) fn ask_ahead_done() {
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
if !j.kept {
j.ahead.clear();
}
}
/// Whether a submission asks the kernel once, before its first refresh,
/// about every range its lists refresh (`VICTORY_ASK_ONCE=1`; off by
/// default).
///
/// A submission's refreshes are done in groups, between the title's own
/// buffer copies (each copy flushes the refreshes recorded before it), and
/// every group asked the kernel again: 2,644 askings a frame, 70 a
/// submission. With the switch the journal answers all of them from one
/// asking made when the submission starts.
///
/// What changes: memory the title's other threads write while the
/// submission is being prepared is seen by the next submission's asking,
/// not by this one's later groups. What this submission's lists read was
/// written before they were submitted, so before the asking. Our own
/// writes into title memory while preparing are told to the journal
/// ([`wrote`]) or end the asking ([`ask_once_end`]).
pub(crate) fn once() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
// On by default since run 81 (with card buffers: 375-450 ms a frame
// against 573-647, the picture unchanged over four minutes);
// `VICTORY_ASK_ONCE=0` asks per range, as before.
*ON.get_or_init(|| std::env::var_os("VICTORY_ASK_ONCE").is_none_or(|v| v != "0"))
}
/// With [`once`]: asks about `ranges` (everything a submission's lists
/// refresh) as [`ask_ahead`] does, and lets that asking stand until
/// [`ask_once_end`].
pub(crate) fn ask_once(ranges: &[(usize, usize)]) {
if !once() {
return;
}
ask_once_end();
ask_ahead(ranges);
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let j = &mut *j;
if j.ahead.is_empty() {
// `ask_ahead` asked nothing (fewer than two ranges).
j.asked += 1;
j.ahead_asked = j.asked;
}
// `ask_ahead` leaves a range that lies alone to `writes`, which asks
// once per flush: with one asking for the submission that was every
// such range asked again at each of its 70 flushes (run 76: 2,300
// askings a frame with the switch on, as without it). They are asked
// here, once; what is not write-watched stays with `writes`.
for &(start, end) in ranges {
if start >= end {
continue;
}
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
if !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) && ask_kernel(j, first, last) {
j.ahead.push((first, last));
}
}
j.kept = !j.ahead.is_empty();
}
/// The submission's one asking stands no longer: its refreshes are done,
/// or title memory was written in a way the journal was not told.
pub(crate) fn ask_once_end() {
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
if j.kept {
j.kept = false;
j.ahead.clear();
}
}
/// We wrote title memory `[at, at + len)` while a submission's one asking
/// stands (the title's buffer copies, done at submission): its pages count
/// as written after that asking, so the refreshes that follow copy them.
pub(crate) fn wrote(at: usize, len: usize) {
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
if !j.kept || len == 0 {
return;
}
j.asked += 1;
let now = j.asked;
for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) {
j.written.insert(page, now);
}
}
/// One kernel asking for `pieces` (page ranges in order); by halves if it
/// fails, as a run across two reservations or into memory that is not
/// write-watched does. A piece alone is left to [`writes`].
fn ask_run(j: &mut Journal, pieces: &[(usize, usize)]) {
if pieces.len() < 2 {
return;
}
let first = pieces[0].0;
let last = pieces.iter().map(|p| p.1).max().unwrap_or(first);
if ask_kernel(j, first, last) {
j.ahead.push((first, last));
return;
}
let (a, b) = pieces.split_at(pieces.len() / 2);
ask_run(j, a);
ask_run(j, b);
}
/// Asks the kernel for the written pages of pages `[first, last)` and notes
/// them in the journal under the ahead asking; false (and nothing changed)
/// if the range is not write-watched memory of one reservation.
fn ask_kernel(j: &mut Journal, first: usize, last: usize) -> bool {
use windows_sys::Win32::System::Memory::GetWriteWatch;
const WRITE_WATCH_FLAG_RESET: u32 = 1;
let mut count = (last - first) * PAGE / KERNEL_PAGE;
j.found.resize(count.max(j.found.len()), 0);
let mut granularity = 0;
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
// SAFETY: the answer buffer holds `count` entries.
let failed = unsafe {
GetWriteWatch(
WRITE_WATCH_FLAG_RESET,
(first * PAGE) as *const _,
(last - first) * PAGE,
j.found.as_mut_ptr().cast(),
&mut count,
&mut granularity,
)
} != 0;
if failed {
return false;
}
#[cfg(feature = "diagnostics")]
{
use crate::copystat::{C, add};
add(C::Watches, 1);
add(C::WatchUs, started.elapsed().as_micros() as u64);
slow(started.elapsed().as_micros() as u64);
}
let now = j.ahead_asked;
for k in 0..count {
let page = j.found[k] / PAGE;
j.written.insert(page, now);
}
true
}
/// What [`writes`] would say of `[start, end)` from the journal alone, if
/// the range lies in one asked ahead ([`ask_ahead`], [`ask_once`]): the
/// pages written since tracking began and the asking that last found each
/// written, with the number of the asking that stands (as [`writes`] gives
/// it). `None` if the kernel would have to be asked.
pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> {
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
let j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
j.ahead
.iter()
.any(|&(a, b)| a <= first && last <= b)
.then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect()))
}
/// The pages of `[start, end)` (whole pages) as last written, for pages
/// written since tracking began: `(page number, asking)` in page order, and
/// this asking's number, which is higher than any in the list but those the
@@ -54,6 +306,16 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let j = &mut *j;
// Asked ahead with the submission's other ranges: the journal has it.
if j.ahead.iter().any(|&(a, b)| a <= first && last <= b) {
return Some((
j.ahead_asked,
j.written
.range(first..last)
.map(|(&p, &w)| (p, w))
.collect(),
));
}
let mut count = (last - first) * PAGE / KERNEL_PAGE;
j.found.resize(count.max(j.found.len()), 0);
let mut granularity = 0;
@@ -75,7 +337,12 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
if !guarded {
return None;
}
guard(first * PAGE, last * PAGE)?
#[cfg(feature = "diagnostics")]
let guarding = std::time::Instant::now();
let written = guard(first * PAGE, last * PAGE);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::GuardUs, guarding.elapsed().as_micros() as u64);
written?
} else {
Vec::new()
};
@@ -84,6 +351,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
use crate::copystat::{C, add};
add(C::Watches, 1);
add(C::WatchUs, started.elapsed().as_micros() as u64);
slow(started.elapsed().as_micros() as u64);
}
j.asked += 1;
let now = j.asked;
@@ -108,11 +376,15 @@ struct Guards {
protected: BTreeSet<usize>,
/// Of those, the ones not written since a copy took them.
clean: BTreeSet<usize>,
/// Blocks already copied as zeros. While they remain wholly uncommitted,
/// the copy can skip hundreds of MB of failing kernel reads per world frame.
absent: BTreeSet<usize>,
}
static GUARDS: Mutex<Guards> = Mutex::new(Guards {
protected: BTreeSet::new(),
clean: BTreeSet::new(),
absent: BTreeSet::new(),
});
fn guards() -> std::sync::MutexGuard<'static, Guards> {
@@ -123,12 +395,20 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> {
/// they were last guarded (all of a block's pages), guarding them again
/// before the caller copies them. `None` if the memory is not a view.
fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery};
// SAFETY: plain data filled in by the query.
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let n = unsafe { VirtualQuery(start as *const _, &mut info, size_of_val(&info)) };
if n == 0 || info.Type != MEM_MAPPED {
// A range whose first block the guards hold already (read-only by our
// hand, or noted absent) is a view: no question to Windows. The
// question walks the page tables to the end of the pages that share the
// first one's state, and a guarded view is one long run of read-only
// pages: 0.6 ms for the title's 174 MB heap, 16 times a frame, and most
// of the 68 ms a frame of "guards" (run 58).
// `VICTORY_GUARD_ASK=1` asks every time, as before.
static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && {
let g = guards();
let first = start / BLOCK;
g.protected.contains(&first) || g.absent.contains(&first)
};
if !known && !is_view(start, end) {
return None;
}
install();
@@ -136,8 +416,35 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
let mut written = Vec::new();
let mut run: Option<usize> = None;
let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
// The range's clean blocks, in order: read off the set in one pass,
// not looked up one block at a time. A frame asks about some 10 GB of
// view memory, 150,000 blocks, nearly all clean: the lookups were most
// of the 60-90 ms a frame of "guards" (run 54). What the loop adds to
// the set meanwhile is the block it stands at or ones before it.
let clean: Vec<usize> = g.clean.range(first..last).copied().collect();
if clean.len() == last - first {
// Nothing written, mapped or new since the range was last taken.
return Some(written);
}
let mut next_clean = 0;
let mut uncommitted_until = first;
for block in first..=last {
let open = block < last && !g.clean.contains(&block);
while next_clean < clean.len() && clean[next_clean] < block {
next_clean += 1;
}
let is_clean = next_clean < clean.len() && clean[next_clean] == block;
let mut open = block < last && !is_clean;
if open && g.absent.contains(&block) {
// Ordinary commits need no runtime mapping notification. Reuse
// this asking's query for the following blocks in the same region.
if block >= uncommitted_until {
uncommitted_until = uncommitted_end(block);
}
open = block >= uncommitted_until;
if open {
g.absent.remove(&block);
}
}
if open {
written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE);
if g.protected.contains(&block) {
@@ -155,8 +462,53 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
Some(written)
}
/// Whether `[start, end)` is view memory. The title's views lie in
/// placeholders, mapped and unmapped block by block as it streams, so a
/// range can begin in a block that is not mapped right now: the first
/// pages of the range that are there decide. A range with nothing there
/// counts as a view (its blocks are noted absent, and looked at again when
/// the runtime maps them).
///
/// Looking at the first address only took such a range for "not a view":
/// its copy was marked not watched for good and copied whole at every
/// refresh, around its unmapped pages (run 54: 300 such ranges, 570 MB
/// copied a frame for them, 255 copies a frame reading around holes).
/// `VICTORY_GUARD_HOLES=0` looks at the first address only, as before.
fn is_view(start: usize, end: usize) -> bool {
use windows_sys::Win32::System::Memory::{
MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery,
};
static HOLES: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let holes = *HOLES.get_or_init(|| std::env::var_os("VICTORY_GUARD_HOLES").is_none_or(|v| v != "0"));
let mut at = start;
loop {
// SAFETY: plain data filled in by the query.
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
if n == 0 {
return false;
}
if info.Type == MEM_MAPPED {
return true;
}
// Committed memory that is no view (the title's heaps, ours), or
// the answer as it was before.
if info.State == MEM_COMMIT || !holes {
return false;
}
// A hole (a placeholder, or free): on to what follows it.
let next = (info.BaseAddress as usize).saturating_add(info.RegionSize);
if next <= at || next >= end {
return true;
}
at = next;
}
}
/// Makes blocks `[from, to)` read-only and notes them guarded and clean;
/// block by block if they span views, leaving out any that fail (unmapped).
/// block by block if they span views, leaving out any that fail, and
/// noting those not committed (unmapped) absent.
fn protect(g: &mut Guards, from: usize, to: usize) {
use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect};
let set = |from: usize, to: usize| {
@@ -182,10 +534,28 @@ fn protect(g: &mut Guards, from: usize, to: usize) {
for block in from..to {
if set(block, block + 1) {
note(g, block, block + 1);
} else if block < uncommitted_end(block) {
g.absent.insert(block);
}
}
}
/// The end (exclusive) of the whole uncommitted blocks starting at `block`.
fn uncommitted_end(block: usize) -> usize {
use windows_sys::Win32::System::Memory::{
MEM_FREE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, VirtualQuery,
};
// SAFETY: plain data filled in by the query.
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a valid out pointer of the right size.
let n = unsafe { VirtualQuery((block * BLOCK) as *const _, &mut info, size_of_val(&info)) };
if n != 0 && matches!(info.State, MEM_RESERVE | MEM_FREE) {
(info.BaseAddress as usize).saturating_add(info.RegionSize) / BLOCK
} else {
block
}
}
/// Gives write access back to the guarded blocks of `[start, end)` and
/// notes them written; true if any was guarded.
fn open(g: &mut Guards, start: usize, end: usize) -> bool {
@@ -212,17 +582,77 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool {
pub fn writing(at: usize, len: usize) {
// The length is the title's (`fread`'s size times count, saturated).
open(&mut guards(), at, at.saturating_add(len));
// A placed texture there changes with no descriptor written.
crate::descriptor::host::remapped(at, len);
}
/// Held shared by a read of title memory in place, and alone by the runtime
/// while it changes what title memory shows.
///
/// The runtime does not change a mapping in one step. To unmap one page of
/// a view it unmaps the whole view and maps what stays again
/// (`xmem.rs` `unmap`), and a view it maps is a reservation until the next
/// call commits it (`map`, then `commit`). For that moment pages the title
/// never gave up are "reserved, never committed", and a thread reading
/// them in place takes an access violation: run 71 in `Layout::detile`,
/// run 74 in the hash before it, both under `Staging::refresh_now`, which
/// had asked whether the texture was all mapped and been told yes. Asking
/// cannot help; not changing the mapping while such a read is under way
/// does.
static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(());
/// What the runtime holds while it changes what title memory shows
/// ([`title_memory_remapping`]).
pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>);
/// The runtime is about to map, unmap or move physical pages of title
/// memory: until what it returns is dropped, no read of title memory in
/// place is under way and none begins ([`title_memory_reading`]). Taken
/// around the whole change, the unmapping and the mapping again.
pub fn title_memory_remapping() -> Remapping {
Remapping(MAPPING.write().unwrap_or_else(|e| e.into_inner()))
}
/// What a read of title memory in place holds ([`title_memory_reading`]).
pub struct Reading(#[allow(dead_code)] std::sync::RwLockReadGuard<'static, ()>);
/// For reading title memory in place: until what it returns is dropped,
/// the runtime changes no mapping, so memory found mapped stays mapped.
/// Not to be taken twice by one thread, nor held across anything that
/// maps title memory.
pub fn title_memory_reading() -> Reading {
Reading(MAPPING.read().unwrap_or_else(|e| e.into_inner()))
}
/// [`title_memory_reading`] if it can be had at once: `None` while the
/// runtime changes a mapping (or waits to), for a caller that has another
/// way to read and would rather not wait.
pub fn title_memory_reading_now() -> Option<Reading> {
match MAPPING.try_read() {
Ok(guard) => Some(Reading(guard)),
Err(std::sync::TryLockError::Poisoned(e)) => Some(Reading(e.into_inner())),
Err(std::sync::TryLockError::WouldBlock) => None,
}
}
/// The runtime mapped or unmapped title memory `[at, at + len)`: what it
/// shows is new and read-write, so it is no longer guarded.
/// shows is new and read-write, so it is no longer guarded (nor known
/// unmapped).
pub fn title_memory_remapped(at: usize, len: usize) {
// A placed texture there arrives, goes or changes with no descriptor
// written.
crate::descriptor::host::remapped(at, len);
// The views the runtime told us of there are no longer what it shows.
crate::inplace::views_gone(at, len);
// And nothing stays in place over it.
crate::inplace::title_memory_freeing(at, len);
let mut g = guards();
let blocks: Vec<usize> = g
.protected
.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK))
.copied()
.collect();
let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK);
let absent: Vec<usize> = g.absent.range(range.clone()).copied().collect();
for block in absent {
g.absent.remove(&block);
}
let blocks: Vec<usize> = g.protected.range(range).copied().collect();
for block in blocks {
g.protected.remove(&block);
g.clean.remove(&block);
@@ -358,17 +788,264 @@ mod tests {
let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) };
file.read(into).is_ok_and(|n| n == 13)
};
assert!(!read(&mut file), "the kernel does not fault into our handler");
assert!(
!read(&mut file),
"the kernel does not fault into our handler"
);
writing(view + 100, 13);
assert!(read(&mut file));
// SAFETY: the bytes just read.
assert_eq!(unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, b"from the disk");
assert_eq!(guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()));
let landed = unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) };
assert_eq!(landed, b"from the disk");
assert_eq!(
guard(view, view + 2 * BLOCK),
Some((view / PAGE..view / PAGE + 1).collect())
);
// SAFETY: our view.
unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) };
unsafe {
UnmapViewOfFile(
windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS {
Value: view as *mut _,
},
)
};
title_memory_remapped(view, 2 * BLOCK);
}
#[test]
fn writes_in_partly_committed_view_blocks_are_reported() {
use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile,
SEC_RESERVE, UnmapViewOfFile,
};
const SIZE: usize = 3 * BLOCK;
struct View(MEMORY_MAPPED_VIEW_ADDRESS);
impl Drop for View {
fn drop(&mut self) {
title_memory_remapped(self.0.Value as usize, SIZE);
// SAFETY: our view is still mapped.
unsafe { UnmapViewOfFile(self.0) };
}
}
// SAFETY: a new reserved pagefile section. The view holds its own
// reference after we close the handle, including on assertion failure.
let view = unsafe {
let section = CreateFileMappingW(
INVALID_HANDLE_VALUE,
std::ptr::null(),
PAGE_READWRITE | SEC_RESERVE,
0,
SIZE as u32,
std::ptr::null(),
);
assert!(!section.is_null());
let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, SIZE);
CloseHandle(section);
assert!(!view.Value.is_null());
View(view)
};
let start = view.0.Value as usize;
let commit = |at: usize, len| {
// SAFETY: these pages belong to our reserved view.
let committed = unsafe { VirtualAlloc(at as _, len, MEM_COMMIT, PAGE_READWRITE) };
assert_eq!(committed as usize, at);
};
let early = start + BLOCK + 3 * KERNEL_PAGE;
let late = start + 2 * BLOCK + 3 * KERNEL_PAGE;
commit(start, BLOCK);
commit(early, KERNEL_PAGE);
let refresh = || guard(start, start + SIZE).unwrap();
assert_eq!(refresh(), [start / PAGE, early / PAGE, late / PAGE]);
// The last block is still entirely reserved.
assert!(!refresh().contains(&(late / PAGE)));
commit(late, KERNEL_PAGE); // Ordinary commit, without a runtime mapping notification.
for at in [early, late] {
assert!(writable(at));
// SAFETY: each address is inside its committed read-write page.
unsafe { (at as *mut u8).write_volatile(1) };
}
assert_eq!(refresh(), [early / PAGE, late / PAGE]);
}
/// A range of view memory whose first block is not mapped is a view
/// all the same: its blocks are reported once, then the ones written
/// or mapped since.
#[test]
fn a_range_that_begins_in_an_unmapped_block_is_guarded() {
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER,
MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2,
VirtualAlloc2,
};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
// SAFETY: a fresh placeholder of three blocks and a pagefile
// section of three; the middle block is mapped first.
let (p, section) = unsafe {
let p = VirtualAlloc2(
GetCurrentProcess(),
std::ptr::null(),
3 * BLOCK,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS,
std::ptr::null_mut(),
0,
) as usize;
assert_ne!(p, 0);
let section = CreateFileMappingW(
-1isize as _,
std::ptr::null(),
PAGE_READWRITE,
0,
(3 * BLOCK) as u32,
std::ptr::null(),
);
assert!(!section.is_null());
(p, section)
};
let map = |block: usize| {
// SAFETY: splits the placeholder at the block and maps the
// section's block there.
let view = unsafe {
VirtualFree(
(p + block * BLOCK) as *mut _,
BLOCK,
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
);
MapViewOfFile3(
section,
GetCurrentProcess(),
(p + block * BLOCK) as *const _,
(block * BLOCK) as u64,
BLOCK,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
std::ptr::null_mut(),
0,
)
};
assert_eq!(view.Value as usize, p + block * BLOCK);
view
};
let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE;
let all: Vec<usize> = (0..3).flat_map(pages).collect();
// Nothing mapped at all: a view with every block absent.
assert!(is_view(p, p + 3 * BLOCK));
let middle = map(1);
title_memory_remapped(p + BLOCK, BLOCK);
// The range begins in the placeholder, its middle block is a view.
assert!(is_view(p, p + 3 * BLOCK));
assert_eq!(guard(p, p + 3 * BLOCK), Some(all));
assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()), "nothing written since");
// SAFETY: inside the mapped middle block.
unsafe { ((p + BLOCK + 8) as *mut u8).write_volatile(1) };
assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect()));
let first = map(0);
title_memory_remapped(p, BLOCK);
assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(0).collect()));
assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()));
// Memory of ours that is no view stays none.
let mut local = [0u8; 16];
let at = local.as_mut_ptr() as usize;
assert!(!is_view(at, at + local.len()));
// SAFETY: our views and placeholder.
unsafe {
UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
UnmapViewOfFile2(GetCurrentProcess(), middle, MEM_PRESERVE_PLACEHOLDER);
for block in 0..3 {
VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
}
windows_sys::Win32::Foundation::CloseHandle(section);
}
title_memory_remapped(p, 3 * BLOCK);
}
/// Blocks of a placeholder between views are reported once, then not
/// again (they cannot be guarded) until the runtime maps them.
#[test]
fn unmapped_blocks_are_reported_once_until_mapped() {
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER,
MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2,
VirtualAlloc2,
};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
// SAFETY: a fresh placeholder of three blocks and a pagefile
// section of two; block 0 shows the section's first block, as the
// runtime maps physical pages.
let (p, section) = unsafe {
let p = VirtualAlloc2(
GetCurrentProcess(),
std::ptr::null(),
3 * BLOCK,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS,
std::ptr::null_mut(),
0,
) as usize;
assert_ne!(p, 0);
let section = CreateFileMappingW(
-1isize as _,
std::ptr::null(),
PAGE_READWRITE,
0,
(2 * BLOCK) as u32,
std::ptr::null(),
);
assert!(!section.is_null());
(p, section)
};
let map = |block: usize| {
// SAFETY: splits the placeholder at the block and maps the
// section's block there.
let view = unsafe {
VirtualFree(
(p + block * BLOCK) as *mut _,
BLOCK,
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
);
MapViewOfFile3(
section,
GetCurrentProcess(),
(p + block * BLOCK) as *const _,
(block * BLOCK) as u64,
BLOCK,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
std::ptr::null_mut(),
0,
)
};
assert_eq!(view.Value as usize, p + block * BLOCK);
view
};
let first = map(0);
let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE;
let all: Vec<usize> = (0..3).flat_map(pages).collect();
assert_eq!(guard(p, p + 3 * BLOCK), Some(all));
assert_eq!(
guard(p, p + 3 * BLOCK),
Some(Vec::new()),
"nothing written since"
);
let second = map(1);
title_memory_remapped(p + BLOCK, BLOCK);
assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect()));
assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()));
// SAFETY: our views and placeholder.
unsafe {
UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
UnmapViewOfFile2(GetCurrentProcess(), second, MEM_PRESERVE_PLACEHOLDER);
for block in 0..3 {
VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
}
windows_sys::Win32::Foundation::CloseHandle(section);
}
title_memory_remapped(p, 3 * 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.
@@ -379,3 +1056,53 @@ mod tests {
title_memory_remapped(top, usize::MAX);
}
}
#[cfg(test)]
mod mapping_tests {
use super::{title_memory_reading, title_memory_remapping};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, mpsc};
use std::time::Duration;
/// A change of mapping waits for a read in place that is under way, and
/// a read in place waits for a change of mapping.
#[test]
fn reads_in_place_and_remappings_wait_for_each_other() {
// A reader holds; the change does not begin until it lets go.
let changed = Arc::new(AtomicBool::new(false));
let reading = title_memory_reading();
let (began, wait) = mpsc::channel();
let change = {
let changed = changed.clone();
std::thread::spawn(move || {
began.send(()).unwrap();
let _changing = title_memory_remapping();
changed.store(true, Ordering::SeqCst);
})
};
wait.recv().unwrap();
std::thread::sleep(Duration::from_millis(100));
assert!(!changed.load(Ordering::SeqCst), "the mapping changed under a read in place");
drop(reading);
change.join().unwrap();
assert!(changed.load(Ordering::SeqCst));
// A change holds; the read does not begin until it is done.
let read = Arc::new(AtomicBool::new(false));
let changing = title_memory_remapping();
let (began, wait) = mpsc::channel();
let reader = {
let read = read.clone();
std::thread::spawn(move || {
began.send(()).unwrap();
let _reading = title_memory_reading();
read.store(true, Ordering::SeqCst);
})
};
wait.recv().unwrap();
std::thread::sleep(Duration::from_millis(100));
assert!(!read.load(Ordering::SeqCst), "a read in place began during a change of mapping");
drop(changing);
reader.join().unwrap();
assert!(read.load(Ordering::SeqCst));
}
}