A write through one view of a page is seen at its other views; page writes counted; levels on demand (off); warm-up; card memory numbers
Memory sync: - The guard over every view of a physical page (code by myokex, victory-amd c6dc4d8, after pull request #115 by Spexivus, its correction by joroyt and a part of VIctory #1122 by tightfall): the title shows one page at several addresses and a copy was guarded at one only. 0.8 to 1.0 million writes through another view in a five-minute run on the test machine. VICTORY_VIEW_GUARD=0 turns it off. - Kernel reads into title memory are read beside and copied in (Joshua Odom, 10ea38e). - Writes of the storage layer into physical pages are counted where the title has the pages mapped and can open the guards there (VICTORY_PAGE_WRITES, off: counted only). Failed page-destination reads are retried. Card memory: - Levels on demand, off unless VICTORY_LEVELS_ON_DEMAND=1: a texture the title fills takes card memory for the levels the title holds; held levels get memory only while the card has room and are asked for again. Its test runs on the software adapter; not run on a card yet. - Refused texture slots are held back so a pass reaches the slots behind them; room can be kept for card copies of title buffers (off). Tools: translate --warm all; the shader cache is keyed on the translator's source; counters for copy-back races, page writes and the copies the texture sweep never lets go; a walls trace. Game runs of these changes on an RTX 4070: five five-minute runs without a device loss or a failed request. This merged tree was built; its test suites were run on the tree the changes come from (gpu 129, hle 97). Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
1 parent
310c6eb6c1
commit
8dd30ab472
25 files changed
+4218
-240
No files matched your search
@@ -20,6 +20,12 @@ developer or publisher.
|
||||
- **[XCL](https://github.com/ivall/xcl)** by ivall and its contributors
|
||||
(GPL-2.0-only) was used as a reference for how the same title behaves under
|
||||
another layer. Fixes inspired by it were written anew in VIctory's code.
|
||||
- The guard over every view of a memory page is code by **myokex**
|
||||
([victory-amd](https://github.com/myokex/victory-amd), commit `c6dc4d8`), which
|
||||
adapts pull request #115 here by Spexivus, its correction by joroyt and a part of
|
||||
VIctory #1122 by tightfall. The read-beside fix for kernel reads into title
|
||||
memory is by **Joshua Odom** (commit `10ea38e` of the same fork family). Both
|
||||
are carried here unchanged apart from one merge conflict.
|
||||
- This fork's changes were developed with [Claude Code](https://claude.com/claude-code).
|
||||
|
||||
## Status of this fork (2026-11-25)
|
||||
@@ -38,6 +44,48 @@ Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB,
|
||||
| Frame rate in the world | 2-4 fps: 420-450 ms per frame by default, 240-350 ms with the newer switches (`VICTORY_RELAY=2`, or `VICTORY_LATE_WAIT=3 VICTORY_WIDE_BACK=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_CARD_BUFFERS_MB=1024`); it started at 3-6 seconds per frame |
|
||||
| Stability | no driver hang or device loss in normal runs (a hang introduced by the wave64 update was found and fixed: its barrier form for 64-lane programs is now off unless `VICTORY_WAVE_WIDE=1`) |
|
||||
|
||||
### Newest (2026-11-25, later the same day)
|
||||
|
||||
Memory sync between the title's memory and the copies on the card:
|
||||
- **A write through one view of a physical page is seen by the copies taken
|
||||
through its other views** (`VICTORY_VIEW_GUARD=0` turns it off). The title
|
||||
shows one page at several addresses and a copy was guarded at one of them
|
||||
only. Measured on the test machine: 0.8 to 1.0 million such writes in a
|
||||
five-minute run, every one of which used to leave a copy stale. Since it
|
||||
went in, the first room had its walls in the later frames of 4 runs out of
|
||||
4 (2 of 5 before); the room's very first shot still comes up without walls
|
||||
in some runs.
|
||||
- Kernel reads into title memory are read beside and copied in, so a block
|
||||
guarded again in between no longer fails the read.
|
||||
- Writes of the storage layer into physical pages are counted where the title
|
||||
has those pages mapped (10,000 to 50,000 guarded blocks of copies lay under
|
||||
them in every run) and can open the guards there:
|
||||
`VICTORY_PAGE_WRITES=guards` (off by default; `1`, `slots`, `all` do more).
|
||||
- Failed page-destination reads are retried (`VICTORY_DSTORAGE_RETRIES=0` = as before).
|
||||
|
||||
Card memory (the test card is full from the first frame of the world: 85 to
|
||||
99 % of its budget for a whole run, about 26,000 texture copies let go and
|
||||
3,400 made again in five minutes, 2.8 GB of render targets that are all in
|
||||
use):
|
||||
- Levels on demand, **off by default** (`VICTORY_LEVELS_ON_DEMAND=1`): a
|
||||
texture the title fills takes card memory only for the levels the title
|
||||
holds (2.2 to 3.0 GB of the copies were levels it does not hold). Its test
|
||||
runs on the software adapter; it has not run on a card yet.
|
||||
- Refused texture slots are held back for a few seconds so that a pass
|
||||
reaches the slots behind them (`VICTORY_FULL_CARD_PASS=0` = as before);
|
||||
room can be kept for the card copies of title buffers
|
||||
(`VICTORY_CARD_ROOM_FOR_BUFFERS=1`, off).
|
||||
|
||||
Tools and diagnostics:
|
||||
- `victory translate <shader file> --warm all --jobs N` translates every
|
||||
shader ahead of a run, on the processor only (about 4.5 to 6.5 minutes
|
||||
here); the shader cache is keyed on the translator's source, so a new
|
||||
build that does not touch the translator starts warm.
|
||||
- Counters, all off or diagnostics-only: `VICTORY_MERGE_RACE=1` (title bytes
|
||||
a copy-back is about to put back to older values: none found in 138,000
|
||||
copy-backs), `VICTORY_WALLS_TRACE`, `VICTORY_CARD_ACCOUNTING`, and a census
|
||||
of the copies the texture sweep never lets go.
|
||||
|
||||
### What this fork changed (summary)
|
||||
|
||||
Rendering:
|
||||
|
||||
@@ -84,6 +84,13 @@ enum Command {
|
||||
/// Worker threads (default: every logical core).
|
||||
#[arg(long)]
|
||||
jobs: Option<usize>,
|
||||
/// Warm the run's shader cache: a file of shader hashes (the 16
|
||||
/// hex digits a run's log names a shader by, anywhere in a line);
|
||||
/// the containers with those hashes are translated into the
|
||||
/// cache and nothing else is done. Set `VICTORY_HOST_WAVE` and
|
||||
/// `VICTORY_VIEW_LIMIT` to what the run's log says of the host.
|
||||
#[arg(long)]
|
||||
warm: Option<PathBuf>,
|
||||
},
|
||||
/// Prepare, map and bind a title executable; with --execute, run it.
|
||||
Run {
|
||||
@@ -152,6 +159,7 @@ fn main() -> Result<()> {
|
||||
pipelines,
|
||||
list,
|
||||
jobs,
|
||||
warm,
|
||||
} => {
|
||||
// `VICTORY_VIEW_LIMIT=<null slot>`: translate as on a host whose view heap is capped
|
||||
if let Some(n) = std::env::var("VICTORY_VIEW_LIMIT").ok().and_then(|v| v.parse().ok()) {
|
||||
@@ -161,6 +169,9 @@ fn main() -> Result<()> {
|
||||
if let Some(n) = std::env::var("VICTORY_HOST_WAVE").ok().and_then(|v| v.parse().ok()) {
|
||||
victory_shader::emit::set_host_max_wave(n);
|
||||
}
|
||||
if let Some(file) = warm {
|
||||
return translate::warm(paths, &file, jobs);
|
||||
}
|
||||
translate::run(paths, validate, pipelines, list, jobs)
|
||||
}
|
||||
Command::Run {
|
||||
|
||||
@@ -152,6 +152,87 @@ struct Checks {
|
||||
host: Option<(Host, emit::HostShader)>,
|
||||
}
|
||||
|
||||
/// `translate --warm <file>`: the containers whose hash the file names are
|
||||
/// translated into the run's shader cache, on `jobs` threads; nothing is
|
||||
/// made on the GPU. A run of the title then finds them there instead of
|
||||
/// translating each at its first use.
|
||||
pub fn warm(paths: Vec<PathBuf>, file: &Path, jobs: Option<usize>) -> Result<()> {
|
||||
// `--warm all`: every container found, whatever its hash.
|
||||
let all = file.as_os_str() == "all";
|
||||
let mut wanted: HashSet<String> = HashSet::new();
|
||||
if !all {
|
||||
let text = std::fs::read_to_string(file)?;
|
||||
for line in text.lines() {
|
||||
for word in line.split(|c: char| !c.is_ascii_hexdigit()) {
|
||||
if word.len() == 16 {
|
||||
wanted.insert(word.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
}
|
||||
anyhow::ensure!(!wanted.is_empty(), "no 16-digit shader hash in {}", file.display());
|
||||
}
|
||||
// `VICTORY_WARM_SECONDS=<n>`: stop taking new shaders after n seconds
|
||||
// (what is done stays in the cache; the next warm-up goes on from there).
|
||||
let limit = std::env::var("VICTORY_WARM_SECONDS").ok().and_then(|v| v.trim().parse::<u64>().ok());
|
||||
let cfg = victory_core::Config::load()?;
|
||||
victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
|
||||
let paths = crate::default_paths(paths)?;
|
||||
let threads = jobs.unwrap_or(4).max(1);
|
||||
let began = std::time::Instant::now();
|
||||
let done = Mutex::new(HashSet::new());
|
||||
let counts = [const { AtomicUsize::new(0) }; 5];
|
||||
for root in &paths {
|
||||
for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) {
|
||||
if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE {
|
||||
continue;
|
||||
}
|
||||
let Ok(data) = std::fs::read(entry.path()) else {
|
||||
continue;
|
||||
};
|
||||
let jobs = sources(&data);
|
||||
let next = AtomicUsize::new(0);
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..threads.min(jobs.len()) {
|
||||
s.spawn(|| {
|
||||
while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) {
|
||||
let Some(bytes) = job.bytes() else {
|
||||
continue;
|
||||
};
|
||||
let hash = blake3::hash(&bytes).to_hex()[..16].to_owned();
|
||||
if limit.is_some_and(|n| began.elapsed().as_secs() >= n) {
|
||||
counts[3].fetch_add(1, Ordering::Relaxed);
|
||||
break;
|
||||
}
|
||||
if (!all && !wanted.contains(&hash)) || !lock(&done).insert(hash) {
|
||||
continue;
|
||||
}
|
||||
let n = counts[4].fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if n.is_multiple_of(1000) {
|
||||
println!("warm-up {n} shaders so far, {:.0} s", began.elapsed().as_secs_f64());
|
||||
}
|
||||
let which = match victory_hle::modules::d3d12x::warm_shader(&bytes) {
|
||||
Ok(true) => 0,
|
||||
Ok(false) => 1,
|
||||
Err(_) => 2,
|
||||
};
|
||||
counts[which].fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
let [translated, there, failed] = [0, 1, 2].map(|i| counts[i].load(Ordering::Relaxed));
|
||||
let asked = if all { "all".to_owned() } else { wanted.len().to_string() };
|
||||
let stopped = if counts[3].load(Ordering::Relaxed) > 0 { " (stopped at the time limit)" } else { "" };
|
||||
println!(
|
||||
"warm-up {asked} hashes asked, {} found: {translated} translated now, {there} in the cache already, {failed} do not translate; {:.1} s on {threads} threads{stopped}",
|
||||
translated + there + failed,
|
||||
began.elapsed().as_secs_f64()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn run(
|
||||
paths: Vec<PathBuf>,
|
||||
validate: bool,
|
||||
|
||||
@@ -594,9 +594,7 @@ impl Layout {
|
||||
row_pitch: usize,
|
||||
depth_pitch: usize,
|
||||
) -> Result<(), Error> {
|
||||
self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| {
|
||||
linear[l..][..len].copy_from_slice(&tiled[t..][..len]);
|
||||
})
|
||||
self.walk::<true>(tiled, linear, mip, slice, row_pitch, depth_pitch)
|
||||
}
|
||||
|
||||
/// The reverse of [`Layout::detile`]: linear rows into tiled memory.
|
||||
@@ -609,22 +607,19 @@ impl Layout {
|
||||
row_pitch: usize,
|
||||
depth_pitch: usize,
|
||||
) -> Result<(), Error> {
|
||||
self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| {
|
||||
tiled[t..][..len].copy_from_slice(&linear[l..][..len]);
|
||||
})
|
||||
self.walk::<false>(linear, tiled, mip, slice, row_pitch, depth_pitch)
|
||||
}
|
||||
|
||||
/// Visits contiguous runs as (tiled byte offset, linear byte offset, length).
|
||||
/// Copies contiguous runs in one direction between the two layouts.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn walk(
|
||||
fn walk<const DETILE: bool>(
|
||||
&self,
|
||||
tiled_len: usize,
|
||||
src: &[u8],
|
||||
dst: &mut [u8],
|
||||
mip: u32,
|
||||
slice: u32,
|
||||
linear_len: usize,
|
||||
row_pitch: usize,
|
||||
depth_pitch: usize,
|
||||
mut copy: impl FnMut(usize, usize, usize),
|
||||
) -> Result<(), Error> {
|
||||
let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?;
|
||||
let depth = m.depth;
|
||||
@@ -650,6 +645,11 @@ impl Layout {
|
||||
.and_then(|(depth_offset, row_offset)| depth_offset.checked_add(row_offset))
|
||||
.and_then(|offset| offset.checked_add(bytes))
|
||||
.ok_or(Error::TooSmall)?;
|
||||
let (tiled_len, linear_len) = if DETILE {
|
||||
(src.len(), dst.len())
|
||||
} else {
|
||||
(dst.len(), src.len())
|
||||
};
|
||||
if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes {
|
||||
return Err(Error::TooSmall);
|
||||
}
|
||||
@@ -672,12 +672,12 @@ impl Layout {
|
||||
runs.push((first_tiled, first_linear, bytes - first_linear));
|
||||
}
|
||||
// A mip can end partway through the last run. Check the other runs
|
||||
// once so each row can copy them with a compile-time length.
|
||||
// once so each row can copy them as fixed-size chunks.
|
||||
let (body, last) = runs.split_at(runs.len().saturating_sub(1));
|
||||
let run_len = body
|
||||
.first()
|
||||
.map(|run| run.2)
|
||||
.filter(|&len| body.iter().all(|run| run.2 == len));
|
||||
let chunk_size = body.first().map(|run| run.2).filter(|&size| {
|
||||
body.iter()
|
||||
.all(|&(offset, _, len)| len == size && offset.is_multiple_of(size))
|
||||
});
|
||||
for z in 0..depth {
|
||||
let (s, inner) = self.split(first + z);
|
||||
let base = u64::from(s) * self.slice_size + m.offset;
|
||||
@@ -685,16 +685,22 @@ impl Layout {
|
||||
let linear_row = z as usize * depth_pitch + y as usize * row_pitch;
|
||||
if linear {
|
||||
let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64;
|
||||
copy(tiled_row as usize, linear_row, bytes);
|
||||
copy_run::<DETILE>(src, dst, tiled_row as usize, linear_row, bytes);
|
||||
} else {
|
||||
let tiled_row = (base + self.row(m, y, inner)) as usize;
|
||||
match run_len {
|
||||
Some(8) => copy_runs::<8>(body, tiled_row, linear_row, &mut copy),
|
||||
Some(16) => copy_runs::<16>(body, tiled_row, linear_row, &mut copy),
|
||||
Some(32) => copy_runs::<32>(body, tiled_row, linear_row, &mut copy),
|
||||
_ => copy_runs::<0>(body, tiled_row, linear_row, &mut copy),
|
||||
match chunk_size {
|
||||
Some(8) if tiled_row.is_multiple_of(8) => {
|
||||
copy_runs::<8, DETILE>(src, dst, body, tiled_row, linear_row)
|
||||
}
|
||||
Some(16) if tiled_row.is_multiple_of(16) => {
|
||||
copy_runs::<16, DETILE>(src, dst, body, tiled_row, linear_row)
|
||||
}
|
||||
Some(32) if tiled_row.is_multiple_of(32) => {
|
||||
copy_runs::<32, DETILE>(src, dst, body, tiled_row, linear_row)
|
||||
}
|
||||
_ => copy_runs::<0, DETILE>(src, dst, body, tiled_row, linear_row),
|
||||
}
|
||||
copy_runs::<0>(last, tiled_row, linear_row, &mut copy);
|
||||
copy_runs::<0, DETILE>(src, dst, last, tiled_row, linear_row);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -702,16 +708,47 @@ impl Layout {
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy micro-tile runs inline at a known width, or use each run's length for N = 0.
|
||||
fn copy_runs<const N: usize>(
|
||||
fn copy_run<const DETILE: bool>(
|
||||
src: &[u8],
|
||||
dst: &mut [u8],
|
||||
tiled: usize,
|
||||
linear: usize,
|
||||
len: usize,
|
||||
) {
|
||||
let (from, to) = if DETILE {
|
||||
(tiled, linear)
|
||||
} else {
|
||||
(linear, tiled)
|
||||
};
|
||||
dst[to..][..len].copy_from_slice(&src[from..][..len]);
|
||||
}
|
||||
|
||||
/// A row of equal runs is contiguous in linear memory. Treat it as a
|
||||
/// slice of arrays so only the tiled chunk needs a bounds check per copy.
|
||||
/// Use the byte ranges for irregular runs and the last run of each row.
|
||||
fn copy_runs<const N: usize, const DETILE: bool>(
|
||||
src: &[u8],
|
||||
dst: &mut [u8],
|
||||
runs: &[(usize, usize, usize)],
|
||||
tiled_row: usize,
|
||||
linear_row: usize,
|
||||
copy: &mut impl FnMut(usize, usize, usize),
|
||||
) {
|
||||
for &(tiled, linear, len) in runs {
|
||||
let len = if N == 0 { len } else { N };
|
||||
copy(tiled_row + tiled, linear_row + linear, len);
|
||||
if N == 0 {
|
||||
for &(tiled, linear, len) in runs {
|
||||
copy_run::<DETILE>(src, dst, tiled_row + tiled, linear_row + linear, len);
|
||||
}
|
||||
} else if DETILE {
|
||||
let tiled = src.as_chunks::<N>().0;
|
||||
let linear = dst[linear_row..][..runs.len() * N].as_chunks_mut::<N>().0;
|
||||
for (out, &(offset, ..)) in linear.iter_mut().zip(runs) {
|
||||
*out = tiled[(tiled_row + offset) / N];
|
||||
}
|
||||
} else {
|
||||
let tiled = dst.as_chunks_mut::<N>().0;
|
||||
let linear = src[linear_row..][..runs.len() * N].as_chunks::<N>().0;
|
||||
for (input, &(offset, ..)) in linear.iter().zip(runs) {
|
||||
tiled[(tiled_row + offset) / N] = *input;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -968,6 +1005,58 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiled_chunks_match_element_offsets_with_odd_row_pitches() {
|
||||
for swizzle in [
|
||||
Swizzle::SW_256B_S,
|
||||
Swizzle::SW_256B_D,
|
||||
Swizzle::SW_4KB_S,
|
||||
Swizzle::SW_4KB_D,
|
||||
Swizzle::SW_64KB_S,
|
||||
Swizzle::SW_64KB_D,
|
||||
] {
|
||||
for n in [1, 2, 4, 8, 16] {
|
||||
let l = Layout::new(&Desc {
|
||||
depth: 2,
|
||||
..desc(73, 39, 7, n, swizzle)
|
||||
})
|
||||
.unwrap();
|
||||
let n = n as usize;
|
||||
let tiled: Vec<_> = (0..l.size)
|
||||
.map(|i| (i.wrapping_mul(0x9e37_79b9) >> 24) as u8)
|
||||
.collect();
|
||||
let mut retiled = vec![0xbb; tiled.len()];
|
||||
let mut expected_tiled = retiled.clone();
|
||||
for slice in 0..l.slices {
|
||||
for (mip, m) in l.mips.iter().enumerate() {
|
||||
let mip = mip as u32;
|
||||
let bytes = m.width as usize * n;
|
||||
let pitch = bytes + 3;
|
||||
// Keep padding between rows, with exactly the active
|
||||
// bytes in the last row.
|
||||
let len = (m.height as usize - 1) * pitch + bytes;
|
||||
let mut linear = vec![0xcc; len];
|
||||
let mut expected = linear.clone();
|
||||
for y in 0..m.height {
|
||||
for x in 0..m.width {
|
||||
let src = l.offset(mip, x, y, slice).unwrap() as usize;
|
||||
let dst = y as usize * pitch + x as usize * n;
|
||||
expected[dst..][..n].copy_from_slice(&tiled[src..][..n]);
|
||||
expected_tiled[src..][..n].copy_from_slice(&tiled[src..][..n]);
|
||||
}
|
||||
}
|
||||
l.detile(&tiled, mip, slice, &mut linear, pitch, len)
|
||||
.unwrap();
|
||||
assert_eq!(linear, expected, "{swizzle:?} {n} mip {mip} slice {slice}");
|
||||
l.tile(&mut retiled, mip, slice, &expected, pitch, len)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
assert_eq!(retiled, expected_tiled, "{swizzle:?} {n}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to
|
||||
/// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12,
|
||||
/// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first.
|
||||
|
||||
@@ -743,6 +743,22 @@ fn log_memory() {
|
||||
mb(card[0]),
|
||||
mb(card[3]),
|
||||
);
|
||||
let targets = crate::resource::targets_census();
|
||||
tracing::info!(
|
||||
"host copies the sweep never lets go: {} the host renders to or writes {:.0} MB ({} of them placed {:.0} MB); of them {} have title memory that is not mapped now {:.0} MB, {} were not used for 30 s and are held by no list and no slot {:.0} MB, {} are both {:.0} MB; and {} copies of textures the title fills that the host copied into {:.0} MB",
|
||||
targets[0],
|
||||
mb(targets[1]),
|
||||
targets[10],
|
||||
mb(targets[11]),
|
||||
targets[2],
|
||||
mb(targets[3]),
|
||||
targets[4],
|
||||
mb(targets[5]),
|
||||
targets[6],
|
||||
mb(targets[7]),
|
||||
targets[8],
|
||||
mb(targets[9]),
|
||||
);
|
||||
tracing::info!(
|
||||
"memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \
|
||||
{:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \
|
||||
@@ -1121,6 +1137,12 @@ pub(crate) fn log(frames: f64) {
|
||||
c[C::GpuWritesLeftOut as usize],
|
||||
mb(c[C::GpuWritesLeftOutBytes as usize]),
|
||||
);
|
||||
let [together, written, mapped] =
|
||||
[0, 1, 2].map(|n| crate::watch::ALIASES[n].load(std::sync::atomic::Ordering::Relaxed));
|
||||
tracing::info!(
|
||||
"guards over several views of a page, since the start: {together} blocks guarded with their other views, \
|
||||
{written} views opened by a write through another, {mapped} ranges opened because a view of them was mapped"
|
||||
);
|
||||
// Where the wall clock of a frame goes: the phases of a frame, the
|
||||
// processor time of the whole process, and what each submitting and
|
||||
// recording thread did.
|
||||
|
||||
@@ -353,7 +353,11 @@ struct Views {
|
||||
shape_index: std::collections::BTreeMap<Shape, u32>,
|
||||
}
|
||||
|
||||
static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views {
|
||||
/// Read far more often than written: every slot a draw reads through a
|
||||
/// table is looked up here, on several recording threads at once in the
|
||||
/// world. Readers share it; only a view not seen before (a new table entry
|
||||
/// or shape) and a released resource take it alone.
|
||||
static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views {
|
||||
list: Vec::new(),
|
||||
index: std::collections::BTreeMap::new(),
|
||||
by_resource: std::collections::BTreeMap::new(),
|
||||
@@ -480,6 +484,12 @@ impl Views {
|
||||
Some(View::Placed(unordered, resource, desc))
|
||||
}
|
||||
|
||||
/// The record words of `view` as a table entry, if it has one.
|
||||
fn entry_of(&self, view: &View) -> Option<[u32; 2]> {
|
||||
let &i = self.index.get(view)?;
|
||||
Some([i, self.list[i as usize].1])
|
||||
}
|
||||
|
||||
/// The record words of `view` as a table entry: its entry (a new or a
|
||||
/// freed one if the view is not there yet) and that entry's generation.
|
||||
fn entry(&mut self, view: View) -> [u32; 2] {
|
||||
@@ -522,8 +532,10 @@ fn words_for(view: View) -> [u32; 2] {
|
||||
View::Placed(unordered, resource, desc) => {
|
||||
let (shape, address) = shape_of(*unordered, resource, desc);
|
||||
if address >> PLACED_ADDRESS_BITS == 0 {
|
||||
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(shape) = views.shape(shape) {
|
||||
// Nearly every placed view has a shape seen before.
|
||||
let known = views_read().shape_index.get(&shape).copied();
|
||||
let shape = known.or_else(|| views_write().shape(shape));
|
||||
if let Some(shape) = shape {
|
||||
NAMED_WHOLE[1].fetch_add(1, Relaxed);
|
||||
return placed_words(shape, address);
|
||||
}
|
||||
@@ -532,7 +544,19 @@ fn words_for(view: View) -> [u32; 2] {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
VIEWS.lock().unwrap_or_else(|e| e.into_inner()).entry(view)
|
||||
// A view written before keeps its entry and generation.
|
||||
if let Some(words) = views_read().entry_of(&view) {
|
||||
return words;
|
||||
}
|
||||
views_write().entry(view)
|
||||
}
|
||||
|
||||
fn views_read() -> std::sync::RwLockReadGuard<'static, Views> {
|
||||
VIEWS.read().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> {
|
||||
VIEWS.write().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// For the memory line: the distinct views kept ([`Views`]), those of them
|
||||
@@ -546,7 +570,7 @@ fn words_for(view: View) -> [u32; 2] {
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
pub(crate) fn views_kept() -> [u64; 8] {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let views = views_read();
|
||||
let each = size_of::<(View, u32)>() as u64;
|
||||
let shape = size_of::<Shape>() as u64;
|
||||
let (mut constants, mut placed) = (0, 0);
|
||||
@@ -697,7 +721,7 @@ pub(crate) fn forget(resource: usize) {
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.remove(&resource);
|
||||
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut views = views_write();
|
||||
let Some(entries) = views.by_resource.remove(&resource) else {
|
||||
return;
|
||||
};
|
||||
@@ -722,12 +746,12 @@ pub(crate) fn forget(resource: usize) {
|
||||
fn view_at(i: u32, generation: u32) -> Option<View> {
|
||||
match generation >> KIND_SHIFT {
|
||||
0 => {
|
||||
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let views = views_read();
|
||||
let (view, current) = views.list.get(i as usize)?;
|
||||
(*current == generation).then(|| view.clone())
|
||||
}
|
||||
CONSTANT => Some(constant_of(i, generation)),
|
||||
PLACED => VIEWS.lock().unwrap_or_else(|e| e.into_inner()).placed_of(i, generation),
|
||||
PLACED => views_read().placed_of(i, generation),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -1104,8 +1128,8 @@ mod tests {
|
||||
View::Placed(_, r, _) => *r == resource,
|
||||
_ => false,
|
||||
};
|
||||
let entries = || VIEWS.lock().unwrap().list.iter().filter(|(v, _)| mine(v)).count();
|
||||
let shapes = || VIEWS.lock().unwrap().shapes.iter().filter(|s| s.1 == resource).count();
|
||||
let entries = || VIEWS.read().unwrap().list.iter().filter(|(v, _)| mine(v)).count();
|
||||
let shapes = || VIEWS.read().unwrap().shapes.iter().filter(|s| s.1 == resource).count();
|
||||
for n in 0..20_000u64 {
|
||||
let address = 0x6_0000_0000 + n * 0x100;
|
||||
create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at);
|
||||
|
||||
@@ -85,7 +85,66 @@ pub(crate) struct HostHeap {
|
||||
/// by slot and by address ([`Spans`]): which slots a newer view of
|
||||
/// other memory there makes stale, and which to look at again when the
|
||||
/// runtime maps, unmaps or writes memory ([`remapped`]).
|
||||
placed: Mutex<Spans>,
|
||||
placed: std::sync::Arc<Mutex<Spans>>,
|
||||
}
|
||||
|
||||
/// The spans of every view heap made ([`HostHeap::placed`]), for the
|
||||
/// texture code, which has no heap at hand ([`next_start`],
|
||||
/// [`first_viewed`]).
|
||||
static PLACED_SPANS: Mutex<Vec<std::sync::Weak<Mutex<Spans>>>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Where the next texture placed inside `[start, end)` starts, past the
|
||||
/// first bytes of the one at `start` ([`HEAD`]): what is there of the
|
||||
/// texture at `start` ends there, whatever its full size. `None`: no view
|
||||
/// in a slot shaders pick by index describes memory in that range.
|
||||
pub(crate) fn next_start(start: u64, end: u64) -> Option<u64> {
|
||||
let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
heaps
|
||||
.iter()
|
||||
.filter_map(std::sync::Weak::upgrade)
|
||||
.filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).next_start(start, end))
|
||||
.min()
|
||||
}
|
||||
|
||||
/// The lowest level that a view of the placed texture at `start` shows,
|
||||
/// over the slots shaders pick by index that hold one now. The title
|
||||
/// views a texture from the first level it holds. `None`: no such slot.
|
||||
pub(crate) fn first_viewed(start: u64) -> Option<u32> {
|
||||
let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
heaps
|
||||
.iter()
|
||||
.filter_map(std::sync::Weak::upgrade)
|
||||
.filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).first_viewed(start))
|
||||
.min()
|
||||
}
|
||||
|
||||
/// Levels on demand (`crate::tiles`): where the placed textures start
|
||||
/// whose first level with memory changed since a texture pass last took
|
||||
/// them ([`HostHeap::texture_views_remade`]).
|
||||
static RESHOWN: Mutex<Vec<u64>> = Mutex::new(Vec::new());
|
||||
|
||||
/// The first level with memory of the placed texture at `start` changed:
|
||||
/// its slots are made again at the next texture pass.
|
||||
pub(crate) fn levels_changed(start: u64) {
|
||||
RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).push(start);
|
||||
}
|
||||
|
||||
/// Levels on demand (`crate::tiles`): where the placed textures start
|
||||
/// whose last upload left a held level without tiles (the card had no
|
||||
/// room, or no heap could be had), and when (`crate::host::moment`). A
|
||||
/// texture pass makes their slots due again once the card has room
|
||||
/// ([`HostHeap::texture_slots_waiting`]).
|
||||
static WAITING: Mutex<std::collections::BTreeMap<u64, u64>> = Mutex::new(std::collections::BTreeMap::new());
|
||||
|
||||
/// The last upload of the placed texture at `start` left a held level
|
||||
/// without tiles. A texture picked by index is uploaded once and then
|
||||
/// only when its memory is found changed, and its staging buffer goes
|
||||
/// with the upload: without this the level stayed empty (the texture
|
||||
/// blurred, or black if no level had tiles) for as long as the title left
|
||||
/// its memory alone, where a texture refused for want of room is tried
|
||||
/// again.
|
||||
pub(crate) fn levels_waiting(start: u64) {
|
||||
WAITING.lock().unwrap_or_else(|e| e.into_inner()).insert(start, crate::host::moment());
|
||||
}
|
||||
|
||||
/// Title memory by the placed texture views that describe it: per span of
|
||||
@@ -110,6 +169,8 @@ pub(crate) struct Spans {
|
||||
rule: Rule,
|
||||
by_start: std::collections::BTreeMap<u64, (u64, std::collections::BTreeSet<u32>)>,
|
||||
by_slot: std::collections::HashMap<u32, u64>,
|
||||
/// The level each slot's view starts at ([`Spans::shows`]).
|
||||
first: std::collections::HashMap<u32, u32>,
|
||||
/// The bytes a placed texture takes, by resource description: worked
|
||||
/// out once for each (a title writes the views of a few thousand
|
||||
/// descriptions, thousands of times a frame).
|
||||
@@ -227,8 +288,30 @@ impl Spans {
|
||||
stale
|
||||
}
|
||||
|
||||
/// The view in slot `index` starts at level `first` of its texture.
|
||||
fn shows(&mut self, index: u32, first: u32) {
|
||||
self.first.insert(index, first);
|
||||
}
|
||||
|
||||
/// The lowest level a view of the texture at `start` starts at.
|
||||
fn first_viewed(&self, start: u64) -> Option<u32> {
|
||||
self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).min().copied()
|
||||
}
|
||||
|
||||
/// The first span that starts inside `[start, end)` past the first
|
||||
/// [`HEAD`] bytes of it.
|
||||
fn next_start(&self, start: u64, end: u64) -> Option<u64> {
|
||||
self.by_start.range(start.saturating_add(HEAD)..end).next().map(|(at, _)| *at)
|
||||
}
|
||||
|
||||
/// The slots that hold a view of the texture at `start`.
|
||||
fn slots_at(&self, start: u64) -> Vec<u32> {
|
||||
self.by_start.get(&start).map(|span| span.1.iter().copied().collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Slot `index` holds no placed texture view any more.
|
||||
fn forget(&mut self, index: u32) {
|
||||
self.first.remove(&index);
|
||||
let Some(start) = self.by_slot.remove(&index) else {
|
||||
return;
|
||||
};
|
||||
@@ -248,6 +331,76 @@ impl Spans {
|
||||
.flat_map(|span| span.1.iter().copied())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The slots of the textures that hold bytes of `[start, end)`, for a
|
||||
/// write there: as [`Spans::slots_in`], but when a texture starts at
|
||||
/// `start` itself the one before it is left out (it ends where that
|
||||
/// one starts, and a request that fills a texture begins at its first
|
||||
/// byte: `slots_in` would name its neighbour with every such write).
|
||||
fn slots_holding(&self, start: u64, end: u64) -> Vec<u32> {
|
||||
if end <= start {
|
||||
return Vec::new();
|
||||
}
|
||||
let before = if self.by_start.contains_key(&start) {
|
||||
None
|
||||
} else {
|
||||
self.by_start.range(..start).next_back().filter(|(_, span)| span.0 > start).map(|(_, span)| span)
|
||||
};
|
||||
before
|
||||
.into_iter()
|
||||
.chain(self.by_start.range(start..end).map(|(_, span)| span))
|
||||
.flat_map(|span| span.1.iter().copied())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Title memory written behind the guards' back whose bytes are there
|
||||
/// (DirectStorage's reads into physical pages, at the addresses the title
|
||||
/// has them mapped; `crate::watch::title_memory_written`), since a texture
|
||||
/// pass last took the ranges ([`page_written`]). Kept apart from
|
||||
/// [`REMAPPED`] so that what such writes do is counted by itself.
|
||||
static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Since the start: such ranges kept for a pass; ranges dropped because no
|
||||
/// pass took them; slots of placed textures that held bytes of them when a
|
||||
/// pass took them; of those, the slots whose texture had been uploaded
|
||||
/// before the write (out of the queue, or in it after an upload): they are
|
||||
/// the ones that kept the bytes from before, and the ones made due when
|
||||
/// `VICTORY_PAGE_WRITES` asks for it.
|
||||
pub(crate) static PAGE_WRITES: [std::sync::atomic::AtomicU64; 4] =
|
||||
[const { std::sync::atomic::AtomicU64::new(0) }; 4];
|
||||
|
||||
/// Frames from the pass that takes a written range to the look at its
|
||||
/// slots: the levels of one texture arrive in a few requests, and a look
|
||||
/// two frames on takes those of the next frame with it.
|
||||
const PAGE_WRITE_AFTER: u64 = 2;
|
||||
|
||||
/// The bytes of a write the guards do not see are in title memory `[at,
|
||||
/// at + len)`: the placed textures there changed with no descriptor
|
||||
/// written and nothing mapped. Kept for the next texture pass
|
||||
/// ([`HostHeap::texture_slots_page_written`]), as [`remapped`] keeps its
|
||||
/// ranges; locks one mutex and calls nothing.
|
||||
pub(crate) fn page_written(at: usize, len: usize) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
/// Ranges kept until a pass takes them.
|
||||
const MOST: usize = 1 << 15;
|
||||
let (start, end) = (at as u64, at.saturating_add(len) as u64);
|
||||
if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) {
|
||||
return;
|
||||
}
|
||||
let mut ranges = PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
PAGE_WRITES[0].fetch_add(1, Relaxed);
|
||||
if let Some(last) = ranges.last_mut()
|
||||
&& last.1 == start
|
||||
{
|
||||
last.1 = end;
|
||||
return;
|
||||
}
|
||||
if ranges.len() >= MOST {
|
||||
PAGE_WRITES[1].fetch_add(ranges.len() as u64, Relaxed);
|
||||
ranges.clear();
|
||||
}
|
||||
ranges.push((start, end));
|
||||
}
|
||||
|
||||
/// Title memory the runtime mapped, unmapped or is about to write since a
|
||||
@@ -373,6 +526,10 @@ struct Waiting {
|
||||
pub(crate) struct TextureQueue {
|
||||
slots: std::collections::BTreeMap<u32, Waiting>,
|
||||
writes: u64,
|
||||
/// Slots held back because the card had no room for the host copy
|
||||
/// they need ([`TextureQueue::hold`]), each with the write it was
|
||||
/// held as.
|
||||
held: std::collections::BTreeMap<u32, u64>,
|
||||
}
|
||||
|
||||
impl TextureQueue {
|
||||
@@ -449,6 +606,37 @@ impl TextureQueue {
|
||||
}
|
||||
}
|
||||
|
||||
/// The card has no room for the host copy slot `index` needs: it is
|
||||
/// not handed out again before frame `due`, or before the card has
|
||||
/// room again ([`TextureQueue::room`]). Nothing else of it changes: it
|
||||
/// is not a slot "waiting for its memory", and when it is due it has
|
||||
/// its old place among the slots never looked at. (It stayed due, so
|
||||
/// every pass on a full card looked at the same few hundred slots
|
||||
/// again and stopped there, and the slots behind them were never
|
||||
/// reached: the ones whose host copy exists and only wants bringing up
|
||||
/// to date, and the ones whose memory went, which is what lets host
|
||||
/// copies go and makes room.)
|
||||
fn hold(&mut self, index: u32, write: u64, due: u64) {
|
||||
if let Some(w) = self.same(index, write) {
|
||||
w.due = w.due.max(due);
|
||||
self.held.insert(index, write);
|
||||
}
|
||||
}
|
||||
|
||||
/// The card has room again at `frame`: the slots held back for lack of
|
||||
/// it are due now, as if they had never been held. Returns how many.
|
||||
fn room(&mut self, frame: u64) -> usize {
|
||||
let held = std::mem::take(&mut self.held);
|
||||
let mut back = 0;
|
||||
for (index, write) in held {
|
||||
if let Some(w) = self.same(index, write) {
|
||||
w.due = w.due.min(frame);
|
||||
back += 1;
|
||||
}
|
||||
}
|
||||
back
|
||||
}
|
||||
|
||||
/// Slot `index` was uploaded with `mapped` bytes of its memory there,
|
||||
/// not all of it: looked at again from frame `due`.
|
||||
fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) {
|
||||
@@ -770,7 +958,16 @@ impl HostHeap {
|
||||
tabled: (0..if sampler { 0 } else { count })
|
||||
.map(|_| std::sync::atomic::AtomicU32::new(0))
|
||||
.collect(),
|
||||
placed: Mutex::default(),
|
||||
placed: {
|
||||
let spans = std::sync::Arc::<Mutex<Spans>>::default();
|
||||
if !sampler {
|
||||
PLACED_SPANS
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.push(std::sync::Arc::downgrade(&spans));
|
||||
}
|
||||
spans
|
||||
},
|
||||
};
|
||||
// A slot never written is undefined: shaders reading one (a slot
|
||||
// the title wrote in a way we do not know, or a table entry no
|
||||
@@ -981,6 +1178,16 @@ impl HostHeap {
|
||||
textures.later(index, write, frame, most);
|
||||
}
|
||||
|
||||
/// See [`TextureQueue::hold`].
|
||||
pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) {
|
||||
self.textures.lock().unwrap_or_else(|e| e.into_inner()).hold(index, write, due);
|
||||
}
|
||||
|
||||
/// See [`TextureQueue::room`].
|
||||
pub(crate) fn texture_slots_room(&self, frame: u64) -> usize {
|
||||
self.textures.lock().unwrap_or_else(|e| e.into_inner()).room(frame)
|
||||
}
|
||||
|
||||
/// Bytes of title slot `index`'s memory that were mapped when it was
|
||||
/// last uploaded in part (0: not uploaded, or whole).
|
||||
pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 {
|
||||
@@ -999,6 +1206,7 @@ impl HostHeap {
|
||||
/// whose pass runs first takes them (a title has one view heap).
|
||||
pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
self.texture_slots_page_written(frame);
|
||||
let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
if ranges.is_empty() {
|
||||
return 0;
|
||||
@@ -1018,6 +1226,54 @@ impl HostHeap {
|
||||
slots.len()
|
||||
}
|
||||
|
||||
/// Takes the ranges of title memory written behind the guards' back
|
||||
/// since the last call ([`page_written`]) and finds the slots whose
|
||||
/// placed texture holds bytes of them ([`Spans::slots_holding`]). A
|
||||
/// slot whose texture was uploaded before the write shows the bytes
|
||||
/// from before: with `VICTORY_PAGE_WRITES` (`crate::watch::page_writes`,
|
||||
/// bit 2) it is due again [`PAGE_WRITE_AFTER`] frames on, as memory
|
||||
/// mapped under it would make it ([`HostHeap::texture_slots_remapped`]);
|
||||
/// its host copy exists, so the upload needs no room on the card. A
|
||||
/// slot still waiting for its first upload is left as it is: that
|
||||
/// upload takes the bytes that are there by then. Slots tables read
|
||||
/// are left to their draws. Counted either way; returns how many slots
|
||||
/// it made due.
|
||||
fn texture_slots_page_written(&self, frame: u64) -> usize {
|
||||
let ranges = std::mem::take(&mut *PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
if ranges.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2]
|
||||
}
|
||||
|
||||
/// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end):
|
||||
/// the slots that held bytes of them, those of them uploaded before,
|
||||
/// and those made due (the latter, if `due`).
|
||||
fn slots_written_under(&self, ranges: &[(u64, u64)], frame: u64, due: bool) -> [usize; 3] {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let mut slots: Vec<u32> = {
|
||||
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
|
||||
ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect()
|
||||
};
|
||||
slots.sort_unstable();
|
||||
slots.dedup();
|
||||
slots.retain(|&slot| !self.tabled_lately(slot, frame));
|
||||
let held = slots.len();
|
||||
let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// Uploaded before: out of the queue, or in it after an upload (in
|
||||
// part, or whole and being looked at again).
|
||||
slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0));
|
||||
PAGE_WRITES[2].fetch_add(held as u64, Relaxed);
|
||||
PAGE_WRITES[3].fetch_add(slots.len() as u64, Relaxed);
|
||||
if !due {
|
||||
return [held, slots.len(), 0];
|
||||
}
|
||||
for &slot in &slots {
|
||||
textures.changed(slot, frame, frame + PAGE_WRITE_AFTER);
|
||||
}
|
||||
[held, slots.len(), slots.len()]
|
||||
}
|
||||
|
||||
/// Whether host slot `index` is made from the very record the title
|
||||
/// has at `handle` now. Its host texture then exists (a slot keeps what
|
||||
/// it views), so bringing that texture up to date takes no memory of
|
||||
@@ -1048,6 +1304,101 @@ impl HostHeap {
|
||||
.is_some_and(Option::is_some)
|
||||
}
|
||||
|
||||
/// Levels on demand (`crate::tiles`): makes again the host slots of the
|
||||
/// placed textures whose first level with memory changed since the
|
||||
/// last call ([`levels_changed`]), each from the view it was made
|
||||
/// from, so that it shows the texture from that level ([`make`]). Only
|
||||
/// slots that are made; a slot draws read through a table is made by
|
||||
/// its draw. Returns how many it made.
|
||||
/// shortcut: the starts are kept in one place for all heaps; the heap
|
||||
/// whose pass runs first takes them (a title has one view heap).
|
||||
/// Levels on demand (`crate::tiles`): the card has room, so the slots
|
||||
/// of up to [`Self::WAITING_A_PASS`] placed textures whose upload left
|
||||
/// a held level without tiles at least a second ago
|
||||
/// ([`levels_waiting`]) are due again from the next frame, as memory
|
||||
/// mapped under them would make them
|
||||
/// ([`HostHeap::texture_slots_remapped`]): the upload then gives the
|
||||
/// level its tiles. To be called only while the card has room: without
|
||||
/// it the upload would give nothing again. Slots tables read are left
|
||||
/// to their draws (`texture.rs` `upload` asks again for those). Returns
|
||||
/// how many slots it made due.
|
||||
/// shortcut: kept in one place for all heaps, as the starts below.
|
||||
pub(crate) fn texture_slots_waiting(&self, frame: u64) -> usize {
|
||||
if self.sampler {
|
||||
return 0;
|
||||
}
|
||||
let starts: Vec<u64> = {
|
||||
let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if waiting.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let starts: Vec<u64> = waiting
|
||||
.iter()
|
||||
.filter(|&(_, &since)| crate::host::long_ago(since, 1000, 2))
|
||||
.map(|(&start, _)| start)
|
||||
.take(Self::WAITING_A_PASS)
|
||||
.collect();
|
||||
for start in &starts {
|
||||
waiting.remove(start);
|
||||
}
|
||||
starts
|
||||
};
|
||||
if starts.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let mut slots: Vec<u32> = {
|
||||
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
|
||||
starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
|
||||
};
|
||||
slots.sort_unstable();
|
||||
slots.dedup();
|
||||
slots.retain(|&slot| !self.tabled_lately(slot, frame));
|
||||
let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for &slot in &slots {
|
||||
textures.changed(slot, frame, frame + 1);
|
||||
}
|
||||
crate::tiles::STATS[10].fetch_add(slots.len() as u64, std::sync::atomic::Ordering::Relaxed);
|
||||
slots.len()
|
||||
}
|
||||
|
||||
/// Textures a pass asks again for their levels
|
||||
/// ([`HostHeap::texture_slots_waiting`]): the first ones given tiles
|
||||
/// may take the room the others were asked for, and an upload that
|
||||
/// gives nothing is a whole texture staged and copied for nothing.
|
||||
const WAITING_A_PASS: usize = 128;
|
||||
|
||||
pub(crate) fn texture_views_remade(&self) -> usize {
|
||||
if self.sampler {
|
||||
return 0;
|
||||
}
|
||||
let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
if starts.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let slots: Vec<u32> = {
|
||||
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
|
||||
starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
|
||||
};
|
||||
let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut remade = 0;
|
||||
for slot in slots {
|
||||
let Some(&key) = made.get(slot as usize) else {
|
||||
continue;
|
||||
};
|
||||
if key == 0 {
|
||||
continue;
|
||||
}
|
||||
let Some(view) = view_at(key as u32, (key >> 32) as u32) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(kept) = make(&view, self.cpu(slot)) {
|
||||
self.keep(slot, kept);
|
||||
remade += 1;
|
||||
}
|
||||
}
|
||||
remade
|
||||
}
|
||||
|
||||
/// The memory of the texture title slot `index` views is not mapped
|
||||
/// (any more): a host slot made from it becomes null again, so that
|
||||
/// the host copy can be let go (`crate::resource::let_go_idle`; a slot
|
||||
@@ -1204,21 +1555,27 @@ impl HostHeap {
|
||||
Some(View::Placed(false, resource, desc))
|
||||
if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) =>
|
||||
{
|
||||
Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32))
|
||||
// (And the level the view starts at: word 4 of a texture
|
||||
// view's description, after format, dimension, mapping
|
||||
// and a pad.)
|
||||
Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32, desc[4]))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let stale = {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let span = placed_view
|
||||
.and_then(|(resource, start)| Some((start, start.saturating_add(placed.bytes(resource)?))));
|
||||
let span = placed_view.and_then(|(resource, start, first)| {
|
||||
Some((start, start.saturating_add(placed.bytes(resource)?), first))
|
||||
});
|
||||
match span {
|
||||
Some((start, end)) => {
|
||||
Some((start, end, first)) => {
|
||||
SPANNED[0].fetch_min(start, Relaxed);
|
||||
SPANNED[1].fetch_max(end, Relaxed);
|
||||
placed.rule = stale_rule();
|
||||
placed.note(index, start, end, !seen)
|
||||
let stale = placed.note(index, start, end, !seen);
|
||||
placed.shows(index, first);
|
||||
stale
|
||||
}
|
||||
None => {
|
||||
placed.forget(index);
|
||||
@@ -2104,6 +2461,32 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> {
|
||||
if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) {
|
||||
return None;
|
||||
}
|
||||
// Levels on demand (`crate::tiles`): a texture made level by
|
||||
// level is shown from the first level that is the title's
|
||||
// and has memory, if the title's view starts before it (a
|
||||
// level without memory reads zeros: a black texture). The
|
||||
// title's own view mostly starts there already.
|
||||
if let Some(first) = crate::resource::first_shown(resource)
|
||||
&& first > 0
|
||||
{
|
||||
// SAFETY: a live resource.
|
||||
let own = unsafe { texture.GetDesc() };
|
||||
// The texture's own view (the title gave none): all of it.
|
||||
let whole = D3D12_SHADER_RESOURCE_VIEW_DESC {
|
||||
Format: own.Format,
|
||||
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
|
||||
Shader4ComponentMapping: 5768,
|
||||
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
|
||||
Texture2D: D3D12_TEX2D_SRV {
|
||||
MostDetailedMip: 0,
|
||||
MipLevels: u32::MAX,
|
||||
PlaneSlice: 0,
|
||||
ResourceMinLODClamp: 0.0,
|
||||
},
|
||||
},
|
||||
};
|
||||
crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels));
|
||||
}
|
||||
// SAFETY: a live texture and a slot of our heap.
|
||||
unsafe {
|
||||
device.CreateShaderResourceView(
|
||||
@@ -2209,6 +2592,11 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> {
|
||||
let len = u64::from(resource[4]) | u64::from(resource[5]) << 32;
|
||||
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
|
||||
let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]);
|
||||
// An empty title buffer: nothing to view, and no host copy to
|
||||
// look for (#70: such views were in flight at device removals).
|
||||
if len == 0 {
|
||||
return None;
|
||||
}
|
||||
if *unordered {
|
||||
buffer_uav(address, len, uav_desc(words), at)
|
||||
} else {
|
||||
@@ -2449,6 +2837,29 @@ mod tests {
|
||||
assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D);
|
||||
}
|
||||
|
||||
/// What the texture code asks of the spans (levels on demand): where
|
||||
/// the next texture starts inside a span, the lowest level a view of a
|
||||
/// texture shows, and a texture's slots.
|
||||
#[test]
|
||||
fn spans_say_the_next_start_and_the_lowest_level_viewed() {
|
||||
let mut spans = Spans::default();
|
||||
// A 512x512 texture of 0x56000 bytes viewed from levels 3 and 1,
|
||||
// and the next one 0x6000 after it (run 188).
|
||||
spans.note(1, 0x1_0000, 0x1_0000 + 0x5_6000, true);
|
||||
spans.shows(1, 3);
|
||||
spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true);
|
||||
spans.shows(2, 1);
|
||||
spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true);
|
||||
assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000));
|
||||
assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None);
|
||||
assert_eq!(spans.first_viewed(0x1_0000), Some(1));
|
||||
assert_eq!(spans.first_viewed(0x1_6000), None);
|
||||
assert_eq!(spans.slots_at(0x1_0000), vec![1, 2]);
|
||||
// The view from level 1 goes: the texture is viewed from level 3.
|
||||
spans.forget(2);
|
||||
assert_eq!(spans.first_viewed(0x1_0000), Some(3));
|
||||
}
|
||||
|
||||
/// Views of one placed texture are told from views of others by the
|
||||
/// address and the resource description, not by what they show.
|
||||
#[test]
|
||||
@@ -2566,6 +2977,38 @@ mod tests {
|
||||
assert!(q.due(16, 100).iter().any(|d| d.0 == 98));
|
||||
}
|
||||
|
||||
/// Slots held back for lack of room on the card are not handed out
|
||||
/// until their frame, keep their place, are not counted as waiting
|
||||
/// for their memory, and all come back at once when the card has room;
|
||||
/// a slot written again meanwhile is the title's new write.
|
||||
#[test]
|
||||
fn slots_held_for_lack_of_room_come_back_when_there_is_room() {
|
||||
let mut q = TextureQueue::default();
|
||||
for i in 0..4u32 {
|
||||
q.written(20 + i, 1, 0, false);
|
||||
}
|
||||
let due = q.due(1, 100);
|
||||
assert_eq!(due.len(), 4);
|
||||
// The card is full: slots 20 and 21 are held back until frame 101.
|
||||
for &(index, write) in due.iter().filter(|d| d.0 < 22) {
|
||||
q.hold(index, write, 101);
|
||||
}
|
||||
let now: Vec<u32> = q.due(2, 100).into_iter().map(|d| d.0).collect();
|
||||
assert!(!now.contains(&20) && !now.contains(&21));
|
||||
assert!(now.contains(&22) && now.contains(&23));
|
||||
assert_eq!(q.census(2)[2], 0, "held slots do not wait for their memory");
|
||||
// Due again at their frame, in the order they had.
|
||||
assert_eq!(q.due(101, 100), due);
|
||||
// Slot 21 is written again while held: due as written.
|
||||
q.written(21, 3, 0, false);
|
||||
assert!(q.due(3, 100).iter().any(|d| d.0 == 21));
|
||||
// Room again at frame 5: slot 20 is due at once, and only it was
|
||||
// still held as it was.
|
||||
assert_eq!(q.room(5), 1);
|
||||
assert!(q.due(5, 100).iter().any(|d| d.0 == 20));
|
||||
assert_eq!(q.room(6), 0);
|
||||
}
|
||||
|
||||
/// Textures of which only the smallest levels are held, packed into
|
||||
/// one another's address range (the three of run 188: 0x2c000 bytes
|
||||
/// each at full size, their starts 0x2000 and 0x4000 apart): writing
|
||||
@@ -2659,6 +3102,63 @@ mod tests {
|
||||
assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]);
|
||||
}
|
||||
|
||||
/// A write names the textures that hold its bytes: the one that
|
||||
/// starts where the write starts, not the neighbour before it, whose
|
||||
/// held levels end there.
|
||||
#[test]
|
||||
fn a_write_at_the_start_of_a_packed_texture_names_it_alone() {
|
||||
let mut spans = Spans::default();
|
||||
let at = 0x7_0000_0000u64;
|
||||
assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
|
||||
assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
|
||||
assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty());
|
||||
// A request that fills the second texture's held levels.
|
||||
assert_eq!(spans.slots_in(at + 0x2000, at + 0x6000), [1, 2]);
|
||||
assert_eq!(spans.slots_holding(at + 0x2000, at + 0x6000), [2]);
|
||||
// From inside the first one's held levels on: both.
|
||||
assert_eq!(spans.slots_holding(at + 0x1000, at + 0x3000), [1, 2]);
|
||||
// A whole 64 KiB page: every texture that starts in it.
|
||||
assert_eq!(spans.slots_holding(at, at + 0x10000), [1, 2, 3]);
|
||||
// Past the last start, the last one; past all, or no bytes, none.
|
||||
assert_eq!(spans.slots_holding(at + 0x20000, at + 0x21000), [3]);
|
||||
assert_eq!(spans.slots_holding(at + 0x32000, at + 0x33000), [] as [u32; 0]);
|
||||
assert_eq!(spans.slots_holding(at + 0x2000, at + 0x2000), [] as [u32; 0]);
|
||||
}
|
||||
|
||||
/// A write behind the guards' back under a placed texture: a slot
|
||||
/// waiting for its first upload is left alone, one uploaded before is
|
||||
/// counted, and made due two frames on when that is asked for. (The
|
||||
/// ranges are handed over here, not through the list all heaps share.)
|
||||
#[test]
|
||||
fn a_page_write_makes_an_uploaded_texture_slot_due_when_asked() {
|
||||
let Some(heap) = HostHeap::new(false, 8) else {
|
||||
return; // no host GPU
|
||||
};
|
||||
let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
|
||||
// 64x64 BC7, one mip, at an address no test and no title uses.
|
||||
let at = 0x7fed_0000_0000u64;
|
||||
let mut desc = [0u32; 16];
|
||||
(desc[10], desc[11]) = (at as u32, (at >> 32) as u32);
|
||||
let view = View::Placed(false, [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc);
|
||||
assert!(heap.note_buffer(1, Some(&view), false).is_empty());
|
||||
let written = [(at, at + 0x1000)];
|
||||
// Waiting for its first upload: held, not uploaded, nothing done.
|
||||
assert_eq!(heap.slots_written_under(&written, 50, true), [1, 0, 0]);
|
||||
let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0];
|
||||
assert_eq!(queued, 1);
|
||||
heap.texture_slot_done(1, write, None);
|
||||
assert_eq!(slots(u64::MAX), []);
|
||||
// Uploaded and out of the queue. Memory elsewhere: nothing.
|
||||
assert_eq!(heap.slots_written_under(&[(at + 0x10_0000, at + 0x10_1000)], 60, true), [0, 0, 0]);
|
||||
// Under it, counted only: it stays out of the queue.
|
||||
assert_eq!(heap.slots_written_under(&written, 60, false), [1, 1, 0]);
|
||||
assert_eq!(slots(u64::MAX), []);
|
||||
// Under it, asked for: due two frames on, not before.
|
||||
assert_eq!(heap.slots_written_under(&written, 60, true), [1, 1, 1]);
|
||||
assert_eq!(slots(61), []);
|
||||
assert_eq!(slots(62), [1]);
|
||||
}
|
||||
|
||||
/// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that
|
||||
/// overlaps others is left out of the spans, as before.
|
||||
#[test]
|
||||
|
||||
@@ -385,6 +385,20 @@ pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0),
|
||||
/// new ones, since the start.
|
||||
pub(crate) static HEAP_TEXTURES_REUPLOADED_FULL: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Whether a pass over the textures picked by index on a full card holds
|
||||
/// back the slots that need a new host copy (`VICTORY_FULL_CARD_PASS=0`:
|
||||
/// no, as before: they stay due, each pass looks at the same ones again
|
||||
/// and stops at the 257th). Held back, such a slot is looked at again
|
||||
/// after about four seconds or as soon as the card has room, and the pass
|
||||
/// goes on to the slots behind it: the ones whose host copy exists and
|
||||
/// only wants bringing up to date, and the ones whose memory went (letting
|
||||
/// their host copies go is what makes room). What is uploaded while the
|
||||
/// card has room is the same either way.
|
||||
fn full_card_pass() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_FULL_CARD_PASS").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// Whether a texture that has its host copy is still brought up to date
|
||||
/// while the card has no room for new ones (`VICTORY_REUPLOAD_WHEN_FULL=0`:
|
||||
/// no).
|
||||
@@ -1587,7 +1601,10 @@ impl State {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let now = crate::host::now_ms().max(1);
|
||||
let next = NEXT.load(Ordering::Relaxed);
|
||||
let due_now = if next == 0 { !room } else { now >= next };
|
||||
// (With levels on demand the card may never be without room: the
|
||||
// lines then start with the first texture made that way.)
|
||||
let by_level = crate::tiles::STATS[4].load(Ordering::Relaxed) > 0;
|
||||
let due_now = if next == 0 { !room || by_level } else { now >= next };
|
||||
if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() {
|
||||
return;
|
||||
}
|
||||
@@ -1687,9 +1704,22 @@ impl State {
|
||||
once!("textures picked by index: the card has no room for more; they wait");
|
||||
}
|
||||
let mut refused = 0;
|
||||
// Room again: the slots held back while the card was full are due
|
||||
// now (`full_card_pass`).
|
||||
if room {
|
||||
host.texture_slots_room(frame);
|
||||
}
|
||||
// Slots whose texture's memory the runtime mapped, unmapped or
|
||||
// wrote since the last pass are due again.
|
||||
host.texture_slots_remapped(frame);
|
||||
// Levels on demand: the slots of textures whose first level with
|
||||
// memory changed since the last pass are made again from it.
|
||||
host.texture_views_remade();
|
||||
// And with room, the textures whose upload left a held level
|
||||
// without the card's memory are uploaded again.
|
||||
if room {
|
||||
host.texture_slots_waiting(frame);
|
||||
}
|
||||
let (due, census) = host.texture_slots_due(frame, 4096);
|
||||
HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed);
|
||||
for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) {
|
||||
@@ -1844,7 +1874,15 @@ impl State {
|
||||
&& heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle));
|
||||
if !has_its_texture {
|
||||
refused += 1;
|
||||
if refused > 256 {
|
||||
if full_card_pass() {
|
||||
// Held back for the frames of about four seconds
|
||||
// (`most`), or until the card has room; the pass
|
||||
// goes on, within a count that bounds one pass.
|
||||
host.texture_slot_held(index, write, frame + most);
|
||||
if refused > 1024 {
|
||||
break;
|
||||
}
|
||||
} else if refused > 256 {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
@@ -3258,13 +3296,16 @@ fn view_state(view: Option<&View>) -> String {
|
||||
memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0))
|
||||
),
|
||||
};
|
||||
format!("placed texture view_format={} {state}", d[0])
|
||||
// (Last, so that readers of the older lines still find
|
||||
// theirs: the level the view starts at, and how many it shows.)
|
||||
format!("placed texture view_format={} {state} view_levels={}+{}", d[0], d[4], d[5] as i32)
|
||||
}
|
||||
Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => {
|
||||
format!(
|
||||
"texture object {r:#x} view_format={} {}",
|
||||
"texture object {r:#x} view_format={} {} view_levels={}",
|
||||
d.as_ref().map_or(0, |d| d[0]),
|
||||
texture_state(*r as This)
|
||||
texture_state(*r as This),
|
||||
d.as_ref().map_or("all".to_owned(), |d| format!("{}+{}", d[4], d[5] as i32))
|
||||
)
|
||||
}
|
||||
Some(v) => format!("{v:?}").chars().take(80).collect(),
|
||||
|
||||
@@ -679,7 +679,7 @@ fn create() -> windows::core::Result<Host> {
|
||||
|
||||
/// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
|
||||
/// Reject it before creating a device in diagnostics' software-only mode.
|
||||
fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
|
||||
pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
|
||||
// SAFETY: plain DXGI adapter queries.
|
||||
unsafe {
|
||||
let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
|
||||
@@ -2698,7 +2698,8 @@ fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
|
||||
/// ([`read_backs`]), the frame's main pass by scissor rectangle with its
|
||||
/// culling dispatches (`draw.rs`, `walls_census`), the shader-written
|
||||
/// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
|
||||
/// copies found stale after their refresh (`shadow.rs`), and, in the
|
||||
/// copies found stale after their refresh (`shadow.rs`; only with
|
||||
/// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the
|
||||
/// runtime, the read requests that fail (with 2: every request).
|
||||
pub(crate) fn walls_trace() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
@@ -5607,6 +5608,13 @@ fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, us
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// The queue everything of ours runs on, for a call that must go to it
|
||||
/// in order with the lists (`crate::tiles`: a texture's levels are
|
||||
/// given memory ahead of the list that uploads them).
|
||||
pub(crate) fn queue(&self) -> &ID3D12CommandQueue {
|
||||
&self.queue
|
||||
}
|
||||
|
||||
/// A buffer in the upload heap, mapped for writing.
|
||||
/// A buffer of `size` bytes the card writes and we read (a read back),
|
||||
/// in the state copies into it need.
|
||||
@@ -5854,6 +5862,7 @@ impl Meter {
|
||||
"placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
|
||||
crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
|
||||
);
|
||||
crate::tiles::status();
|
||||
{
|
||||
let [queued, due, away, partly, oldest] =
|
||||
[0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
|
||||
@@ -5877,6 +5886,19 @@ impl Meter {
|
||||
crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
|
||||
);
|
||||
}
|
||||
{
|
||||
let mode = crate::watch::page_writes();
|
||||
let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed));
|
||||
let [kept, dropped, slots, uploaded] =
|
||||
[0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed));
|
||||
tracing::info!(
|
||||
"writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset counts, 1 acts, guards, slots, all)",
|
||||
bytes >> 20,
|
||||
if mode & 1 != 0 { "opened, taken again" } else { "left as they were" },
|
||||
if mode & 4 != 0 { "told as well" } else { "counted only" },
|
||||
if mode & 2 != 0 { "made due again" } else { "left as they were" }
|
||||
);
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
tracing::info!(
|
||||
"write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
|
||||
|
||||
@@ -267,11 +267,17 @@ pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size:
|
||||
struct Views {
|
||||
/// By address: bytes, the section's handle, the offset in it.
|
||||
views: BTreeMap<usize, (usize, usize, u64)>,
|
||||
/// By section and byte offset of a 64 KiB page: the address of that
|
||||
/// page in every view that shows it. A write through one view of a
|
||||
/// page is a write of the bytes every other view shows
|
||||
/// (`crate::watch` guards them all).
|
||||
pages: BTreeMap<(usize, u64), Vec<usize>>,
|
||||
/// Sections by handle: bytes, and whether made committed.
|
||||
sections: Vec<(usize, u64, bool)>,
|
||||
}
|
||||
|
||||
static VIEWS: Mutex<Views> = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new() });
|
||||
static VIEWS: Mutex<Views> =
|
||||
Mutex::new(Views { views: BTreeMap::new(), pages: BTreeMap::new(), sections: Vec::new() });
|
||||
|
||||
fn views() -> std::sync::MutexGuard<'static, Views> {
|
||||
VIEWS.lock().unwrap_or_else(|e| e.into_inner())
|
||||
@@ -288,7 +294,17 @@ pub fn title_memory_section(section: usize, bytes: u64, committed: bool) {
|
||||
/// The runtime mapped `[at, at + len)` as a view of `section` from
|
||||
/// `offset` on. Call after [`crate::title_memory_remapped`] of the range.
|
||||
pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) {
|
||||
views().views.insert(at, (len, section, offset));
|
||||
{
|
||||
let mut v = views();
|
||||
v.views.insert(at, (len, section, offset));
|
||||
for k in 0..len.div_ceil(K64) {
|
||||
v.pages.entry((section, offset + (k * K64) as u64)).or_default().push(at + k * K64);
|
||||
}
|
||||
}
|
||||
// This view is writable from now on: a guard over the same bytes at
|
||||
// another view must look at them again, and the pages are noted written
|
||||
// there (`crate::watch`).
|
||||
crate::watch::views_mapped(section, offset, len);
|
||||
}
|
||||
|
||||
/// What `[at, at + len)` showed is gone ([`crate::title_memory_remapped`]):
|
||||
@@ -303,10 +319,88 @@ pub(crate) fn views_gone(at: usize, len: usize) {
|
||||
let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base);
|
||||
let gone: Vec<usize> = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect();
|
||||
for base in gone {
|
||||
v.views.remove(&base);
|
||||
let Some((bytes, section, offset)) = v.views.remove(&base) else {
|
||||
continue;
|
||||
};
|
||||
for k in 0..bytes.div_ceil(K64) {
|
||||
let key = (section, offset + (k * K64) as u64);
|
||||
if let Some(pages) = v.pages.get_mut(&key) {
|
||||
let page = base + k * K64;
|
||||
pages.retain(|&shown| shown != page);
|
||||
if pages.is_empty() {
|
||||
v.pages.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The title views that overlap `[start, end)`, as `(address, bytes)`.
|
||||
pub(crate) fn views_between(start: usize, end: usize) -> Vec<(usize, usize)> {
|
||||
if start >= end {
|
||||
return Vec::new();
|
||||
}
|
||||
let v = views();
|
||||
let mut out = Vec::new();
|
||||
if let Some((&base, &(bytes, _, _))) = v.views.range(..=start).next_back()
|
||||
&& base + bytes > start
|
||||
{
|
||||
out.push((base, bytes));
|
||||
}
|
||||
for (&base, &(bytes, _, _)) in v.views.range(start.saturating_add(1)..end) {
|
||||
out.push((base, bytes));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The address of the 64 KiB page shown at `page` in every title view that
|
||||
/// shows it, `page`'s own address included; empty if `page` is not a view.
|
||||
pub(crate) fn pages_of(page: usize) -> Vec<usize> {
|
||||
let v = views();
|
||||
let Some((&base, &(bytes, section, offset))) = v.views.range(..=page).next_back() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let within = page.wrapping_sub(base);
|
||||
if within >= bytes || !within.is_multiple_of(K64) {
|
||||
return Vec::new();
|
||||
}
|
||||
v.pages.get(&(section, offset + within as u64)).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The title views that show any of the physical bytes `[offset, offset +
|
||||
/// len)` of `section`, as `(address, bytes)` ranges in address order; not
|
||||
/// those of a page shown in very many views (`MANY_VIEWS`).
|
||||
pub(crate) fn views_of_section(section: usize, offset: u64, len: usize) -> Vec<(usize, usize)> {
|
||||
if len == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let v = views();
|
||||
let end = offset.saturating_add(len as u64);
|
||||
let mut pages: Vec<usize> = Vec::new();
|
||||
let mut at = offset - offset % K64 as u64;
|
||||
while at < end {
|
||||
if let Some(shown) = v.pages.get(&(section, at))
|
||||
&& shown.len() <= crate::watch::MANY_VIEWS
|
||||
{
|
||||
pages.extend(shown.iter().copied());
|
||||
}
|
||||
match at.checked_add(K64 as u64) {
|
||||
Some(next) => at = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
pages.sort_unstable();
|
||||
pages.dedup();
|
||||
let mut runs: Vec<(usize, usize)> = Vec::with_capacity(pages.len());
|
||||
for page in pages {
|
||||
match runs.last_mut() {
|
||||
Some((first, bytes)) if *first + *bytes == page => *bytes += K64,
|
||||
_ => runs.push((page, K64)),
|
||||
}
|
||||
}
|
||||
runs
|
||||
}
|
||||
|
||||
/// How the views cover `[at, at + len)`.
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub(crate) enum Cover {
|
||||
|
||||
@@ -50,6 +50,8 @@ pub mod shader_cache;
|
||||
mod memory;
|
||||
#[cfg(windows)]
|
||||
mod shadow;
|
||||
#[cfg(windows)]
|
||||
mod tiles;
|
||||
pub mod signature;
|
||||
#[cfg(windows)]
|
||||
mod texture;
|
||||
@@ -62,5 +64,6 @@ pub use host::on_failure;
|
||||
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,
|
||||
title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_written,
|
||||
writing as kernel_will_write,
|
||||
};
|
||||
@@ -861,6 +861,9 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) {
|
||||
// Depth textures shaders also write: what they wrote, first.
|
||||
list.twin_use(dst, false, true);
|
||||
list.twin_use(src, false, false);
|
||||
// A destination made level by level gets its levels' memory
|
||||
// ahead of this list (`crate::tiles`).
|
||||
crate::texture::card_writes(list, dst, to, None);
|
||||
ensure_state(list, dst, COPY_DEST);
|
||||
ensure_state(list, src, COPY_SOURCE);
|
||||
crate::texture::host_written(dst);
|
||||
@@ -994,6 +997,11 @@ extern "system" fn copy_texture_region(
|
||||
// A depth texture shaders also write: what they wrote, first (the
|
||||
// source above too).
|
||||
list.twin_use(dst.resource, false, true);
|
||||
// A destination made level by level gets the level's memory ahead
|
||||
// of this list (`crate::tiles`): the title's bake copies each level
|
||||
// of its result into a block-compressed texture of that kind, and
|
||||
// a copy into a level without memory is dropped.
|
||||
crate::texture::card_writes(list, dst.resource, to, Some(dst.footprint.offset as u32));
|
||||
ensure_state(list, dst.resource, COPY_DEST);
|
||||
crate::texture::host_written(dst.resource);
|
||||
let mut to_location = dst;
|
||||
@@ -1147,6 +1155,8 @@ extern "system" fn resolve(
|
||||
// Depth textures shaders also write: what they wrote, first.
|
||||
list.twin_use(dst, false, true);
|
||||
list.twin_use(src, false, false);
|
||||
// As for a copy (`crate::tiles`).
|
||||
crate::texture::card_writes(list, dst, to, Some(dst_sub));
|
||||
ensure_state(list, dst, RESOLVE_DEST);
|
||||
ensure_state(list, src, RESOLVE_SOURCE);
|
||||
crate::texture::host_written(dst);
|
||||
|
||||
@@ -244,22 +244,24 @@ pub(crate) fn pc_format(format: u32) -> u32 {
|
||||
/// (NVIDIA) refused the whole texture, so every pass that wrote it drew
|
||||
/// nothing. There 8-bit RGBA stands in: the same channels in the same
|
||||
/// order, every 4-bit level exact and every 5-bit level within 1/510.
|
||||
/// The title also renders to R9G9B9E5 (67), which no PC GPU does: 16-bit
|
||||
/// float RGBA stands in, with at least R9G9B9E5's precision and range.
|
||||
/// The title's pipelines and views of such targets name the stand-in too
|
||||
/// ([`view_format`], the host view checks).
|
||||
/// shortcut: copies between such a target and a texture the title fills
|
||||
/// itself in the 16-bit format are skipped ([`stands_in`]); convert them
|
||||
/// if a pass turns out to need one.
|
||||
pub(crate) fn target_format(format: u32) -> u32 {
|
||||
const STAND_INS: [(u32, u32); 2] = [(86, 28), (115, 28)];
|
||||
const STAND_INS: [(u32, u32); 3] = [(86, 28), (115, 28), (67, 10)];
|
||||
let Some(i) = STAND_INS.iter().position(|&(f, _)| f == format) else {
|
||||
return format;
|
||||
};
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
static REFUSED: std::sync::OnceLock<[bool; 2]> = std::sync::OnceLock::new();
|
||||
static REFUSED: std::sync::OnceLock<[bool; 3]> = std::sync::OnceLock::new();
|
||||
let refused = REFUSED.get_or_init(|| {
|
||||
STAND_INS.map(|(f, _)| {
|
||||
STAND_INS.map(|(f, to)| {
|
||||
let Some(host) = crate::host::host() else {
|
||||
return false;
|
||||
};
|
||||
@@ -279,7 +281,7 @@ pub(crate) fn target_format(format: u32) -> u32 {
|
||||
| D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0;
|
||||
let refused = asked.is_err() || support.Support1.0 & both != both;
|
||||
if refused {
|
||||
tracing::info!(format = f, "the host does not render to this format: 8-bit RGBA stands in");
|
||||
tracing::info!(format = f, stand_in = to, "the host does not render to this format: a stand-in is used");
|
||||
}
|
||||
refused
|
||||
})
|
||||
@@ -1125,6 +1127,10 @@ pub(crate) struct HostTexture {
|
||||
/// Whether its contents come from title memory ([`fills`]): counted in
|
||||
/// [`KINDS`] while it lives.
|
||||
filled: bool,
|
||||
/// Made without memory of its own (`crate::tiles`): the tiles its
|
||||
/// levels have been given. Its `bytes` are 0: what it holds of the card
|
||||
/// is counted there.
|
||||
pub(crate) tiled: Option<crate::tiles::Tiled>,
|
||||
}
|
||||
|
||||
/// What a title texture has on the host: its host copy and, for a depth
|
||||
@@ -1303,7 +1309,49 @@ fn hosted(this: This, make: bool) -> Option<Made> {
|
||||
.clear
|
||||
.as_ref()
|
||||
.map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast::<c_void>());
|
||||
let Some(texture) = host_texture(&r.desc, r.host.state, clear) else {
|
||||
// Levels on demand (`crate::tiles`): a texture the title places in
|
||||
// memory and fills, of a megabyte or more, that does not hold all
|
||||
// its levels now, is made without memory and given it level by
|
||||
// level. It does not hold them all if its memory is not all
|
||||
// mapped, if the next texture starts inside its span, or if a
|
||||
// view of it starts below level 0. Every other texture, and this
|
||||
// one if the card will not have it so, is made as before.
|
||||
const TEXTURE_2D: u32 = 3;
|
||||
let mut tiled = None;
|
||||
let mut texture = None;
|
||||
let shape_fits = fills(&r.desc)
|
||||
&& r.desc.dimension == TEXTURE_2D
|
||||
&& r.desc.depth_or_array_size == 1
|
||||
&& r.desc.mip_levels > 1
|
||||
&& r.desc.sample_count <= 1;
|
||||
if shape_fits && r.host.placed.load(Relaxed) && crate::tiles::wanted() {
|
||||
let bytes = footprint(&r.desc).map_or(0, |f| f.size);
|
||||
let start = r.data() as u64;
|
||||
// What the upload can read: a console layout, no XOR mode
|
||||
// (`crate::texture` `staging`).
|
||||
let readable = texture_layout(&r.desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor());
|
||||
let partly = readable
|
||||
&& bytes >= crate::tiles::floor()
|
||||
&& (!crate::texture::committed(r.data().cast_const(), bytes as usize)
|
||||
|| crate::descriptor::host::next_start(start, start.saturating_add(bytes)).is_some()
|
||||
|| crate::descriptor::host::first_viewed(start).is_some_and(|first| first > 0));
|
||||
let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true) } else { None };
|
||||
let cut = reserved
|
||||
.as_ref()
|
||||
.zip(crate::host::host())
|
||||
.and_then(|(t, host)| crate::tiles::Tiled::make(&host.device, t, u32::from(r.desc.mip_levels)));
|
||||
// (Both or neither: a reserved texture the card will not cut
|
||||
// into tiles is dropped here, and the old kind is made below.)
|
||||
if cut.is_some() {
|
||||
tiled = cut;
|
||||
texture = reserved;
|
||||
}
|
||||
}
|
||||
let texture = match texture {
|
||||
Some(texture) => Some(texture),
|
||||
None => host_texture(&r.desc, r.host.state, clear),
|
||||
};
|
||||
let Some(texture) = texture else {
|
||||
r.host.refused.store(true, Relaxed);
|
||||
return None;
|
||||
};
|
||||
@@ -1320,7 +1368,10 @@ fn hosted(this: This, make: bool) -> Option<Made> {
|
||||
);
|
||||
}
|
||||
let state = crate::host::legal_state(&texture, crate::host::texture_state(r.host.state));
|
||||
let mut host = HostTexture::new(texture, state);
|
||||
let mut host = match tiled {
|
||||
Some(tiled) => HostTexture::new_tiled(texture, state, tiled),
|
||||
None => HostTexture::new(texture, state),
|
||||
};
|
||||
host.filled = fills(&r.desc);
|
||||
if host.filled {
|
||||
KINDS[0].fetch_add(1, Relaxed);
|
||||
@@ -1371,7 +1422,9 @@ pub(crate) fn room() -> bool {
|
||||
let mb = std::env::var("VICTORY_TEXTURE_BUDGET_MB").ok()?;
|
||||
mb.trim().parse::<u64>().ok().map(|mb| mb << 20)
|
||||
});
|
||||
let filled = KINDS[1].load(Relaxed);
|
||||
// (With the tiles of the copies made level by level, whose own bytes
|
||||
// count as none: `crate::tiles`.)
|
||||
let filled = KINDS[1].load(Relaxed) + crate::tiles::given_total();
|
||||
if let Some(limit) = limit {
|
||||
return filled < limit;
|
||||
}
|
||||
@@ -1379,11 +1432,31 @@ pub(crate) fn room() -> bool {
|
||||
return true;
|
||||
}
|
||||
match crate::host::host().and_then(|h| h.video_memory()) {
|
||||
Some([budget, used, ..]) => used < budget / 100 * room_percent(),
|
||||
// What is kept for card copies of title buffers not made yet
|
||||
// counts as used (`crate::shadow::card_room_kept`; 0 by default).
|
||||
Some([budget, used, ..]) => used + crate::shadow::card_room_kept() < budget / 100 * room_percent(),
|
||||
None => filled < WITHOUT_BUDGET,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`room`] as it was at most a tenth of a second ago, for a question
|
||||
/// asked of many textures a frame ([`room`] asks the system each time).
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn room_lately() -> bool {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
// The tenth of a second of the last asking, counted from 1, and its
|
||||
// answer in the lowest bit.
|
||||
static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let tenth = crate::host::now_ms() / 100 + 1;
|
||||
let last = LAST.load(Relaxed);
|
||||
if last >> 1 == tenth {
|
||||
return last & 1 != 0;
|
||||
}
|
||||
let room = room();
|
||||
LAST.store((tenth << 1) | u64::from(room), Relaxed);
|
||||
room
|
||||
}
|
||||
|
||||
/// The share of the card's budget, in percent, up to which host copies of
|
||||
/// textures picked by index are made ([`room`]): 90 unless
|
||||
/// `VICTORY_TEXTURE_ROOM_PERCENT` says another (50 to 97). At 90 about a
|
||||
@@ -1474,7 +1547,8 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>,
|
||||
return;
|
||||
}
|
||||
let began = std::time::Instant::now();
|
||||
let mut copies: Vec<(usize, ResourceDesc, u64)> = Vec::new();
|
||||
// (The last: made level by level, its bytes are those of its tiles.)
|
||||
let mut copies: Vec<(usize, ResourceDesc, u64, bool)> = Vec::new();
|
||||
// Textures the title fills without a host copy: never one, one let go.
|
||||
let mut without = [0u64; 2];
|
||||
{
|
||||
@@ -1487,7 +1561,10 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>,
|
||||
}
|
||||
let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match made.as_ref() {
|
||||
Some((host, _)) => copies.push((r.data() as usize, r.desc, host.bytes)),
|
||||
Some((host, _)) => copies.push(match &host.tiled {
|
||||
Some(tiled) => (r.data() as usize, r.desc, tiled.given_bytes(), true),
|
||||
None => (r.data() as usize, r.desc, host.bytes, false),
|
||||
}),
|
||||
None => without[usize::from(r.host.gone.load(Relaxed))] += 1,
|
||||
}
|
||||
}
|
||||
@@ -1508,9 +1585,16 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>,
|
||||
// a level not mapped; with the largest level not mapped; with no
|
||||
// level mapped; copies without a console layout (not asked).
|
||||
let mut c = [0u64; 7];
|
||||
for &(memory, desc, bytes) in &copies {
|
||||
// Of the copies: made level by level, and the bytes of their tiles.
|
||||
let mut on_demand = [0u64; 2];
|
||||
for &(memory, desc, bytes, by_level) in &copies {
|
||||
c[0] += 1;
|
||||
c[1] += bytes;
|
||||
if by_level {
|
||||
on_demand[0] += 1;
|
||||
on_demand[1] += bytes;
|
||||
continue;
|
||||
}
|
||||
let Some(layout) = texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else {
|
||||
c[6] += 1;
|
||||
continue;
|
||||
@@ -1587,6 +1671,7 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>,
|
||||
[gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]];
|
||||
let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]];
|
||||
let walk_ms = began.elapsed().as_millis() as u64;
|
||||
let [by_level_n, by_level_mb] = [on_demand[0], on_demand[1] >> 20];
|
||||
tracing::info!(
|
||||
"card accounting: room {room}, the card {used_mb} MB in use of a budget of {budget_mb} MB; host copies of textures the title \
|
||||
fills: {copies_n} alive {copies_mb} MB, of which {unmapped_mb} MB are levels whose title memory is not mapped ({partly} copies \
|
||||
@@ -1597,7 +1682,8 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>,
|
||||
all mapped {never_whole_mb} MB, {never_part} in part {never_part_mb} MB mapped, {never_none} not mapped); {gone_n} whose host \
|
||||
copy was let go ({gone_mb} MB: {gone_whole} all mapped {gone_whole_mb} MB, {gone_part} in part {gone_part_mb} MB mapped, \
|
||||
{gone_none} not mapped); since the line before: {let_go} host copies let go {let_go_mb} MB, {again} made again {again_mb} MB, \
|
||||
{made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own"
|
||||
{made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own; of the host \
|
||||
copies {by_level_n} are made level by level and hold {by_level_mb} MB of tiles (in the MB alive, not in the levels not mapped)"
|
||||
);
|
||||
WALKING.store(false, Relaxed);
|
||||
};
|
||||
@@ -1688,6 +1774,66 @@ pub(crate) fn let_go_idle() {
|
||||
}
|
||||
}
|
||||
|
||||
/// For the memory line: the host copies the sweep never lets go
|
||||
/// ([`let_go_idle`] takes only copies of textures the title fills that the
|
||||
/// host never copied into), by what would say they are dead weight. A
|
||||
/// count and the bytes (twins included) of: the copies the host renders to
|
||||
/// or writes; of them, those whose title memory is not mapped now (its
|
||||
/// first page); those nothing has used for 30 seconds and 60 frames and
|
||||
/// that no list and no slot holds; those that are both; the copies of
|
||||
/// textures the title fills that the host copied into; and, of the first,
|
||||
/// the placed ones. Render-target copies grew from 2,319 MB at the world's
|
||||
/// first frame to 3,075 MB 150 s later in run 197 and never shrank, while
|
||||
/// 26,517 copies of filled textures were let go to stay under the card's
|
||||
/// line.
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
pub(crate) fn targets_census() -> [u64; 12] {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let mut c = [0u64; 12];
|
||||
let all = textures();
|
||||
for &at in all.iter() {
|
||||
// SAFETY: as in `let_go_idle`.
|
||||
let r = unsafe { &*(at as *const Resource) };
|
||||
let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some((host, twin)) = made.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
let copied_into = host.filled && crate::texture::host_wrote(at);
|
||||
if host.filled && !copied_into {
|
||||
continue;
|
||||
}
|
||||
let bytes = host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes);
|
||||
let mut add = |i: usize| {
|
||||
c[i] += 1;
|
||||
c[i + 1] += bytes;
|
||||
};
|
||||
if copied_into {
|
||||
add(8);
|
||||
continue;
|
||||
}
|
||||
add(0);
|
||||
let placed = r.host.placed.load(Relaxed);
|
||||
// Its first page: what is there of a texture starts there.
|
||||
let unmapped = placed && !crate::texture::committed(r.data().cast_const(), 1);
|
||||
let idle = crate::host::long_ago(r.host.used.load(Relaxed), 30_000, 60)
|
||||
&& std::sync::Arc::strong_count(host) == 1
|
||||
&& crate::host::references(&host.texture) == 1;
|
||||
if unmapped {
|
||||
add(2);
|
||||
}
|
||||
if idle {
|
||||
add(4);
|
||||
}
|
||||
if unmapped && idle {
|
||||
add(6);
|
||||
}
|
||||
if placed {
|
||||
add(10);
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// For the memory line: title textures with a host copy the host renders
|
||||
/// to or writes and those copies' bytes (twins included); title textures
|
||||
/// without a host copy and the bytes of title memory they are; host copies
|
||||
@@ -1772,6 +1918,24 @@ impl HostTexture {
|
||||
state: std::sync::atomic::AtomicU32::new(state),
|
||||
bytes,
|
||||
filled: false,
|
||||
tiled: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A texture made without memory of its own (`crate::tiles`): counted
|
||||
/// as a host texture of no bytes.
|
||||
fn new_tiled(
|
||||
texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource,
|
||||
state: u32,
|
||||
tiled: crate::tiles::Tiled,
|
||||
) -> HostTexture {
|
||||
HOST_TEXTURES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
HostTexture {
|
||||
texture,
|
||||
state: std::sync::atomic::AtomicU32::new(state),
|
||||
bytes: 0,
|
||||
filled: false,
|
||||
tiled: Some(tiled),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1843,6 +2007,18 @@ fn host_texture(
|
||||
desc: &ResourceDesc,
|
||||
state: u32,
|
||||
clear: *const c_void,
|
||||
) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
|
||||
host_texture_as(desc, state, clear, false)
|
||||
}
|
||||
|
||||
/// [`host_texture`]; `reserved`: without memory of its own, to be given
|
||||
/// tiles level by level (`crate::tiles`).
|
||||
#[cfg(windows)]
|
||||
fn host_texture_as(
|
||||
desc: &ResourceDesc,
|
||||
state: u32,
|
||||
clear: *const c_void,
|
||||
reserved: bool,
|
||||
) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access
|
||||
@@ -1898,23 +2074,40 @@ fn host_texture(
|
||||
..Default::default()
|
||||
};
|
||||
let mut texture: Option<ID3D12Resource> = None;
|
||||
// SAFETY: the description has the host layout (checked size, same
|
||||
// fields); the out pointer is ours.
|
||||
let made = unsafe {
|
||||
host.device.CreateCommittedResource(
|
||||
&heap,
|
||||
D3D12_HEAP_FLAG_NONE,
|
||||
(&raw const d).cast(),
|
||||
D3D12_RESOURCE_STATES(
|
||||
crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
|
||||
),
|
||||
// The same layout: format, then color or depth and stencil.
|
||||
clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()),
|
||||
&mut texture,
|
||||
)
|
||||
let made = if reserved {
|
||||
// The card's own layout of 64 KiB tiles, which a reserved texture
|
||||
// must have.
|
||||
d.layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE.0 as u32;
|
||||
// SAFETY: as below; a texture the title fills has no clear value.
|
||||
unsafe {
|
||||
host.device.CreateReservedResource(
|
||||
(&raw const d).cast(),
|
||||
D3D12_RESOURCE_STATES(
|
||||
crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
|
||||
),
|
||||
None,
|
||||
&mut texture,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// SAFETY: the description has the host layout (checked size, same
|
||||
// fields); the out pointer is ours.
|
||||
unsafe {
|
||||
host.device.CreateCommittedResource(
|
||||
&heap,
|
||||
D3D12_HEAP_FLAG_NONE,
|
||||
(&raw const d).cast(),
|
||||
D3D12_RESOURCE_STATES(
|
||||
crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
|
||||
),
|
||||
// The same layout: format, then color or depth and stencil.
|
||||
clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()),
|
||||
&mut texture,
|
||||
)
|
||||
}
|
||||
};
|
||||
if let Err(e) = made {
|
||||
tracing::warn!(error = %e, desc = ?d, "no host texture");
|
||||
tracing::warn!(error = %e, desc = ?d, reserved, "no host texture");
|
||||
}
|
||||
if let Some(t) = &texture {
|
||||
crate::host::name(t, || {
|
||||
@@ -1924,6 +2117,73 @@ fn host_texture(
|
||||
texture
|
||||
}
|
||||
|
||||
/// The host copy of title texture `this` if it is made and was made
|
||||
/// without memory of its own (`crate::tiles`); it is not made here.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn host_tiled(this: This) -> Option<OnDemand> {
|
||||
if this.is_null() || !crate::tiles::wanted() {
|
||||
return None;
|
||||
}
|
||||
hosted(this, false).map(|(host, _)| host).filter(|host| host.tiled.is_some()).map(OnDemand)
|
||||
}
|
||||
|
||||
/// The first level a view of title texture `this` may show, if its host
|
||||
/// copy is made level by level and some level is held and has memory
|
||||
/// (`crate::tiles::Tiled::first_shown`).
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn first_shown(this: This) -> Option<u32> {
|
||||
host_tiled(this)?.tiled()?.first_shown()
|
||||
}
|
||||
|
||||
/// A host copy made without memory of its own (`crate::tiles`), as a
|
||||
/// submission-time step of a list holds it.
|
||||
#[cfg(windows)]
|
||||
pub(crate) struct OnDemand(std::sync::Arc<HostTexture>);
|
||||
|
||||
// SAFETY: the host texture is named only in queue calls, which any thread
|
||||
// may make; what it has been given is behind a lock of its own.
|
||||
#[cfg(windows)]
|
||||
unsafe impl Send for OnDemand {}
|
||||
// SAFETY: as above.
|
||||
#[cfg(windows)]
|
||||
unsafe impl Sync for OnDemand {}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl OnDemand {
|
||||
pub(crate) fn tiled(&self) -> Option<&crate::tiles::Tiled> {
|
||||
self.0.tiled.as_ref()
|
||||
}
|
||||
|
||||
/// [`crate::tiles::Tiled::uploaded`]; `memory`: where the texture's
|
||||
/// title memory starts (its slots are made again if the first level
|
||||
/// they may show changed).
|
||||
/// Held levels get tiles only while the card has room ([`room`]).
|
||||
/// Returns whether a level is still without its tiles: the caller
|
||||
/// records the upload again later.
|
||||
pub(crate) fn uploaded(&self, held: u32, memory: u64) -> bool {
|
||||
let Some(tiled) = &self.0.tiled else {
|
||||
return false;
|
||||
};
|
||||
let (changed, waiting) = tiled.uploaded(&self.0.texture, held, room());
|
||||
if changed {
|
||||
crate::descriptor::host::levels_changed(memory);
|
||||
}
|
||||
if waiting {
|
||||
crate::tiles::STATS[9].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
waiting
|
||||
}
|
||||
|
||||
/// [`crate::tiles::Tiled::card_wrote`]; `memory` as above.
|
||||
pub(crate) fn card_wrote(&self, levels: u32, memory: u64) {
|
||||
if let Some(tiled) = &self.0.tiled
|
||||
&& tiled.card_wrote(&self.0.texture, levels)
|
||||
{
|
||||
crate::descriptor::host::levels_changed(memory);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A texture's console memory and description; `None` for buffers.
|
||||
pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> {
|
||||
if this.is_null() {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Translated shaders kept on disk (decision 0003): under the configured
|
||||
//! cache folder, keyed by the container's content and by the VIctory build
|
||||
//! that translated it (the BLAKE3 of our executable), so a rebuilt
|
||||
//! translator never serves an old translation. Entries go through
|
||||
//! cache folder, keyed by the container's content and by the translator
|
||||
//! that translated it (its source fingerprint and settings, see `build`), so
|
||||
//! a changed translator never serves an old translation. Entries go through
|
||||
//! `victory-pipeline`'s content-addressed cache, which writes them
|
||||
//! atomically; an entry that does not read back is translated again.
|
||||
//!
|
||||
@@ -37,60 +37,58 @@ pub(crate) fn counts() -> (u64, u64) {
|
||||
(HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// What identifies this build: the BLAKE3 of our executable file and of
|
||||
/// the translation settings it runs with (the loop limit, which a
|
||||
/// diagnostics build can change at run time).
|
||||
fn build() -> &'static [u8; 32] {
|
||||
static BUILD: OnceLock<[u8; 32]> = OnceLock::new();
|
||||
BUILD.get_or_init(|| {
|
||||
let exe = std::env::current_exe().and_then(std::fs::read);
|
||||
let limit = victory_shader::emit::loop_limit();
|
||||
if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT {
|
||||
tracing::warn!(
|
||||
limit,
|
||||
"VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner"
|
||||
);
|
||||
}
|
||||
match exe {
|
||||
Ok(mut bytes) => {
|
||||
bytes.extend_from_slice(&limit.to_le_bytes());
|
||||
// So is the view heap's null slot (it differs by host GPU):
|
||||
// a translation cached without the clamp must not be served.
|
||||
crate::descriptor::host::probe_view_limit();
|
||||
bytes.extend_from_slice(&victory_shader::emit::view_heap_limit().to_le_bytes());
|
||||
// Which group barriers wait is part of the translation too.
|
||||
bytes.push(victory_shader::emit::group_sync());
|
||||
// So are the switches that pick the form of a wave64 program:
|
||||
// without them here a run with `VICTORY_WAVE_WIDE=0` was
|
||||
// served the translations an earlier run of the same
|
||||
// executable had cached with the switch unset.
|
||||
for name in [
|
||||
"VICTORY_WAVE_WIDE",
|
||||
"VICTORY_WAVE_DEEP_SKIPS",
|
||||
"VICTORY_WAVE_OWN_BITS",
|
||||
"VICTORY_F16_NEAREST",
|
||||
] {
|
||||
bytes.extend_from_slice(name.as_bytes());
|
||||
bytes.push(b'=');
|
||||
if let Some(value) = std::env::var_os(name) {
|
||||
bytes.extend_from_slice(value.as_encoded_bytes());
|
||||
}
|
||||
bytes.push(0);
|
||||
/// What identifies the translation, besides the container: the shader
|
||||
/// crate's fingerprint (its source, every switch it reads, the host facts the
|
||||
/// device gave it, the loop limit, barrier waits and clean-up passes) and
|
||||
/// this file's encoding of the result. Not the whole executable any more: a
|
||||
/// rebuild that leaves the translator alone keeps its translations (each new
|
||||
/// build used to translate the title's thousands of shaders again, which kept
|
||||
/// the first minutes of every test run short of pipelines).
|
||||
/// `VICTORY_SHADER_CACHE_KEY=exe` restores the old key (the executable's hash).
|
||||
/// Worked out per lookup, so a translation made before the device said its
|
||||
/// wave size is never filed under the later key.
|
||||
fn build() -> [u8; 32] {
|
||||
static WARNED: std::sync::Once = std::sync::Once::new();
|
||||
let limit = victory_shader::emit::loop_limit();
|
||||
if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT {
|
||||
WARNED.call_once(|| tracing::warn!(limit, "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner"));
|
||||
}
|
||||
static EXE: OnceLock<Option<[u8; 32]>> = OnceLock::new();
|
||||
let exe = EXE.get_or_init(|| {
|
||||
if std::env::var_os("VICTORY_SHADER_CACHE_KEY").is_some_and(|v| v == "exe") {
|
||||
match std::env::current_exe().and_then(std::fs::read) {
|
||||
Ok(bytes) => Some(*blake3::hash(&bytes).as_bytes()),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "cannot read our executable; keying on the translator");
|
||||
None
|
||||
}
|
||||
// And which clean-up passes ran over the translated code.
|
||||
bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes());
|
||||
*blake3::hash(&bytes).as_bytes()
|
||||
}
|
||||
Err(e) => {
|
||||
// Without it no entry can be trusted: a fresh key per run.
|
||||
tracing::warn!(error = %e, "cannot read our executable; shader cache unused");
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default();
|
||||
*blake3::hash(&now.as_nanos().to_le_bytes()).as_bytes()
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
});
|
||||
let mut h = blake3::Hasher::new();
|
||||
h.update(b"victory shader cache key 2\0");
|
||||
if let Some(exe) = exe {
|
||||
h.update(exe);
|
||||
}
|
||||
h.update(&victory_shader::emit::translation_fingerprint());
|
||||
h.update(include_bytes!("shader_cache.rs"));
|
||||
*h.finalize().as_bytes()
|
||||
}
|
||||
|
||||
/// The offline warm-up (`victory translate --warm`): `container` is
|
||||
/// translated into the cache unless it is there already. `Ok(true)`: it
|
||||
/// was translated now. Needs [`use_shader_cache`] and the same host facts
|
||||
/// the run will have (`victory_shader::emit::translation_fingerprint`).
|
||||
pub fn warm(container: &[u8]) -> Result<bool, String> {
|
||||
let cache = CACHE.get().ok_or("no shader cache")?;
|
||||
let ran = AtomicBool::new(false);
|
||||
let translate = |c: &[u8]| {
|
||||
ran.store(true, Ordering::Relaxed);
|
||||
victory_shader::emit::translate(c).map_err(|e| e.to_string())
|
||||
};
|
||||
cached(cache, &build(), container, translate).map(|_| ran.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// The translation of a console shader container, from the cache when
|
||||
@@ -98,7 +96,7 @@ fn build() -> &'static [u8; 32] {
|
||||
pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> {
|
||||
let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string());
|
||||
match CACHE.get() {
|
||||
Some(cache) => cached(cache, build(), container, translate),
|
||||
Some(cache) => cached(cache, &build(), container, translate),
|
||||
None => translate(container),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,6 +162,40 @@ fn card_limits() -> (u64, u64) {
|
||||
/// Bytes alive of copies' card sides, and of their "before" twins.
|
||||
static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
|
||||
|
||||
/// Whether the texture queue leaves room on the card for the card copies
|
||||
/// of title buffers that are not made yet
|
||||
/// (`VICTORY_CARD_ROOM_FOR_BUFFERS=1`; off by default).
|
||||
///
|
||||
/// The copies are made in one burst when the world loads (run 189: 94 of
|
||||
/// its 95 within two seconds, right before the first world frame), and
|
||||
/// [`card_for`] makes one only while the card is under eight tenths of its
|
||||
/// budget. That held as long as the textures picked by index filled the
|
||||
/// card after the burst. Since the texture queue keeps packed neighbours
|
||||
/// (52b8060) it fills the card while the world loads: 85% and more at the
|
||||
/// burst in runs 190 to 192, so one copy of 95 was made, the CPU looked
|
||||
/// for shader writes in 600 to 720 MB a frame where it had been 30, and
|
||||
/// the frame went from about 240 to 370-470 ms.
|
||||
///
|
||||
/// With the switch, the texture queue's rule (`resource::room`) counts the
|
||||
/// part of [`card_limits`]' second number that no copy has taken yet as
|
||||
/// used, and a copy may be made up to nine tenths of the budget: the room
|
||||
/// it takes was kept for it. After the burst what is kept is what the
|
||||
/// burst left of the limit (87 MB of 1,024 in run 189).
|
||||
fn card_room_kept_on() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
/// The bytes of the card's memory the texture queue leaves free for card
|
||||
/// copies of title buffers not made yet ([`card_room_kept_on`]): 0 with
|
||||
/// the switch off or without card copies.
|
||||
pub(crate) fn card_room_kept() -> u64 {
|
||||
if !card_room_kept_on() || !cards() {
|
||||
return 0;
|
||||
}
|
||||
card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// The copies in the card's memory.
|
||||
static CARDED: Mutex<Vec<std::sync::Weak<Shadow>>> = Mutex::new(Vec::new());
|
||||
|
||||
@@ -212,8 +246,11 @@ fn card_for(size: u64) -> Option<ID3D12Resource> {
|
||||
// queue's own rule (`resource::room`: nine tenths of the budget) counts
|
||||
// them, so the card's use stays where it was and the textures' share
|
||||
// shrinks by the copies' bytes, at most `card_limits`' second number.
|
||||
// (With `card_room_kept_on` the texture queue kept this copy's room
|
||||
// free, and the copy may go up to the queue's own line.)
|
||||
let tenths = if card_room_kept_on() { 9 } else { 8 };
|
||||
if let Some([budget, used, ..]) = host.video_memory()
|
||||
&& used + size > budget / 10 * 8
|
||||
&& used + size > budget / 10 * tenths
|
||||
{
|
||||
return None;
|
||||
}
|
||||
@@ -598,6 +635,155 @@ fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize,
|
||||
out
|
||||
}
|
||||
|
||||
/// The runs of 4-byte words of title memory (cut on its addresses;
|
||||
/// `read` and `merged` are of the memory at `address`) that hold a byte in
|
||||
/// which `merged` differs from `read`, as (offset, bytes) in order to
|
||||
/// `put`. A shader stores words, so these are what the card wrote; every
|
||||
/// other byte of `merged` is the title's as it was read.
|
||||
fn word_runs(address: usize, read: &[u8], merged: &[u8], mut put: impl FnMut(usize, usize)) {
|
||||
let n = read.len().min(merged.len());
|
||||
let mut i = 0;
|
||||
while i < n {
|
||||
// Equal bytes are passed over, 32 at a time while they last.
|
||||
match first_difference(&read[i..n], &merged[i..n]) {
|
||||
Some(d) => i += d,
|
||||
None => break,
|
||||
}
|
||||
// From the word that holds this byte (or the stretch's first
|
||||
// byte) to the end of the last word in a row that holds one.
|
||||
let first = i - ((address + i) & 3).min(i);
|
||||
let mut end = first;
|
||||
while end < n {
|
||||
let word = (((address + end) | 3) + 1 - address).min(n);
|
||||
if read[end..word] == merged[end..word] {
|
||||
break;
|
||||
}
|
||||
end = word;
|
||||
}
|
||||
put(first, end - first);
|
||||
i = end;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the merges that write a stretch of title memory back
|
||||
/// ([`Shadow::relay_merge`], [`Shadow::card_merge`],
|
||||
/// [`Shadow::card_merge_relay`]) look, right before that write, for title
|
||||
/// bytes it is about to put back to older values (`VICTORY_MERGE_RACE=1`;
|
||||
/// off by default). Logging only: [`merge_race`].
|
||||
fn merge_race_on() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_MERGE_RACE").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
/// [`merge_race`]'s sums. Of frame `frame`, and in `total` since the
|
||||
/// start: stretches written back, their bytes, title bytes put back to
|
||||
/// older values, bytes the title and the card both changed, stretches with
|
||||
/// either, the runs a write of the card's words alone makes
|
||||
/// ([`word_runs`]) and their bytes. `said`: the frame's first stretches
|
||||
/// with either. `quiet`: frames since the last line.
|
||||
struct MergeRace {
|
||||
frame: u64,
|
||||
now: [u64; 7],
|
||||
said: Vec<String>,
|
||||
total: [u64; 7],
|
||||
quiet: u64,
|
||||
}
|
||||
|
||||
static MERGE_RACE: Mutex<MergeRace> =
|
||||
Mutex::new(MergeRace { frame: 0, now: [0; 7], said: Vec::new(), total: [0; 7], quiet: 0 });
|
||||
|
||||
/// With [`merge_race_on`], right before a merge writes `merged` over title
|
||||
/// memory at `address` (a stretch of the copy of the title buffer `copy`:
|
||||
/// start and bytes): title memory is read once more and compared with
|
||||
/// `read`, what the merge read of it before. A byte that changed in
|
||||
/// between and that the write-back stores with its value as first read
|
||||
/// (the card did not change it) is a title byte put back to an older
|
||||
/// value; one the write-back stores with the card's byte is one both
|
||||
/// changed. Only bytes the write-back stores are looked at. Summed per
|
||||
/// frame; a line for every frame that has any, and one every 100 frames
|
||||
/// whatever it holds, so that "none" is said, not assumed.
|
||||
///
|
||||
/// A lower bound: a title write that lands after this read (while the
|
||||
/// write-back itself runs) is not seen, nor one that wrote a byte and then
|
||||
/// its old value again. Costs one more read and two compares of every
|
||||
/// stretch written back, on the thread that merges.
|
||||
fn merge_race(read: Option<&[u8]>, copy: (u64, u64), address: usize, merged: &[u8], which: &'static str) {
|
||||
if !merge_race_on() {
|
||||
return;
|
||||
}
|
||||
let Some(read) = read else {
|
||||
return;
|
||||
};
|
||||
let n = read.len().min(merged.len());
|
||||
let (read, merged) = (&read[..n], &merged[..n]);
|
||||
let mut runs: Vec<(usize, usize)> = Vec::new();
|
||||
word_runs(address, read, merged, |off, len| runs.push((off, len)));
|
||||
let whole = [(0, n)];
|
||||
let looked: &[(usize, usize)] = &whole;
|
||||
let mut again = vec![0u8; n];
|
||||
let (mut put_back, mut both, mut first) = (0u64, 0u64, None);
|
||||
if crate::host::read_into(address as *const u8, &mut again) {
|
||||
for &(off, len) in looked {
|
||||
for i in off..off + len {
|
||||
if again[i] == read[i] || again[i] == merged[i] {
|
||||
continue;
|
||||
}
|
||||
if merged[i] == read[i] {
|
||||
put_back += 1;
|
||||
first.get_or_insert(i);
|
||||
} else {
|
||||
both += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let frame = crate::frame::current();
|
||||
let mut race = MERGE_RACE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if race.frame != frame {
|
||||
race.quiet += 1;
|
||||
if race.now[4] > 0 || race.quiet >= 100 {
|
||||
tracing::info!(
|
||||
frame = race.frame,
|
||||
stretches = race.now[0],
|
||||
stretch_bytes = race.now[1],
|
||||
put_back = race.now[2],
|
||||
both_changed = race.now[3],
|
||||
stretches_hit = race.now[4],
|
||||
word_runs = race.now[5],
|
||||
word_run_bytes = race.now[6],
|
||||
stretches_since_start = race.total[0],
|
||||
stretch_bytes_since_start = race.total[1],
|
||||
put_back_since_start = race.total[2],
|
||||
both_changed_since_start = race.total[3],
|
||||
stretches_hit_since_start = race.total[4],
|
||||
word_runs_since_start = race.total[5],
|
||||
word_run_bytes_since_start = race.total[6],
|
||||
first = ?race.said,
|
||||
"merge race: title bytes that changed between a merge's read of title memory and its write-back of what shaders wrote, in this frame (VICTORY_MERGE_RACE=1)"
|
||||
);
|
||||
race.quiet = 0;
|
||||
}
|
||||
race.frame = frame;
|
||||
race.now = [0; 7];
|
||||
race.said.clear();
|
||||
}
|
||||
let hit = u64::from(put_back + both > 0);
|
||||
let run_bytes: u64 = runs.iter().map(|r| r.1 as u64).sum();
|
||||
let add = [1, n as u64, put_back, both, hit, runs.len() as u64, run_bytes];
|
||||
for (i, v) in add.iter().enumerate() {
|
||||
race.now[i] += v;
|
||||
race.total[i] += v;
|
||||
}
|
||||
if hit > 0 && race.said.len() < 8 {
|
||||
race.said.push(format!(
|
||||
"{which}: copy {:#x}+{:#x} stretch {address:#x}+{n:#x}: {put_back} put back (first at {:#x}), {both} both changed",
|
||||
copy.0,
|
||||
copy.1,
|
||||
address + first.unwrap_or(0)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod relay_tests {
|
||||
use super::{Flights, changed_runs, merge_piece, outside};
|
||||
@@ -857,51 +1043,54 @@ fn give_back(v: Vec<u8>) {
|
||||
|
||||
const NOT_WATCHED: u8 = 2;
|
||||
|
||||
/// Where `a` and `b` (of one length) first differ, compared eight bytes at
|
||||
/// a time.
|
||||
// Fixed-size equality compiles to two SIMD comparisons on Windows x64.
|
||||
// Only the first or last unequal chunk needs a byte-wise search.
|
||||
const DIFF_CHUNK: usize = 32;
|
||||
|
||||
/// Where `a` and `b` first differ within their common length.
|
||||
fn first_difference(a: &[u8], b: &[u8]) -> Option<usize> {
|
||||
let whole = a.len().min(b.len()) / 8 * 8;
|
||||
let from = a[..whole]
|
||||
.as_chunks::<8>().0.iter()
|
||||
.zip(b[..whole].chunks_exact(8))
|
||||
.position(|(x, y)| x != y)
|
||||
.map_or(whole, |word| word * 8);
|
||||
a[from..].iter().zip(&b[from..]).position(|(x, y)| x != y).map(|i| from + i)
|
||||
let len = a.len().min(b.len());
|
||||
let (a_chunks, a_tail) = a[..len].as_chunks::<DIFF_CHUNK>();
|
||||
let (b_chunks, b_tail) = b[..len].as_chunks::<DIFF_CHUNK>();
|
||||
let (offset, a, b) = match a_chunks.iter().zip(b_chunks).position(|(x, y)| x != y) {
|
||||
Some(i) => (i * DIFF_CHUNK, &a_chunks[i][..], &b_chunks[i][..]),
|
||||
None => (len - a_tail.len(), a_tail, b_tail),
|
||||
};
|
||||
a.iter().zip(b).position(|(x, y)| x != y).map(|i| offset + i)
|
||||
}
|
||||
|
||||
/// Where `a` and `b` (of one length) last differ.
|
||||
/// Where `a` and `b` last differ within their common length.
|
||||
fn last_difference(a: &[u8], b: &[u8]) -> Option<usize> {
|
||||
let whole = a.len().min(b.len()) / 8 * 8;
|
||||
if let Some(i) = a[whole..].iter().zip(&b[whole..]).rposition(|(x, y)| x != y) {
|
||||
return Some(whole + i);
|
||||
let len = a.len().min(b.len());
|
||||
let (a_chunks, a_tail) = a[..len].as_chunks::<DIFF_CHUNK>();
|
||||
let (b_chunks, b_tail) = b[..len].as_chunks::<DIFF_CHUNK>();
|
||||
if let Some(i) = a_tail.iter().zip(b_tail).rposition(|(x, y)| x != y) {
|
||||
return Some(len - a_tail.len() + i);
|
||||
}
|
||||
let word = a[..whole]
|
||||
.as_chunks::<8>().0.iter()
|
||||
.zip(b[..whole].chunks_exact(8))
|
||||
.rposition(|(x, y)| x != y)?
|
||||
* 8;
|
||||
a[word..word + 8]
|
||||
let chunk = a_chunks.iter().zip(b_chunks).rposition(|(x, y)| x != y)?;
|
||||
a_chunks[chunk]
|
||||
.iter()
|
||||
.zip(&b[word..word + 8])
|
||||
.zip(&b_chunks[chunk])
|
||||
.rposition(|(x, y)| x != y)
|
||||
.map(|i| word + i)
|
||||
.map(|i| chunk * DIFF_CHUNK + i)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod difference_tests {
|
||||
use super::{first_difference, last_difference};
|
||||
|
||||
/// The word-wise searches agree with the byte-wise ones they replace.
|
||||
/// The chunk searches agree with a byte-wise scan across chunk boundaries.
|
||||
#[test]
|
||||
fn differences_are_found_as_byte_by_byte() {
|
||||
let base: Vec<u8> = (0..61u32).map(|i| (i * 7 + 3) as u8).collect();
|
||||
let same = base.clone();
|
||||
assert_eq!(first_difference(&base, &same), None);
|
||||
assert_eq!(last_difference(&base, &same), None);
|
||||
for len in [0usize, 1, 7, 8, 9, 16, 23, 61] {
|
||||
let base: Vec<u8> = (0..98u32).map(|i| (i * 7 + 3) as u8).collect();
|
||||
for len in [0, 1, 31, 32, 33, 63, 64, 65, 97] {
|
||||
let a = &base[1..1 + len];
|
||||
let same = a.to_vec();
|
||||
assert_eq!(first_difference(&same, a), None);
|
||||
assert_eq!(last_difference(&same, a), None);
|
||||
for at in 0..len {
|
||||
for other in at..len {
|
||||
let (a, mut b) = (&base[..len], base[..len].to_vec());
|
||||
let mut b = a.to_vec();
|
||||
b[at] ^= 0x80;
|
||||
b[other] ^= 0x01;
|
||||
let first = a.iter().zip(&b).position(|(x, y)| x != y);
|
||||
@@ -912,6 +1101,19 @@ mod difference_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn differences_ignore_bytes_past_the_shorter_slice() {
|
||||
let a = [0; 65];
|
||||
let mut b = [0; 67];
|
||||
b[65] = 1;
|
||||
assert_eq!(first_difference(&a, &b), None);
|
||||
assert_eq!(last_difference(&b, &a), None);
|
||||
b[32] = 1;
|
||||
b[64] = 1;
|
||||
assert_eq!(first_difference(&b, &a), Some(32));
|
||||
assert_eq!(last_difference(&a, &b), Some(64));
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit shader writes are looked for and put back in.
|
||||
@@ -1325,6 +1527,80 @@ mod wide_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`Shadow::copy_back`] does with a piece that differs from the
|
||||
/// snapshot: `host` is the copy's bytes there, `old` the snapshot's. From
|
||||
/// the first byte that differs to the last, title memory is read into
|
||||
/// `title` (scratch, sized to that stretch) by `read` (the stretch's offset
|
||||
/// in the piece, where to), the GPU's bytes are put in and `host` takes the
|
||||
/// result. The stretch's offset in the piece and its length if that changed
|
||||
/// title memory; none if nothing differs or title memory is not there.
|
||||
/// `runs` takes the runs of the stretch (offsets into `title`, lengths)
|
||||
/// whose bytes are the GPU's and differ from the title's as read: only
|
||||
/// those are to be written, so a title write that lands between the read
|
||||
/// and the write elsewhere in the stretch stays (upstream VIctory #2009).
|
||||
/// `mask` is scratch.
|
||||
fn back_piece(
|
||||
host: &mut [u8],
|
||||
old: &[u8],
|
||||
title: &mut Vec<u8>,
|
||||
mask: &mut Vec<u8>,
|
||||
runs: &mut Vec<(usize, usize)>,
|
||||
read: impl FnOnce(usize, &mut [u8]) -> bool,
|
||||
) -> Option<(usize, usize)> {
|
||||
runs.clear();
|
||||
// From the first byte that differs to the last: title memory is read
|
||||
// and written there only (a shader that sets a few words of a piece
|
||||
// cost a read, a walk and a write of all 64 KiB of it).
|
||||
let first = first_difference(host, old)?;
|
||||
let last = last_difference(host, old).unwrap_or(first);
|
||||
let n = last + 1 - first;
|
||||
let (host, old) = (&mut host[first..=last], &old[first..=last]);
|
||||
title.clear();
|
||||
title.resize(n, 0);
|
||||
if !read(first, title) {
|
||||
return None;
|
||||
}
|
||||
// Title memory with the GPU's bytes put in; the copy takes the title's
|
||||
// bytes in turn.
|
||||
// Without a branch, so the loop runs many bytes at a time: the GPU's
|
||||
// byte where the copy's byte is not what it was before the submission
|
||||
// and the title left its byte as it was, else the title's. (With the
|
||||
// two searches above this was 44 ms a frame for 970 pieces.)
|
||||
// Where the shader and the title both changed a byte while the GPU ran,
|
||||
// the title's stays: the shader computed its byte from the copy's older
|
||||
// data (one cleared a bit of a record the title had already replaced,
|
||||
// and copying it back broke the title's object: an access violation
|
||||
// through 0xffffffff00000000; PalmVIDev e0b70476, VIctory f39c6c2).
|
||||
mask.clear();
|
||||
mask.resize(n, 0);
|
||||
let mut differs = 0u8;
|
||||
for (((t, h), o), m) in title.iter_mut().zip(host.iter_mut()).zip(old).zip(mask.iter_mut()) {
|
||||
let gpu = if (*h != *o) & (*t == *o) { 0xffu8 } else { 0 };
|
||||
let merged = (*t & !gpu) | (*h & gpu);
|
||||
*m = merged ^ *t;
|
||||
differs |= *m;
|
||||
*t = merged;
|
||||
*h = merged;
|
||||
}
|
||||
if differs == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut i = 0;
|
||||
while i < n {
|
||||
while i < n && mask[i] == 0 {
|
||||
i += 1;
|
||||
}
|
||||
let start = i;
|
||||
while i < n && mask[i] != 0 {
|
||||
i += 1;
|
||||
}
|
||||
if i > start {
|
||||
runs.push((start, i - start));
|
||||
}
|
||||
}
|
||||
Some((first, n))
|
||||
}
|
||||
|
||||
/// Since the last frame-rate line, of [`Shadow::merge_under_writes`]: pages
|
||||
/// compared, changed runs put in, and their bytes.
|
||||
static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
|
||||
@@ -1363,7 +1639,93 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod merge_tests {
|
||||
use super::changed_runs;
|
||||
use super::{PIECE, back_piece, changed_runs};
|
||||
|
||||
/// A piece put back takes the GPU's bytes where the copy changed and
|
||||
/// the title's everywhere else, reads and writes title memory only from
|
||||
/// the first change to the last, and its scratch holds that stretch and
|
||||
/// no more: not the 64 KiB per range it once was.
|
||||
#[test]
|
||||
fn a_piece_put_back_reads_only_its_stretch() {
|
||||
let old: Vec<u8> = (0..PIECE).map(|i| (i * 7 + i / 251) as u8).collect();
|
||||
// The title wrote 7 and 40,000 since the snapshot; the GPU wrote 5,
|
||||
// 9 and 40,000 (the GPU's byte wins where both wrote).
|
||||
let mut title_memory = old.clone();
|
||||
title_memory[7] ^= 0x11;
|
||||
title_memory[40_000] ^= 0x22;
|
||||
let mut host = old.clone();
|
||||
for at in [5, 9] {
|
||||
host[at] ^= 0x33;
|
||||
}
|
||||
let gpu = host.clone();
|
||||
let mut scratch = Vec::new();
|
||||
let (mut mask, mut runs) = (Vec::new(), Vec::new());
|
||||
let mut asked = None;
|
||||
let read = |first: usize, into: &mut [u8]| {
|
||||
asked = Some((first, into.len()));
|
||||
into.copy_from_slice(&title_memory[first..first + into.len()]);
|
||||
true
|
||||
};
|
||||
assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((5, 5)));
|
||||
assert_eq!(asked, Some((5, 5)));
|
||||
let mut wanted = title_memory[5..10].to_vec();
|
||||
wanted[0] = gpu[5];
|
||||
wanted[4] = gpu[9];
|
||||
assert_eq!(scratch, wanted);
|
||||
assert_eq!(host[5..10], wanted);
|
||||
// Only the GPU's two bytes are written back (upstream #2009).
|
||||
assert_eq!(runs, [(0, 1), (4, 1)]);
|
||||
// The copy outside the stretch is left as it was.
|
||||
assert!(host[..5] == gpu[..5] && host[10..] == gpu[10..]);
|
||||
assert!(scratch.capacity() < PIECE / 2, "scratch of {} bytes for a stretch of 5", scratch.capacity());
|
||||
|
||||
// Nothing differs: title memory is not read.
|
||||
let mut same = old.clone();
|
||||
assert_eq!(back_piece(&mut same, &old, &mut scratch, &mut mask, &mut runs, |_, _| unreachable!()), None);
|
||||
// Title memory not there: nothing to write, the copy unchanged.
|
||||
let mut host = gpu.clone();
|
||||
assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, _| false), None);
|
||||
assert!(host == gpu);
|
||||
// The GPU wrote what the title holds already: nothing to write.
|
||||
let mut title_memory = old.clone();
|
||||
title_memory[5] = gpu[5];
|
||||
title_memory[9] = gpu[9];
|
||||
let mut host = gpu.clone();
|
||||
let read = |first: usize, into: &mut [u8]| {
|
||||
into.copy_from_slice(&title_memory[first..first + into.len()]);
|
||||
true
|
||||
};
|
||||
assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), None);
|
||||
// A whole piece changed: the scratch grows to it.
|
||||
let mut host: Vec<u8> = old.iter().map(|b| !b).collect();
|
||||
assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, into| into.len() == PIECE), Some((0, PIECE)));
|
||||
assert_eq!(scratch.len(), PIECE);
|
||||
}
|
||||
|
||||
/// A byte the shader and the title both changed while the GPU ran keeps
|
||||
/// the title's (the shader computed it from the copy's older data); a
|
||||
/// byte only the shader changed goes back, and only such bytes are in
|
||||
/// the runs to write (PalmVIDev e0b70476, upstream #2009).
|
||||
#[test]
|
||||
fn a_byte_both_changed_keeps_the_titles_and_only_gpu_bytes_are_written() {
|
||||
let old = vec![1u8, 2, 3, 4, 5, 6];
|
||||
let mut host = old.clone();
|
||||
host[1] = 20; // the GPU alone
|
||||
host[3] = 40; // both
|
||||
host[4] = 50; // the GPU alone
|
||||
let mut title_memory = old.clone();
|
||||
title_memory[3] = 44;
|
||||
title_memory[5] = 66; // the title alone
|
||||
let (mut scratch, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let read = |first: usize, into: &mut [u8]| {
|
||||
into.copy_from_slice(&title_memory[first..first + into.len()]);
|
||||
true
|
||||
};
|
||||
assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((1, 4)));
|
||||
assert_eq!(scratch, [20, 3, 44, 50], "the title's byte where both changed");
|
||||
assert_eq!(host[1..5], [20, 3, 44, 50], "the copy takes the result");
|
||||
assert_eq!(runs, [(0, 1), (3, 1)], "the GPU's bytes only");
|
||||
}
|
||||
|
||||
/// The runs hold exactly the bytes that differ: putting them into the
|
||||
/// old bytes gives the new ones, and no run holds an equal byte.
|
||||
@@ -1504,6 +1866,51 @@ mod piece_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pages of `[a, e)` (title addresses, `a < e`) that a copy whose
|
||||
/// first page is `base` must take from title memory before it holds the
|
||||
/// title's bytes: those it never took (`copied` 0), whether or not the
|
||||
/// title wrote them since tracking began, and those `written` (as
|
||||
/// `crate::watch::writes` gives it, by page in order) shows written after
|
||||
/// the copy took them. As [`Shadow::copy_stale`] decides it.
|
||||
///
|
||||
/// [`Shadow::stale_under_writes`] and [`Shadow::merge_under_writes`] looked
|
||||
/// at `written` alone, so a page of a range shaders may be writing that the
|
||||
/// copy never took, and the title had not written lately, was neither
|
||||
/// merged nor a reason to settle; the refresh leaves such ranges alone, and
|
||||
/// shaders read zeros there (fxceless/victory-fork#206: missing geometry
|
||||
/// with `VICTORY_LATE_WAIT`/`VICTORY_RELAY`).
|
||||
fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec<usize> {
|
||||
(a / PAGE..e.div_ceil(PAGE))
|
||||
.filter(|&page| page >= base)
|
||||
.filter(|&page| match copied.get(page - base) {
|
||||
None => false,
|
||||
Some(0) => true,
|
||||
Some(&at) => written
|
||||
.binary_search_by_key(&page, |&(p, _)| p)
|
||||
.is_ok_and(|i| written[i].1 > at),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod stale_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pages_never_taken_are_stale_written_or_not() {
|
||||
let base = 0x100;
|
||||
let copied = [5, 0, 5, 5];
|
||||
let at = |page: usize| page * PAGE;
|
||||
// Page 0x101 was never taken; page 0x102 was written after it was
|
||||
// taken, page 0x103 before.
|
||||
let written = [(0x102, 6), (0x103, 4)];
|
||||
assert_eq!(stale_pages_in(base, &copied, at(0x100), at(0x104), &written), [0x101, 0x102]);
|
||||
// Part of a page counts as the page; pages outside the copy do not.
|
||||
assert_eq!(stale_pages_in(base, &copied, at(0x101) + 8, at(0x101) + 16, &[]), [0x101]);
|
||||
assert!(stale_pages_in(base, &copied, at(0x104), at(0x106), &[(0x104, 9)]).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies of windows outside buffers let go since the start, and their
|
||||
/// bytes.
|
||||
static LET_GO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
|
||||
@@ -1927,44 +2334,27 @@ impl Shadow {
|
||||
for &(at, n) in &differing {
|
||||
self.changed(at, at + n);
|
||||
}
|
||||
let mut title = vec![0u8; PIECE];
|
||||
// Sized to each stretch read (`back_piece`): a zeroed 64 KiB per
|
||||
// range, most of whose ranges differ nowhere, was most of the
|
||||
// work for small ranges.
|
||||
let (mut title, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new());
|
||||
for (at, n) in differing {
|
||||
// SAFETY: inside the mapping; only the submitting thread
|
||||
// writes it.
|
||||
let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
|
||||
let old = &before[at - from..at - from + n];
|
||||
// From the first byte that differs to the last: title
|
||||
// memory is read and written there only (a shader that sets
|
||||
// a few words of a piece cost a read, a walk and a write of
|
||||
// all 64 KiB of it).
|
||||
let Some(first) = first_difference(host, old) else {
|
||||
let read = |first: usize, title: &mut [u8]| crate::host::read_into((start + at + first) as *const u8, title);
|
||||
let Some((first, n)) = back_piece(host, old, &mut title, &mut mask, &mut runs, read) else {
|
||||
continue;
|
||||
};
|
||||
let last = last_difference(host, old).unwrap_or(first);
|
||||
let (at, n) = (at + first, last + 1 - first);
|
||||
let (host, old) = (&mut host[first..=last], &old[first..=last]);
|
||||
let title = &mut title[..n];
|
||||
if !crate::host::read_into((start + at) as *const u8, title) {
|
||||
continue;
|
||||
}
|
||||
// Title memory with the GPU's bytes put in; the copy takes
|
||||
// the title's bytes in turn.
|
||||
// Without a branch, so the loop runs many bytes at a time:
|
||||
// the GPU's byte where the copy's byte is not what it was
|
||||
// before the submission, else the title's. (With the two
|
||||
// searches above this was 44 ms a frame for 970 pieces.)
|
||||
let mut differs = 0u8;
|
||||
for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) {
|
||||
let gpu = if *h != *o { 0xffu8 } else { 0 };
|
||||
let merged = (*t & !gpu) | (*h & gpu);
|
||||
differs |= merged ^ *t;
|
||||
*t = merged;
|
||||
*h = merged;
|
||||
}
|
||||
if differs != 0 {
|
||||
crate::watch::writing(start + at, n);
|
||||
crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
|
||||
written += n;
|
||||
let at = at + first;
|
||||
crate::watch::writing(start + at, n);
|
||||
// Only the GPU's bytes (upstream #2009): the rest of the
|
||||
// stretch is the title's as read, and a title write landing
|
||||
// there since stays.
|
||||
for &(off, len) in &runs {
|
||||
crate::host::write_mapped((start + at + off) as *mut u8, title[off..].as_ptr(), len);
|
||||
written += len;
|
||||
}
|
||||
}
|
||||
// Our write shows as a title write at the copy's next refresh,
|
||||
@@ -2048,10 +2438,14 @@ impl Shadow {
|
||||
if !crate::host::read_into((start + at) as *const u8, title) {
|
||||
return 0;
|
||||
}
|
||||
// The stretch as read: what the card did not change is the
|
||||
// title's, and may have been written again since.
|
||||
let as_read = merge_race_on().then(|| title.clone());
|
||||
if !merge_piece(now, held, title) {
|
||||
return 0;
|
||||
}
|
||||
crate::watch::writing(start + at, n);
|
||||
merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "pc relay");
|
||||
crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
|
||||
n
|
||||
}
|
||||
@@ -2221,9 +2615,7 @@ impl Shadow {
|
||||
let base = start / PAGE;
|
||||
let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
|
||||
busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) {
|
||||
Some((_, written)) => written.into_iter().any(|(page, write)| {
|
||||
page >= base && copied.get(page - base).is_none_or(|&at| at == 0 || write > at)
|
||||
}),
|
||||
Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(),
|
||||
None => true,
|
||||
})
|
||||
}
|
||||
@@ -2278,11 +2670,7 @@ impl Shadow {
|
||||
};
|
||||
let stale: Vec<usize> = {
|
||||
let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
|
||||
written
|
||||
.into_iter()
|
||||
.filter(|&(page, write)| page >= base && copied.get(page - base).is_none_or(|&at| at == 0 || write > at))
|
||||
.map(|(page, _)| page)
|
||||
.collect()
|
||||
stale_pages_in(base, &copied, a, e, &written)
|
||||
};
|
||||
for page in stale {
|
||||
let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e));
|
||||
@@ -2435,7 +2823,7 @@ impl Shadow {
|
||||
/// title's that arrived between the refresh and the look.
|
||||
fn refresh_check(&self, from: usize, to: usize) {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1") || crate::host::walls_trace()) {
|
||||
if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1")) {
|
||||
return;
|
||||
}
|
||||
const SAMPLE: usize = 256;
|
||||
@@ -2662,6 +3050,9 @@ impl Shadow {
|
||||
title.resize(n, 0);
|
||||
let mut written = 0;
|
||||
if crate::host::read_into((start + at) as *const u8, title) {
|
||||
// The stretch as read: what the card did not change is the
|
||||
// title's, and may have been written again since.
|
||||
let as_read = merge_race_on().then(|| title.clone());
|
||||
// As in `copy_back`: the card's byte where it is not what it
|
||||
// was before the submission, else the title's.
|
||||
let mut differs = 0u8;
|
||||
@@ -2674,6 +3065,7 @@ impl Shadow {
|
||||
}
|
||||
if differs != 0 {
|
||||
crate::watch::writing(start + at, n);
|
||||
merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card");
|
||||
crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
|
||||
written = n;
|
||||
}
|
||||
@@ -2738,6 +3130,9 @@ impl Shadow {
|
||||
title.clear();
|
||||
title.resize(n, 0);
|
||||
let mapped = crate::host::read_into((start + at) as *const u8, title);
|
||||
// The stretch as read: what the card did not change is the
|
||||
// title's, and may have been written again since.
|
||||
let as_read = (mapped && merge_race_on()).then(|| title.clone());
|
||||
let mut changed = false;
|
||||
for (a, b) in outside(at, at + n, skip) {
|
||||
let (a, b) = (a - at, b - at);
|
||||
@@ -2749,6 +3144,7 @@ impl Shadow {
|
||||
return 0;
|
||||
}
|
||||
crate::watch::writing(start + at, n);
|
||||
merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card relay");
|
||||
crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
|
||||
n
|
||||
}
|
||||
|
||||
@@ -56,6 +56,19 @@ pub(crate) struct Staging {
|
||||
uploaded: std::sync::atomic::AtomicBool,
|
||||
/// When a list last recorded a use of it (`crate::host::moment`).
|
||||
used: std::sync::atomic::AtomicU64,
|
||||
/// Levels on demand (`crate::tiles`): the texture's host copy was made
|
||||
/// without memory of its own when the staging buffer was made.
|
||||
on_demand: bool,
|
||||
/// For such a texture: the levels that were the title's at the last
|
||||
/// detiling (a bit a level; the staging buffer holds zeros for the
|
||||
/// others), and what that was judged by ([`Staging::judgement`]).
|
||||
detiled: std::sync::atomic::AtomicU32,
|
||||
judged: [std::sync::atomic::AtomicU64; 2],
|
||||
/// For such a texture: when an upload last left a held level without
|
||||
/// tiles (`crate::host::moment`, never 0; 0: none did). The upload is
|
||||
/// recorded again about a second later if the card has room by then
|
||||
/// ([`upload`]).
|
||||
waiting: std::sync::atomic::AtomicU64,
|
||||
}
|
||||
|
||||
/// What a texture's staging buffer holds: the hash of the memory detiled
|
||||
@@ -225,6 +238,7 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool {
|
||||
if !first && before.is_none() {
|
||||
return true;
|
||||
}
|
||||
card_writes(list, placed, to, None);
|
||||
crate::list::ensure_state(list, placed, COPY_DEST);
|
||||
let part = |texture: &ID3D12Resource, index: usize| D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer the location never releases.
|
||||
@@ -576,6 +590,32 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
|
||||
};
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
staging.used.store(crate::host::moment(), Relaxed);
|
||||
// Levels on demand: a view of the texture now starts at another
|
||||
// level, or another texture now starts inside its span, with no byte
|
||||
// of its memory changed. The levels are judged anew: detiled again at
|
||||
// this list's submission, and uploaded by this list.
|
||||
if staging.on_demand && staging.judgement() != staging.judged() {
|
||||
staging.forget();
|
||||
staging.dirty.store(true, Relaxed);
|
||||
}
|
||||
// Levels on demand: the last upload left a held level without tiles
|
||||
// (the card had no room, or no heap could be had), and nothing else
|
||||
// would record an upload again until the title writes the texture: the
|
||||
// level stayed empty, the texture blurred or black. Asked again about
|
||||
// once a second, and only when the card has room; the staging buffer
|
||||
// still holds the level's bytes.
|
||||
if staging.on_demand {
|
||||
let since = staging.waiting.load(Relaxed);
|
||||
if since != 0 && crate::host::long_ago(since, 1000, 2) {
|
||||
if crate::resource::room_lately() {
|
||||
staging.waiting.store(0, Relaxed);
|
||||
staging.dirty.store(true, Relaxed);
|
||||
crate::tiles::STATS[10].fetch_add(1, Relaxed);
|
||||
} else {
|
||||
staging.waiting.store(crate::host::moment().max(1), Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The host texture has the staging buffer's contents: only the check
|
||||
// at submission is left, and what it finds changed the next list that
|
||||
// samples the texture uploads (a frame late where every list of the
|
||||
@@ -649,11 +689,207 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
|
||||
staging.dirty.store(false, Relaxed);
|
||||
});
|
||||
}
|
||||
// Once per submission however many of its lists sample the texture.
|
||||
list.defer_texture(staging);
|
||||
// Levels on demand (`crate::tiles`): after the check below, in the
|
||||
// order of this list's steps, and before the list is executed, the
|
||||
// levels the staging buffer holds as the title's are given the card's
|
||||
// memory if they have none. The list copies every level, so each one
|
||||
// given here is written whole by it (the rest are copies into no
|
||||
// memory, which the card drops).
|
||||
let on_demand = if staging.on_demand { crate::resource::host_tiled(resource) } else { None };
|
||||
let Some(on_demand) = on_demand else {
|
||||
// Once per submission however many of its lists sample the texture.
|
||||
list.defer_texture(staging);
|
||||
return;
|
||||
};
|
||||
list.defer_texture(staging.clone());
|
||||
list.defer_host(move || {
|
||||
let waiting = on_demand.uploaded(staging.detiled.load(Relaxed), staging.memory as u64);
|
||||
staging.waiting.store(if waiting { crate::host::moment().max(1) } else { 0 }, Relaxed);
|
||||
// A texture picked by index has no staging buffer after this
|
||||
// upload: its slots are made due again by the texture pass.
|
||||
if waiting {
|
||||
crate::descriptor::host::levels_waiting(staging.memory as u64);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Levels on demand: the levels a list claimed for its zeros
|
||||
/// (`crate::tiles::Tiled::claim`), held by the list's submission-time
|
||||
/// step. A list that is reset without having been submitted gives the
|
||||
/// claim up, or the next list that writes those levels would send no zeros
|
||||
/// and what its write does not cover would be what the tiles' last owner
|
||||
/// left.
|
||||
struct Claimed {
|
||||
on_demand: crate::resource::OnDemand,
|
||||
fresh: u32,
|
||||
ran: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
impl Drop for Claimed {
|
||||
fn drop(&mut self) {
|
||||
if self.fresh != 0
|
||||
&& !*self.ran.get_mut()
|
||||
&& let Some(tiled) = self.on_demand.tiled()
|
||||
{
|
||||
tiled.unclaim(self.fresh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Levels on demand (`crate::tiles`): the card itself is about to write
|
||||
/// title texture `resource` in `list` (a copy or a resolve into level
|
||||
/// `level`, or into every level). If its host copy `texture` was made
|
||||
/// without memory, the levels written get theirs when the list is
|
||||
/// submitted, ahead of it on the queue; the ones that have none yet are
|
||||
/// first written with zeros, here in the same list, so that what the
|
||||
/// card's write does not cover is not what the tiles' last owner left.
|
||||
/// To be called before the list is brought to the state of that write.
|
||||
/// shortcut: two lists that write the same new level, submitted in the
|
||||
/// other order than recorded, lose the first one's write under the zeros
|
||||
/// of the other; so does an upload recorded and not yet submitted.
|
||||
pub(crate) fn card_writes(list: &HostList, resource: This, texture: &ID3D12Resource, level: Option<u32>) {
|
||||
let Some(on_demand) = crate::resource::host_tiled(resource) else {
|
||||
return;
|
||||
};
|
||||
let Some(tiled) = on_demand.tiled() else {
|
||||
return;
|
||||
};
|
||||
let levels = match level {
|
||||
Some(level) => tiled.with_level(level),
|
||||
None => tiled.every_level(),
|
||||
};
|
||||
if levels == 0 {
|
||||
return;
|
||||
}
|
||||
let fresh = tiled.claim(levels);
|
||||
// Of them, the ones whose zeros could not be recorded.
|
||||
let mut unzeroed = if host().is_none() { fresh } else { 0 };
|
||||
if fresh != 0
|
||||
&& let Some(host) = host()
|
||||
{
|
||||
const COPY_DEST: u32 = 0x400;
|
||||
crate::list::ensure_state(list, resource, COPY_DEST);
|
||||
// SAFETY: a live resource.
|
||||
let d = unsafe { texture.GetDesc() };
|
||||
for level in (0..u32::from(d.MipLevels).min(32)).filter(|&level| fresh & (1u32 << level) != 0) {
|
||||
let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
|
||||
let mut bytes = 0u64;
|
||||
// SAFETY: outputs for one subresource.
|
||||
unsafe {
|
||||
host.device
|
||||
.GetCopyableFootprints(&d, level, 1, 0, Some(&mut footprint), None, None, Some(&mut bytes));
|
||||
}
|
||||
let Some((buffer, data)) = list.upload(host, bytes) else {
|
||||
// (With the levels that share its tiles, if it is one of
|
||||
// the small ones.)
|
||||
unzeroed |= tiled.with_level(level);
|
||||
continue;
|
||||
};
|
||||
// SAFETY: a mapped buffer of `bytes` bytes, just made.
|
||||
unsafe { std::ptr::write_bytes(data, 0, bytes as usize) };
|
||||
let to = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer the location never releases.
|
||||
pResource: unsafe { std::mem::transmute_copy(texture) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: level },
|
||||
};
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: as above; the list holds the buffer until it is reset.
|
||||
pResource: unsafe { std::mem::transmute_copy(&buffer) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint },
|
||||
};
|
||||
// SAFETY: an open list; both locations name live resources.
|
||||
unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
|
||||
}
|
||||
}
|
||||
// A new level without its zeros gets no tiles from this list: the
|
||||
// card's write into it is lost (the level reads zeros, as before the
|
||||
// write), which is less wrong than a part write over what the tiles'
|
||||
// last owner left. The next list that writes it claims it again.
|
||||
unzeroed &= fresh;
|
||||
if unzeroed != 0 {
|
||||
tiled.unclaim(unzeroed);
|
||||
}
|
||||
let levels = levels & !unzeroed;
|
||||
if levels == 0 {
|
||||
return;
|
||||
}
|
||||
let memory = crate::resource::texture_memory(resource).map_or(0, |(memory, _)| memory as u64);
|
||||
let step = Claimed {
|
||||
on_demand,
|
||||
fresh: fresh & !unzeroed,
|
||||
ran: std::sync::atomic::AtomicBool::new(false),
|
||||
};
|
||||
list.defer_host(move || {
|
||||
step.ran.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
step.on_demand.card_wrote(levels, memory);
|
||||
});
|
||||
}
|
||||
|
||||
impl Staging {
|
||||
/// Levels on demand: what says, beside the mapping, which levels of
|
||||
/// the texture are the title's now. First the lowest level a live view
|
||||
/// of the texture shows (0 without a view that says): the title's own
|
||||
/// word, a texture it holds from level 3 on is viewed from level 3.
|
||||
/// Then where the next texture placed in this one's span starts, in
|
||||
/// bytes from this one's start (`u64::MAX`: none does): for a texture
|
||||
/// viewed from level 0 although a neighbour sits where its large
|
||||
/// levels would be.
|
||||
fn judgement(&self) -> [u64; 2] {
|
||||
let start = self.memory as u64;
|
||||
let first = crate::descriptor::host::first_viewed(start).map_or(0, u64::from);
|
||||
let limit = crate::descriptor::host::next_start(start, start.saturating_add(self.layout.size))
|
||||
.map_or(u64::MAX, |at| at - start);
|
||||
[first, limit]
|
||||
}
|
||||
|
||||
/// What [`Staging::judgement`] said at the last detiling.
|
||||
fn judged(&self) -> [u64; 2] {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
[self.judged[0].load(Relaxed), self.judged[1].load(Relaxed)]
|
||||
}
|
||||
|
||||
/// Levels on demand: the levels that are the title's now, a bit a
|
||||
/// level. A level is held if no view starts above it, its bytes end
|
||||
/// before the next texture starts, and all of them are mapped. The
|
||||
/// smallest levels share the texture's first block and are held
|
||||
/// together. (The console layout: that block first, then the other
|
||||
/// levels from the smallest up, level 0 last:
|
||||
/// `victory_formats::texture::Layout`.) A texture this cannot tell
|
||||
/// the levels of holds them all.
|
||||
fn held_levels(&self, [first, limit]: [u64; 2]) -> u32 {
|
||||
let mips = &self.layout.mips;
|
||||
if self.layout.slices != 1 || mips.is_empty() || mips.len() > 32 {
|
||||
return u32::MAX;
|
||||
}
|
||||
let tail = (self.layout.first_tail_mip as usize).min(mips.len());
|
||||
let there = |from: u64, to: u64| {
|
||||
to > from && to <= limit && committed(self.memory.wrapping_add(from as usize), (to - from) as usize)
|
||||
};
|
||||
let mut held = 0u32;
|
||||
for (level, m) in mips.iter().enumerate().take(tail) {
|
||||
let end = if level == 0 { self.layout.slice_size } else { mips[level - 1].offset };
|
||||
if level as u64 >= first && there(m.offset, end) {
|
||||
held |= 1 << level;
|
||||
}
|
||||
}
|
||||
if tail < mips.len() && there(0, self.layout.alignment.min(self.layout.slice_size)) {
|
||||
for level in tail..mips.len() {
|
||||
if level as u64 >= first {
|
||||
held |= 1 << level;
|
||||
}
|
||||
}
|
||||
}
|
||||
held
|
||||
}
|
||||
|
||||
/// Forgets what the staging buffer was last filled from: the next
|
||||
/// refresh detiles anew, whether the memory changed or not.
|
||||
fn forget(&self) {
|
||||
*self.last.lock().unwrap_or_else(|e| e.into_inner()) = Last::default();
|
||||
}
|
||||
|
||||
/// The title memory the texture is read from: address and bytes.
|
||||
pub(crate) fn memory(&self) -> (usize, usize) {
|
||||
(self.memory as usize, self.layout.size as usize)
|
||||
@@ -835,6 +1071,20 @@ impl Staging {
|
||||
/// Detiles `tiled` (the texture's memory) into the staging buffer.
|
||||
fn detile(&self, tiled: &[u8]) {
|
||||
self.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
// Levels on demand: which levels are the title's is judged here,
|
||||
// once, for what the staging buffer holds from now on. The step
|
||||
// that gives levels their memory goes by this answer.
|
||||
let held = if self.on_demand {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let judged = self.judgement();
|
||||
self.judged[0].store(judged[0], Relaxed);
|
||||
self.judged[1].store(judged[1], Relaxed);
|
||||
let held = self.held_levels(judged);
|
||||
self.detiled.store(held, Relaxed);
|
||||
held
|
||||
} else {
|
||||
u32::MAX
|
||||
};
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if tiled.iter().all(|&b| b == 0) {
|
||||
tracing::debug!(
|
||||
@@ -852,6 +1102,11 @@ impl Staging {
|
||||
let linear = unsafe {
|
||||
std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len)
|
||||
};
|
||||
if mip < 32 && held & (1 << mip) == 0 {
|
||||
// Not the title's: zeros, not what lies in that memory.
|
||||
linear.fill(0);
|
||||
continue;
|
||||
}
|
||||
if let Err(e) =
|
||||
self.layout
|
||||
.detile(tiled, mip, slice, linear, pitch, pitch * rows as usize)
|
||||
@@ -1095,6 +1350,9 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 {
|
||||
|
||||
/// The staging state of a title texture, made on first use.
|
||||
fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
|
||||
// Asked before the table is locked: the sweep lets go of a staging
|
||||
// buffer with its texture's host side locked, in that order.
|
||||
let on_demand = crate::resource::host_tiled(resource).is_some();
|
||||
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let map = map.get_or_insert_with(HashMap::new);
|
||||
if let Some(s) = map.get(&(resource as usize)) {
|
||||
@@ -1162,6 +1420,10 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
|
||||
dirty: std::sync::atomic::AtomicBool::new(true),
|
||||
uploaded: std::sync::atomic::AtomicBool::new(false),
|
||||
used: std::sync::atomic::AtomicU64::new(crate::host::moment()),
|
||||
on_demand,
|
||||
detiled: std::sync::atomic::AtomicU32::new(0),
|
||||
judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2],
|
||||
waiting: std::sync::atomic::AtomicU64::new(0),
|
||||
});
|
||||
map.insert(resource as usize, s.clone());
|
||||
Some(s)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -14,11 +14,14 @@
|
||||
//! wholly uncommitted are skipped while they remain so; one query can
|
||||
//! confirm a whole region, including ordinary reservations between views.
|
||||
//!
|
||||
//! shortcut: writes into physical pages through another view (xmem's
|
||||
//! `write_physical`, DirectStorage's page destinations) are not seen at
|
||||
//! the guarded addresses; they go to the texture pool, whose textures are
|
||||
//! hashed, not guarded. A system call writing into a guarded block fails
|
||||
//! (none is known to).
|
||||
//! Writes into physical pages through another view are seen too: the
|
||||
//! runtime tells us the views of the pages it wrote itself ([`writing`],
|
||||
//! xmem's `write_physical` and DirectStorage's page destinations), and a
|
||||
//! write by the title through any view of a guarded page faults like one
|
||||
//! at the guarded address (the guard makes every view of the page
|
||||
//! read-only, [`open`] gives them all back; not a page of more than
|
||||
//! [`MANY_VIEWS`] views). A
|
||||
//! system call writing into a guarded block fails (none is known to).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Mutex;
|
||||
@@ -218,6 +221,12 @@ pub(crate) fn wrote(at: usize, len: usize) {
|
||||
}
|
||||
j.asked += 1;
|
||||
let now = j.asked;
|
||||
// The asking that stands moves with it: `asked` and `writes` give it as
|
||||
// "now", and a page noted written after "now" stays stale for every
|
||||
// copy that takes it (copied at `now`, written at `now + 1`): copied
|
||||
// again at every refresh, and a reason to settle flights
|
||||
// (fxceless/victory-fork#410).
|
||||
j.ahead_asked = now;
|
||||
for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) {
|
||||
j.written.insert(page, now);
|
||||
}
|
||||
@@ -379,12 +388,17 @@ struct Guards {
|
||||
/// Blocks already copied as zeros. While they remain wholly uncommitted,
|
||||
/// the copy can skip hundreds of MB of failing kernel reads per world frame.
|
||||
absent: BTreeSet<usize>,
|
||||
/// Blocks whose physical page was guarded together with its other views
|
||||
/// (those views' blocks are in it too): a write to one opens them all.
|
||||
/// A write range can be huge (`fread`), so only these are looked up.
|
||||
aliased: BTreeSet<usize>,
|
||||
}
|
||||
|
||||
static GUARDS: Mutex<Guards> = Mutex::new(Guards {
|
||||
protected: BTreeSet::new(),
|
||||
clean: BTreeSet::new(),
|
||||
absent: BTreeSet::new(),
|
||||
aliased: BTreeSet::new(),
|
||||
});
|
||||
|
||||
fn guards() -> std::sync::MutexGuard<'static, Guards> {
|
||||
@@ -508,8 +522,77 @@ fn is_view(start: usize, end: usize) -> bool {
|
||||
|
||||
/// Makes blocks `[from, to)` read-only and notes them guarded and clean;
|
||||
/// block by block if they span views, leaving out any that fail, and
|
||||
/// noting those not committed (unmapped) absent.
|
||||
/// noting those not committed (unmapped) absent. The same physical pages
|
||||
/// at every other view of them are made read-only too: a write through
|
||||
/// one of those is this memory written, and only a fault can say so.
|
||||
/// `VICTORY_VIEW_GUARD=0` leaves the other views as they are, as before.
|
||||
fn protect(g: &mut Guards, from: usize, to: usize) {
|
||||
protect_here(g, from, to);
|
||||
if !view_guard() {
|
||||
return;
|
||||
}
|
||||
for (base, bytes) in crate::inplace::views_between(from.saturating_mul(BLOCK), to.saturating_mul(BLOCK)) {
|
||||
let first = (base / BLOCK).max(from);
|
||||
let last = (base.saturating_add(bytes).div_ceil(BLOCK)).min(to);
|
||||
for block in first..last {
|
||||
let shown = crate::inplace::pages_of(block * BLOCK);
|
||||
// One view (nothing else to guard), or the page the title shows
|
||||
// wherever it has nothing (thousands of views): each view of
|
||||
// that one is guarded by itself.
|
||||
if shown.len() < 2 || shown.len() > MANY_VIEWS {
|
||||
continue;
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
ALIASES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
for alias in shown {
|
||||
let alias = alias / BLOCK;
|
||||
g.aliased.insert(alias);
|
||||
if alias != block {
|
||||
protect_alias(g, alias);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Views of one page past which its views are not guarded together.
|
||||
pub(crate) const MANY_VIEWS: usize = 64;
|
||||
|
||||
/// Whether all the views of a guarded page are guarded together
|
||||
/// (`VICTORY_VIEW_GUARD`).
|
||||
fn view_guard() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_GUARD").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// Diagnostics: blocks guarded together with their other views, blocks
|
||||
/// opened because another view of theirs was written, and blocks opened
|
||||
/// because a view of theirs was mapped; since the start.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) static ALIASES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
|
||||
|
||||
/// Makes `block` read-only: another view of pages a copy has just taken
|
||||
/// through its own view, so that a write through this one faults too. It is
|
||||
/// not noted clean. The copies of title memory at this view have not taken
|
||||
/// the pages: noted clean, the block would not be reported written at their
|
||||
/// next check and they would keep the bytes from before the write (`guard`
|
||||
/// reports a block that is read-only and not clean as written, then notes it
|
||||
/// clean). A block that is clean stays so: had the pages been written since
|
||||
/// its copies took them, `open` would have opened it.
|
||||
fn protect_alias(g: &mut Guards, block: usize) {
|
||||
use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect};
|
||||
if g.protected.contains(&block) {
|
||||
return;
|
||||
}
|
||||
let mut old = 0;
|
||||
// SAFETY: title view memory; only its protection changes.
|
||||
if unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READONLY, &mut old) } != 0 {
|
||||
g.protected.insert(block);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`protect`] for one range, without the other views of its pages.
|
||||
fn protect_here(g: &mut Guards, from: usize, to: usize) {
|
||||
use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect};
|
||||
let set = |from: usize, to: usize| {
|
||||
let mut old = 0;
|
||||
@@ -557,8 +640,31 @@ fn uncommitted_end(block: usize) -> usize {
|
||||
}
|
||||
|
||||
/// Gives write access back to the guarded blocks of `[start, end)` and
|
||||
/// notes them written; true if any was guarded.
|
||||
/// notes them written; true if any was guarded. The same physical pages at
|
||||
/// every other view of them are opened too: the write that faulted (or is
|
||||
/// ours, `crate::host::copy_mapped`) goes through one view, and every
|
||||
/// guard over the pages must copy them again.
|
||||
fn open(g: &mut Guards, start: usize, end: usize) -> bool {
|
||||
let any = open_here(g, start, end);
|
||||
if start >= end || g.aliased.is_empty() {
|
||||
return any;
|
||||
}
|
||||
let aliased: Vec<usize> = g.aliased.range(start / BLOCK..end.div_ceil(BLOCK)).copied().collect();
|
||||
for block in aliased {
|
||||
g.aliased.remove(&block);
|
||||
for alias in crate::inplace::pages_of(block * BLOCK) {
|
||||
if alias / BLOCK != block && open_here(g, alias, alias.saturating_add(BLOCK)) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
ALIASES[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
g.aliased.remove(&(alias / BLOCK));
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
/// [`open`] for one range, without the other views of its pages.
|
||||
fn open_here(g: &mut Guards, start: usize, end: usize) -> bool {
|
||||
use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect};
|
||||
let blocks: Vec<usize> = g
|
||||
.protected
|
||||
@@ -586,6 +692,98 @@ pub fn writing(at: usize, len: usize) {
|
||||
crate::descriptor::host::remapped(at, len);
|
||||
}
|
||||
|
||||
/// What `VICTORY_PAGE_WRITES` asks to be done with a write the guards do
|
||||
/// not see once its bytes are there ([`title_memory_written`]), as bits:
|
||||
/// 1, the guarded blocks under it are opened and count as written (host
|
||||
/// copies of buffers and textures read through tables take them again);
|
||||
/// 2, the placed textures picked by index that lie under it are due again;
|
||||
/// 4, both also for reads to plain addresses when they have finished.
|
||||
/// Unset or `0`: nothing, counted only. `1`: bits 1 and 2. `guards`: bit 1
|
||||
/// alone. `slots`: bit 2 alone. `all`: everything.
|
||||
pub(crate) fn page_writes() -> u8 {
|
||||
static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
|
||||
*MODE.get_or_init(|| match std::env::var("VICTORY_PAGE_WRITES").as_deref().map(str::trim) {
|
||||
Ok("1") => 3,
|
||||
Ok("guards") => 1,
|
||||
Ok("slots") => 2,
|
||||
Ok("all") => 7,
|
||||
_ => 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Since the start: writes into physical pages through the runtime's own
|
||||
/// views that landed at addresses the title has mapped (one for each run
|
||||
/// of addresses); their bytes; guarded blocks that lay under them (host
|
||||
/// copies that would otherwise keep the bytes from before); reads to
|
||||
/// plain addresses that finished.
|
||||
pub(crate) static WRITTEN: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
|
||||
|
||||
/// The bytes of a write the guards do not see are there: title memory
|
||||
/// `[at, at + len)`. `pages`: DirectStorage wrote them into physical pages
|
||||
/// through a view of the runtime's own, and this is an address where the
|
||||
/// title has those pages mapped (no title address faulted, nothing was
|
||||
/// mapped or unmapped; the shortcut this file's header names). Otherwise a
|
||||
/// read to a plain address has finished, of which [`writing`] was told
|
||||
/// before it began.
|
||||
///
|
||||
/// Upstream's c75fdba does the same for its trackers (its `Writing` marks
|
||||
/// the pages once more when dropped; page destinations are reported at
|
||||
/// each address showing them). Here it is counted always and acted on as
|
||||
/// [`page_writes`] says. Called without the runtime's page-table lock;
|
||||
/// takes the guards' lock, then, alone, the lock of the ranges kept for
|
||||
/// the texture pass.
|
||||
pub fn title_memory_written(at: usize, len: usize, pages: bool) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
if len == 0 {
|
||||
return;
|
||||
}
|
||||
let mode = page_writes();
|
||||
let end = at.saturating_add(len);
|
||||
if pages {
|
||||
WRITTEN[0].fetch_add(1, Relaxed);
|
||||
WRITTEN[1].fetch_add(len as u64, Relaxed);
|
||||
} else {
|
||||
WRITTEN[3].fetch_add(1, Relaxed);
|
||||
if mode & 4 == 0 {
|
||||
return;
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut g = guards();
|
||||
let guarded = g.protected.range(at / BLOCK..end.div_ceil(BLOCK)).count() as u64;
|
||||
if pages {
|
||||
WRITTEN[2].fetch_add(guarded, Relaxed);
|
||||
}
|
||||
if mode & 1 != 0 && guarded != 0 {
|
||||
open(&mut g, at, end);
|
||||
}
|
||||
}
|
||||
// A placed texture there changed with no descriptor written.
|
||||
crate::descriptor::host::page_written(at, len);
|
||||
}
|
||||
|
||||
/// The runtime mapped a view of the physical bytes `[offset, offset + len)`
|
||||
/// of `section` (`crate::inplace::title_memory_view`): the view is
|
||||
/// writable, so the same bytes guarded at another view must be checked
|
||||
/// again — and are, the pages noted written, which also has the next check
|
||||
/// guard the new view (`protect`).
|
||||
pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) {
|
||||
if !view_guard() {
|
||||
return;
|
||||
}
|
||||
let ranges = crate::inplace::views_of_section(section, offset, len);
|
||||
if ranges.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut g = guards();
|
||||
for &(at, n) in &ranges {
|
||||
if open_here(&mut g, at, at.saturating_add(n)) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
ALIASES[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Held shared by a read of title memory in place, and alone by the runtime
|
||||
/// while it changes what title memory shows.
|
||||
///
|
||||
@@ -657,6 +855,10 @@ pub fn title_memory_remapped(at: usize, len: usize) {
|
||||
g.protected.remove(&block);
|
||||
g.clean.remove(&block);
|
||||
}
|
||||
let aliased: Vec<usize> = g.aliased.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect();
|
||||
for block in aliased {
|
||||
g.aliased.remove(&block);
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers the handler that takes writes to guarded blocks, once, ahead
|
||||
@@ -1046,6 +1248,154 @@ mod tests {
|
||||
title_memory_remapped(p, 3 * BLOCK);
|
||||
}
|
||||
|
||||
/// A pagefile section mapped twice: two views of the same physical
|
||||
/// pages, the second left for the test; the section handle, the two
|
||||
/// addresses.
|
||||
fn two_views(bytes: usize) -> (usize, usize, usize) {
|
||||
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile,
|
||||
};
|
||||
// SAFETY: a fresh pagefile section, mapped twice; the views keep
|
||||
// the section alive and the handle is closed by the caller.
|
||||
unsafe {
|
||||
let section = CreateFileMappingW(
|
||||
INVALID_HANDLE_VALUE,
|
||||
std::ptr::null(),
|
||||
PAGE_READWRITE,
|
||||
0,
|
||||
bytes as u32,
|
||||
std::ptr::null(),
|
||||
);
|
||||
assert!(!section.is_null());
|
||||
let one = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize;
|
||||
let two = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize;
|
||||
assert_ne!(one, 0);
|
||||
assert_ne!(two, 0);
|
||||
crate::inplace::title_memory_view(one, bytes, section as usize, 0);
|
||||
crate::inplace::title_memory_view(two, bytes, section as usize, 0);
|
||||
(section as usize, one, two)
|
||||
}
|
||||
}
|
||||
|
||||
/// The section of [`two_views`] is closed and its views unmapped; the
|
||||
/// guard is told they are gone first.
|
||||
fn drop_views(section: usize, views: &[usize], bytes: usize) {
|
||||
use windows_sys::Win32::Foundation::CloseHandle;
|
||||
use windows_sys::Win32::System::Memory::{MEMORY_MAPPED_VIEW_ADDRESS, UnmapViewOfFile};
|
||||
for &view in views {
|
||||
title_memory_remapped(view, bytes);
|
||||
// SAFETY: a view of the section mapped by `two_views`.
|
||||
unsafe {
|
||||
UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
|
||||
Value: view as *mut _,
|
||||
})
|
||||
};
|
||||
}
|
||||
// SAFETY: the section's last reference.
|
||||
unsafe { CloseHandle(section as *mut std::ffi::c_void) };
|
||||
}
|
||||
|
||||
/// The title wrote the pages of a guarded texture through another view
|
||||
/// of them: the fault at that view is the guard's to see, and the
|
||||
/// guarded view's next check reports the pages written.
|
||||
#[test]
|
||||
fn a_write_through_another_view_is_reported_at_the_guarded_one() {
|
||||
const SIZE: usize = 2 * BLOCK;
|
||||
let (section, guarded, other) = two_views(SIZE);
|
||||
let pages = |block: usize| (guarded + block * BLOCK) / PAGE;
|
||||
// The first check takes it in (and every view of its pages).
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet");
|
||||
// Writing through the other view faults into the handler, which
|
||||
// opens that view and the guarded one: the next check sees it.
|
||||
// SAFETY: the second view, read-write once the handler has opened it.
|
||||
unsafe { ((other + BLOCK + 8) as *mut u8).write(1) };
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)]));
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()));
|
||||
drop_views(section, &[guarded, other], SIZE);
|
||||
}
|
||||
|
||||
/// A view of guarded pages is mapped anew: it is writable, so the
|
||||
/// guarded view checks its pages again (and guards the new view).
|
||||
#[test]
|
||||
fn a_view_mapped_beside_a_guarded_one_makes_it_check_again() {
|
||||
const SIZE: usize = 2 * BLOCK;
|
||||
let (section, guarded, other) = two_views(SIZE);
|
||||
let pages = |block: usize| (guarded + block * BLOCK) / PAGE;
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet");
|
||||
title_memory_remapped(other, SIZE);
|
||||
crate::inplace::title_memory_view(other, SIZE, section, 0);
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()));
|
||||
drop_views(section, &[guarded, other], SIZE);
|
||||
}
|
||||
|
||||
/// A write of the runtime's own, told at one view of the pages
|
||||
/// (`writing`): the other views' next checks report the pages written.
|
||||
#[test]
|
||||
fn a_write_told_at_one_view_is_reported_at_the_others() {
|
||||
const SIZE: usize = 2 * BLOCK;
|
||||
let (section, guarded, other) = two_views(SIZE);
|
||||
let pages = |block: usize| (guarded + block * BLOCK) / PAGE;
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet");
|
||||
writing(other + BLOCK, BLOCK);
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)]));
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()));
|
||||
// Half a page and the next: both blocks, not just the first's.
|
||||
writing(other + BLOCK / 2, BLOCK);
|
||||
assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
|
||||
drop_views(section, &[guarded, other], SIZE);
|
||||
}
|
||||
|
||||
/// Both views of the pages are checked, each for a copy of its own
|
||||
/// (the title shows one physical page at several addresses, and each
|
||||
/// address has its host copy): a write through either is reported at
|
||||
/// both, whichever is checked first. Guarding the pages for the first
|
||||
/// view's check must not note the second view clean, or its copy would
|
||||
/// keep the bytes from before the write.
|
||||
#[test]
|
||||
fn a_write_is_reported_at_every_checked_view() {
|
||||
const SIZE: usize = 2 * BLOCK;
|
||||
let (section, one, two) = two_views(SIZE);
|
||||
let pages = |view: usize, block: usize| (view + block * BLOCK) / PAGE;
|
||||
assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0), pages(one, 1)]));
|
||||
assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0), pages(two, 1)]), "the second view's first check");
|
||||
assert_eq!(guard(one, one + SIZE), Some(Vec::new()), "nothing written yet");
|
||||
assert_eq!(guard(two, two + SIZE), Some(Vec::new()), "nothing written yet");
|
||||
// SAFETY: the second view, read-write once the handler has opened it.
|
||||
unsafe { ((two + BLOCK + 8) as *mut u8).write(1) };
|
||||
assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 1)]));
|
||||
assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 1)]), "written through this view, checked second");
|
||||
// SAFETY: the first view, as above.
|
||||
unsafe { ((one + 8) as *mut u8).write(1) };
|
||||
assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0)]));
|
||||
assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0)]), "written through this view, checked second");
|
||||
assert_eq!(guard(one, one + SIZE), Some(Vec::new()));
|
||||
assert_eq!(guard(two, two + SIZE), Some(Vec::new()));
|
||||
drop_views(section, &[one, two], SIZE);
|
||||
}
|
||||
|
||||
/// A page shown in more than `MANY_VIEWS` views is guarded at each by
|
||||
/// itself: the others stay writable, and nothing looks through them all.
|
||||
#[test]
|
||||
fn a_page_of_many_views_is_guarded_one_view_at_a_time() {
|
||||
let (section, one, two) = two_views(BLOCK);
|
||||
let filler = one + (1 << 45);
|
||||
for n in 0..MANY_VIEWS {
|
||||
crate::inplace::title_memory_view(filler + n * BLOCK, BLOCK, section, 0);
|
||||
}
|
||||
assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE]));
|
||||
assert!(writable(two), "another view of it is left alone");
|
||||
// SAFETY: the guarded view, opened by the handler.
|
||||
unsafe { ((one + 8) as *mut u8).write(1) };
|
||||
assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE]));
|
||||
title_memory_remapped(filler, MANY_VIEWS * BLOCK);
|
||||
drop_views(section, &[one, two], BLOCK);
|
||||
}
|
||||
|
||||
/// A write or mapping that runs past the end of the address space (a
|
||||
/// title's `fread` with a huge count) covers up to the end; the sum used
|
||||
/// to overflow. Up there no test has guarded blocks.
|
||||
|
||||
@@ -36,6 +36,19 @@ fn host_gpu_failed(what: &str) -> ! {
|
||||
unreachable!("the process has ended")
|
||||
}
|
||||
|
||||
/// The offline warm-up: see `victory_gpu::shader_cache::warm`.
|
||||
pub fn warm_shader(container: &[u8]) -> Result<bool, String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
victory_gpu::shader_cache::warm(container)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = container;
|
||||
Err("no shader cache on this host".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps the host's translations of the title's shaders in `dir` (a
|
||||
/// folder of the cache) across runs, and its compiled pipelines beside it
|
||||
/// (`pipelines`).
|
||||
|
||||
@@ -863,8 +863,25 @@ fn execute(request: &Request) -> Result<(), HRESULT> {
|
||||
return Err(fail(E_INVALIDARG, "source larger than destination"));
|
||||
}
|
||||
let size = request.source_size as usize;
|
||||
return into_destination(request, size, |out| read_into(request, out).map(|()| size))
|
||||
.map_err(|hr| fail(hr, "copying"));
|
||||
// A file read into a title address is the kernel's write, and the
|
||||
// kernel does not fault into the GPU side's guard: a block guarded
|
||||
// again between `kernel_will_write` and the read (the guard over all
|
||||
// the views of a page protects other views from other threads) made
|
||||
// the read fail with ERROR_INVALID_USER_BUFFER, and the title stops
|
||||
// at the failed request (runs amd-C and amd-C2, seconds after the
|
||||
// world's first frame). It is read beside and copied in: our copy
|
||||
// faults into the guard like the title's own writes.
|
||||
let bounce = options & (PAGE_DESTINATION | MEMORY_SOURCE) == 0;
|
||||
return into_destination(request, size, |out| {
|
||||
if !bounce {
|
||||
return read_into(request, out).map(|()| size);
|
||||
}
|
||||
let mut data = vec![0; size];
|
||||
read_into(request, &mut data)?;
|
||||
out.copy_from_slice(&data);
|
||||
Ok(size)
|
||||
})
|
||||
.map_err(|hr| fail(hr, "copying"));
|
||||
}
|
||||
let tables = if bc != 0 { Some(bcpack_tables()?) } else { None };
|
||||
let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?;
|
||||
@@ -1034,13 +1051,22 @@ fn into_destination(
|
||||
fill: impl FnOnce(&mut [u8]) -> Result<usize, HRESULT>,
|
||||
) -> Result<(), HRESULT> {
|
||||
if request.options & PAGE_DESTINATION == 0 {
|
||||
// Raw reads land through the kernel, which does not fault into the
|
||||
// GPU side's guard on title buffers; open them first.
|
||||
// Opens the guarded blocks and tells the GPU side a placed texture
|
||||
// there changes. `fill` writes from user mode (a file read is read
|
||||
// beside first, see `execute`), so a block guarded again meanwhile
|
||||
// faults into the guard instead of failing the write.
|
||||
victory_gpu::kernel_will_write(request.destination as usize, len);
|
||||
// SAFETY: the title's destination holds `destination_size` bytes, at
|
||||
// least `len`, and nothing else writes it until completion.
|
||||
let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::<u8>(), len) };
|
||||
return fill(out).map(drop);
|
||||
let filled = fill(out).map(drop);
|
||||
// Said again now that the bytes are there (upstream's c75fdba holds
|
||||
// the blocks open over the read and marks them once more at its
|
||||
// end): a copy or a texture pass that took the memory while the
|
||||
// read was under way took what was there before. Counted; acted on
|
||||
// only with `VICTORY_PAGE_WRITES=all`.
|
||||
victory_gpu::title_memory_written(request.destination as usize, len, false);
|
||||
return filled;
|
||||
}
|
||||
let offset = (request.page_offset & 0xffff) as usize;
|
||||
// SAFETY: the title passes a page number per 64 KiB of destination,
|
||||
@@ -1054,20 +1080,33 @@ fn into_destination(
|
||||
// Consecutive pages of one allocation (the usual case): written in
|
||||
// place through one view.
|
||||
if let Some(mut window) = super::xmem::page_window(pages, offset, len) {
|
||||
return fill(window.bytes()).map(drop);
|
||||
let filled = fill(window.bytes()).map(drop);
|
||||
drop(window);
|
||||
// The title maps pages where the card reads them and has them
|
||||
// filled afterwards: the GPU side's copies of those addresses
|
||||
// learn of the bytes only from this (upstream c75fdba, fork PR
|
||||
// #571). After a decode that failed part way too: what it wrote
|
||||
// is there.
|
||||
super::xmem::pages_written(pages, offset, len);
|
||||
return filled;
|
||||
}
|
||||
let mut data = vec![0; len];
|
||||
let n = fill(&mut data)?;
|
||||
// A page the title has just made, or a view the host refuses for a moment (commit
|
||||
// or address space short while a load maps many at once), can come right a little
|
||||
// later: tried again before the request fails (`VICTORY_DSTORAGE_RETRIES`, default 12,
|
||||
// about 1.5 s in all).
|
||||
// A page the title has just made, or a view the host refuses for a
|
||||
// moment, comes right a little later: the write is tried again before
|
||||
// the request fails (`VICTORY_DSTORAGE_RETRIES`, 12 tries, about 0.9 s
|
||||
// in all; 0: not tried again, as before). Runs 175-178 lost 12 to 446
|
||||
// reads a launch here, all in one second of the loading; the one build
|
||||
// that tried again (run 165) lost none of 13.
|
||||
static RETRIES: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
|
||||
let retries = *RETRIES.get_or_init(|| {
|
||||
std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.parse().ok()).unwrap_or(12)
|
||||
std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(12)
|
||||
});
|
||||
// Since the start: writes that succeeded on a later try, and writes
|
||||
// given up.
|
||||
static RETRIED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)];
|
||||
let mut written = super::xmem::write_physical(pages, offset, &data[..n]);
|
||||
let mut tries = 0;
|
||||
let mut tries = 0u32;
|
||||
while !written && tries < retries {
|
||||
std::thread::sleep(std::time::Duration::from_millis((2u64 << tries.min(6)).min(128)));
|
||||
tries += 1;
|
||||
@@ -1075,12 +1114,28 @@ fn into_destination(
|
||||
}
|
||||
if written {
|
||||
if tries > 0 {
|
||||
tracing::info!(offset, len, tries, "dstorage: a destination's physical pages written after a retry");
|
||||
let on_a_retry = RETRIED[0].fetch_add(1, Ordering::Relaxed) + 1;
|
||||
tracing::info!(
|
||||
offset,
|
||||
len,
|
||||
tries,
|
||||
on_a_retry,
|
||||
given_up = RETRIED[1].load(Ordering::Relaxed),
|
||||
"dstorage: a destination's physical pages written after a retry"
|
||||
);
|
||||
}
|
||||
// As above, after the write that succeeded.
|
||||
super::xmem::pages_written(pages, offset, n);
|
||||
Ok(())
|
||||
} else {
|
||||
let known = super::xmem::pages_known(pages, offset, len);
|
||||
tracing::warn!(known, last_error = std::io::Error::last_os_error().raw_os_error(), "dstorage: retries used up");
|
||||
let given_up = RETRIED[1].fetch_add(1, Ordering::Relaxed) + 1;
|
||||
tracing::warn!(
|
||||
known = super::xmem::pages_known(pages, offset, len),
|
||||
tries,
|
||||
given_up,
|
||||
on_a_retry = RETRIED[0].load(Ordering::Relaxed),
|
||||
"dstorage: retries used up (VICTORY_DSTORAGE_RETRIES)"
|
||||
);
|
||||
// Said aloud: the title never reads a request's result
|
||||
// (it only polls for completion), so a destination left unwritten
|
||||
// is a model or texture that silently holds whatever its pages
|
||||
|
||||
@@ -519,7 +519,10 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi
|
||||
// fail there instead of faulting into its handler; the title's
|
||||
// synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned
|
||||
// destinations and retry a failed `ReadFile` forever. So the destination
|
||||
// is opened first.
|
||||
// is opened first. A block guarded again before the kernel writes it (the
|
||||
// guard over all the views of a page protects other views from other
|
||||
// threads) fails that `ReadFile`, and the title's retry opens it again;
|
||||
// `fread` has no such retry and reads beside instead (see there).
|
||||
|
||||
pub extern "system" fn ReadFile(
|
||||
file: *mut c_void,
|
||||
@@ -534,12 +537,38 @@ pub extern "system" fn ReadFile(
|
||||
)
|
||||
}
|
||||
|
||||
/// The host CRT reads large requests straight into the caller's buffer.
|
||||
/// The host CRT reads large requests straight into the caller's buffer
|
||||
/// through the kernel, whose write fails on a guarded block instead of
|
||||
/// faulting into the guard. So the bytes are read beside, a chunk at a time
|
||||
/// (a caller may ask for far more than the file holds), and copied in from
|
||||
/// user mode, where a guarded block faults into the guard like the title's
|
||||
/// own writes. Returns the items read, as the CRT does; the bytes of a
|
||||
/// partial last item are copied too, as the CRT leaves them.
|
||||
pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize {
|
||||
victory_gpu::kernel_will_write(buffer as usize, size.saturating_mul(count));
|
||||
host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)(
|
||||
buffer, size, count, stream,
|
||||
)
|
||||
let read = host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize);
|
||||
let total = size.saturating_mul(count);
|
||||
if buffer.is_null() || total == 0 {
|
||||
// The CRT's own checks and answer (EINVAL, or nothing to read).
|
||||
return read(buffer, size, count, stream);
|
||||
}
|
||||
const CHUNK: usize = 1 << 20;
|
||||
let mut beside = vec![0u8; total.min(CHUNK)];
|
||||
let mut done = 0;
|
||||
while done < total {
|
||||
let want = (total - done).min(CHUNK);
|
||||
let n = read(beside.as_mut_ptr(), 1, want, stream);
|
||||
if n > 0 {
|
||||
victory_gpu::kernel_will_write(buffer as usize + done, n);
|
||||
// SAFETY: the caller's buffer holds `size * count` bytes, and
|
||||
// `done + n` is at most that.
|
||||
unsafe { std::ptr::copy_nonoverlapping(beside.as_ptr(), buffer.add(done), n) };
|
||||
done += n;
|
||||
}
|
||||
if n < want {
|
||||
break;
|
||||
}
|
||||
}
|
||||
done / size
|
||||
}
|
||||
|
||||
pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File {
|
||||
@@ -751,6 +780,40 @@ mod tests {
|
||||
assert_eq!((&out, n), (b"0123456789", 10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fread_reads_beside_in_chunks() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("data.bin");
|
||||
// Over two chunks, and not a whole number of 3-byte items.
|
||||
let bytes: Vec<u8> = (0..(5 << 19) + 1).map(|i| (i * 7 + i / 251) as u8).collect();
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32);
|
||||
let open = || {
|
||||
let f = _wfopen(w(&path.to_string_lossy()).as_ptr(), w("rb").as_ptr());
|
||||
assert!(!f.is_null());
|
||||
f
|
||||
};
|
||||
|
||||
// Asked for far more than the file holds: the whole file, in items.
|
||||
let f = open();
|
||||
let mut out = vec![0xaau8; bytes.len() + 64];
|
||||
let items = fread(out.as_mut_ptr(), 3, out.len() / 3, f);
|
||||
assert_eq!(items, bytes.len() / 3);
|
||||
assert_eq!(&out[..bytes.len()], &bytes[..], "the partial last item's bytes too");
|
||||
assert!(out[bytes.len()..].iter().all(|&b| b == 0xaa), "nothing past what was read");
|
||||
fclose(f);
|
||||
|
||||
// Exact reads continue where the last one stopped.
|
||||
let f = open();
|
||||
let mut a = vec![0u8; 1000];
|
||||
let mut b = vec![0u8; (1 << 20) + 5];
|
||||
assert_eq!(fread(a.as_mut_ptr(), 1000, 1, f), 1);
|
||||
assert_eq!(fread(b.as_mut_ptr(), 1, b.len(), f), b.len());
|
||||
assert_eq!(a, bytes[..1000]);
|
||||
assert_eq!(b, bytes[1000..1000 + b.len()]);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
fn text(v: &[u16]) -> String {
|
||||
String::from_utf16_lossy(&v[..v.len() - 1])
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ const KEYBOARD: usize = PADS + 1;
|
||||
const DEVICES: usize = PADS + 2;
|
||||
|
||||
/// Readings kept per device for next/previous lookups.
|
||||
const HISTORY: usize = 32;
|
||||
const HISTORY: usize = 256;
|
||||
const POLL: Duration = Duration::from_millis(8);
|
||||
|
||||
/// The keyboard's stand-in gamepad (virtual key, button); README lists it.
|
||||
|
||||
@@ -364,12 +364,25 @@ struct Slice {
|
||||
index: usize,
|
||||
}
|
||||
|
||||
impl Slice {
|
||||
/// The key in `Physical::shown` of the page `k` pages after this one.
|
||||
fn key(&self, k: usize) -> (usize, usize) {
|
||||
(Arc::as_ptr(&self.section) as usize, self.index + k)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Physical {
|
||||
next_page: usize,
|
||||
pages: HashMap<usize, Slice>,
|
||||
/// Mapped views by address: their length and what they show.
|
||||
views: BTreeMap<usize, (usize, Slice)>,
|
||||
/// Where each page shows: by its section and its index there, the
|
||||
/// address of that page in every view that shows it now ([`shown_at`];
|
||||
/// as upstream's c75fdba keeps it). The title maps pages where the
|
||||
/// card reads them and has them filled afterwards by DirectStorage,
|
||||
/// which writes through views of our own.
|
||||
shown: HashMap<(usize, usize), Vec<usize>>,
|
||||
}
|
||||
|
||||
static PHYSICAL: LazyLock<Mutex<Physical>> = LazyLock::new(|| {
|
||||
@@ -596,6 +609,58 @@ pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option<
|
||||
})
|
||||
}
|
||||
|
||||
/// The title addresses that show bytes `[offset, offset + len)` of `pages`
|
||||
/// now, byte for byte, as runs (address, bytes) in address order: a write
|
||||
/// to the pages through a view of our own ([`page_window`],
|
||||
/// [`write_physical`]) lands there too, and nothing that watches those
|
||||
/// addresses sees it (the GPU side's guards fault only on a write at the
|
||||
/// guarded address itself). Empty if no view shows them. Byte for byte,
|
||||
/// not by whole pages: the title packs several small textures into one
|
||||
/// page and fills each with a request of its own.
|
||||
pub(crate) fn shown_at(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> {
|
||||
let Some(end) = offset.checked_add(len) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let first = offset / PAGE;
|
||||
let Some(touched) = pages.get(first..end.div_ceil(PAGE)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut pieces: Vec<(usize, usize)> = Vec::new();
|
||||
{
|
||||
let physical = physical();
|
||||
for (i, page) in touched.iter().enumerate() {
|
||||
let Some(addresses) = physical.pages.get(page).and_then(|slice| physical.shown.get(&slice.key(0))) else {
|
||||
continue;
|
||||
};
|
||||
// The bytes of this page that the write covers.
|
||||
let lo = if i == 0 { offset % PAGE } else { 0 };
|
||||
let hi = (end - (first + i) * PAGE).min(PAGE);
|
||||
pieces.extend(addresses.iter().map(|&at| (at + lo, hi - lo)));
|
||||
}
|
||||
}
|
||||
pieces.sort_unstable();
|
||||
let mut runs: Vec<(usize, usize)> = Vec::new();
|
||||
for (at, bytes) in pieces {
|
||||
match runs.last_mut() {
|
||||
Some((start, n)) if *start + *n == at => *n += bytes,
|
||||
_ => runs.push((at, bytes)),
|
||||
}
|
||||
}
|
||||
runs
|
||||
}
|
||||
|
||||
/// Bytes `[offset, offset + len)` of `pages` have been written through a
|
||||
/// view of our own: the GPU side is told at every title address that
|
||||
/// shows them (`victory_gpu::title_memory_written`; what it does with it
|
||||
/// is `VICTORY_PAGE_WRITES`' to say, and it counts either way). Call when
|
||||
/// the bytes are there, and without the page table's lock ([`shown_at`]
|
||||
/// takes and leaves it).
|
||||
pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) {
|
||||
for (at, bytes) in shown_at(pages, offset, len) {
|
||||
victory_gpu::title_memory_written(at, bytes, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps `n` pages at `address`, in place of what is mapped there; null
|
||||
/// `pages` unmaps. Returns `address`, or null if a page or the host fails.
|
||||
pub extern "system" fn XMemMapPhysicalPages(
|
||||
@@ -746,6 +811,9 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
|
||||
victory_gpu::title_memory_remapped(base, len);
|
||||
// What the range shows now, for the GPU side's in-place census.
|
||||
victory_gpu::title_memory_view(base, len, slice.section.0 as usize, (slice.index * PAGE) as u64);
|
||||
for k in 0..len.div_ceil(PAGE) {
|
||||
physical.shown.entry(slice.key(k)).or_default().push(base + k * PAGE);
|
||||
}
|
||||
physical.views.insert(base, (len, slice));
|
||||
true
|
||||
}
|
||||
@@ -824,6 +892,15 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) {
|
||||
let Some((size, slice)) = physical.views.remove(&at) else {
|
||||
continue;
|
||||
};
|
||||
for k in 0..size.div_ceil(PAGE) {
|
||||
let key = slice.key(k);
|
||||
if let Some(addresses) = physical.shown.get_mut(&key) {
|
||||
addresses.retain(|&a| a != at + k * PAGE);
|
||||
if addresses.is_empty() {
|
||||
physical.shown.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
victory_gpu::title_memory_remapped(at, size);
|
||||
// SAFETY: a view we mapped; it becomes a placeholder again.
|
||||
unsafe {
|
||||
@@ -1306,6 +1383,54 @@ mod tests {
|
||||
assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1);
|
||||
}
|
||||
|
||||
/// Pages say where the title has them mapped, byte for byte (after
|
||||
/// fork PR #571's test; its runs are whole pages).
|
||||
#[test]
|
||||
fn pages_say_where_they_are_mapped() {
|
||||
let pages = allocate(3);
|
||||
let reserve = |n: usize| {
|
||||
let at = XMemVirtualAlloc(std::ptr::null_mut(), n * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE);
|
||||
assert!(!at.is_null());
|
||||
at
|
||||
};
|
||||
// `b` keeps a page unmapped at either end, so that no run at `b`
|
||||
// ever touches one at `a`, wherever the host puts the two.
|
||||
let (a, b) = (reserve(3), reserve(4));
|
||||
assert!(shown_at(&pages, 0, 3 * PAGE).is_empty(), "mapped nowhere");
|
||||
// All three at `a`; the last two at `b`, from its second page on.
|
||||
assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
|
||||
let second = b.wrapping_byte_add(PAGE);
|
||||
assert_eq!(XMemMapPhysicalPages(second, 2, pages[1..].as_ptr()), second);
|
||||
let (a, second) = (a as usize, second as usize);
|
||||
let sorted = |mut runs: Vec<(usize, usize)>| {
|
||||
runs.sort_unstable();
|
||||
runs
|
||||
};
|
||||
assert_eq!(shown_at(&pages, 0, PAGE), vec![(a, PAGE)]);
|
||||
// A request for part of a page names those bytes alone.
|
||||
assert_eq!(shown_at(&pages, 0x4000, 0x3000), vec![(a + 0x4000, 0x3000)]);
|
||||
// Across two pages, shown at two addresses each: one run at each.
|
||||
assert_eq!(
|
||||
shown_at(&pages, PAGE + 1, PAGE),
|
||||
sorted(vec![(a + PAGE + 1, PAGE), (second + 1, PAGE)])
|
||||
);
|
||||
// A page unmapped in the middle of a view: the rest still shows.
|
||||
let middle = (a + PAGE) as *mut c_void;
|
||||
assert_eq!(XMemMapPhysicalPages(middle, 1, std::ptr::null()), middle);
|
||||
assert_eq!(
|
||||
shown_at(&pages, 0, 3 * PAGE),
|
||||
sorted(vec![(a, PAGE), (a + 2 * PAGE, PAGE), (second, 2 * PAGE)])
|
||||
);
|
||||
// Too few pages for the bytes: nothing (the write fails too).
|
||||
assert!(shown_at(&pages, 0, 3 * PAGE + 1).is_empty());
|
||||
for (at, n) in [(a, 3), (second, 2)] {
|
||||
let at = at as *mut c_void;
|
||||
assert_eq!(XMemMapPhysicalPages(at, n, std::ptr::null()), at);
|
||||
}
|
||||
assert!(shown_at(&pages, 0, 3 * PAGE).is_empty());
|
||||
assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_windows_cover_one_run_in_place() {
|
||||
let (a, b) = (allocate(3), allocate(1));
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Fingerprint of the translator's own source, for the shader cache key
|
||||
//! (`victory-gpu`'s `shader_cache`): a rebuilt executable whose translator did
|
||||
//! not change keeps its cached translations. Also lists every `VICTORY_*`
|
||||
//! switch the translator reads, whose values join the key at run time.
|
||||
//! Reads only this crate's `src` folder; writes nothing but cargo directives.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn files(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
files(&p, out);
|
||||
} else if p.extension().is_some_and(|x| x == "rs") {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// FNV-1a, 64 bits, two lanes with different offsets: a mismatch only costs
|
||||
/// a cache miss, so this need not be cryptographic.
|
||||
fn fnv(state: &mut [u64; 2], bytes: &[u8]) {
|
||||
for &b in bytes {
|
||||
for (i, s) in state.iter_mut().enumerate() {
|
||||
*s ^= u64::from(b) ^ (i as u64 * 0x9e);
|
||||
*s = s.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||
println!("cargo:rerun-if-changed=src");
|
||||
println!("cargo:rerun-if-changed=Cargo.toml");
|
||||
let mut list = Vec::new();
|
||||
files(&src, &mut list);
|
||||
list.sort();
|
||||
let mut state = [0xcbf2_9ce4_8422_2325u64, 0x8422_2325_cbf2_9ce4u64];
|
||||
let mut switches = std::collections::BTreeSet::new();
|
||||
for p in &list {
|
||||
let rel = p.strip_prefix(&src).unwrap_or(p).to_string_lossy().replace('\\', "/");
|
||||
let text = std::fs::read(p).unwrap_or_default();
|
||||
fnv(&mut state, rel.as_bytes());
|
||||
fnv(&mut state, &(text.len() as u64).to_le_bytes());
|
||||
fnv(&mut state, &text);
|
||||
let s = String::from_utf8_lossy(&text);
|
||||
let mut rest = &s[..];
|
||||
while let Some(at) = rest.find("\"VICTORY_") {
|
||||
let tail = &rest[at + 1..];
|
||||
let end = tail
|
||||
.find(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'))
|
||||
.unwrap_or(tail.len());
|
||||
if tail[end..].starts_with('"') {
|
||||
switches.insert(tail[..end].to_string());
|
||||
}
|
||||
rest = &tail[end..];
|
||||
}
|
||||
}
|
||||
println!("cargo:rustc-env=VICTORY_SHADER_SOURCE_HASH={:016x}{:016x}", state[0], state[1]);
|
||||
let joined: Vec<_> = switches.into_iter().collect();
|
||||
println!("cargo:rustc-env=VICTORY_SHADER_SWITCHES={}", joined.join(","));
|
||||
}
|
||||
@@ -188,6 +188,33 @@ pub fn shader_opt() -> u32 {
|
||||
*PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref()))
|
||||
}
|
||||
|
||||
/// Everything a translation depends on besides the container: the
|
||||
/// translator's own source (hashed at build time), the value of every
|
||||
/// `VICTORY_*` switch it reads, the host facts the device hands it (widest
|
||||
/// wave, view heap limit) and the settings above. The shader cache keys on
|
||||
/// this instead of on the whole executable, so a rebuild that leaves the
|
||||
/// translator alone keeps its translations. Call it after the device is made.
|
||||
pub fn translation_fingerprint() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(env!("VICTORY_SHADER_SOURCE_HASH").as_bytes());
|
||||
out.push(u8::from(cfg!(feature = "diagnostics")));
|
||||
out.push(u8::from(cfg!(debug_assertions)));
|
||||
for name in env!("VICTORY_SHADER_SWITCHES").split(',').filter(|n| !n.is_empty()) {
|
||||
out.extend_from_slice(name.as_bytes());
|
||||
out.push(b'=');
|
||||
if let Some(value) = std::env::var_os(name) {
|
||||
out.extend_from_slice(value.as_encoded_bytes());
|
||||
}
|
||||
out.push(0);
|
||||
}
|
||||
out.extend_from_slice(&lower::host_max_wave().to_le_bytes());
|
||||
out.extend_from_slice(&shader::view_heap_limit().to_le_bytes());
|
||||
out.extend_from_slice(&loop_limit().to_le_bytes());
|
||||
out.push(group_sync());
|
||||
out.extend_from_slice(&shader_opt().to_le_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// `VICTORY_SHADER_OPT`'s value; every pass when it is unset or
|
||||
/// unreadable. Pure, for testing.
|
||||
fn parse_shader_opt(value: Option<&str>) -> u32 {
|
||||
|
||||
Reference in new issue
Block a user