From b9f76aa5316671528a1c0f1df109fe864168d242 Mon Sep 17 00:00:00 2001 From: user Date: Sat, 28 Nov 2026 02:30:22 +0100 Subject: [PATCH 1/2] perf: faster BCPack, detiling, inflate, hashing, DSP CPU-side optimizations of the layer, each checked against the original code. IMPORTANT, how this was tested: the author of these changes does not own a copy of the game. Nothing here has been run with the game, and nothing has been run on Windows. Every number below comes from benchmarks on synthetic data that was made up for the purpose (textures, streams, impulse responses and memory journals), on Linux, one core of an Intel i7-13620H (AVX2, VAES, no AVX-512). Before merging, run `cargo test` on Windows. victory-gpu - watch.rs: the ranges asked ahead (`ahead`) were walked linearly by every `writes`, `asked`, `nothing_new` and `ask_more` call. They are now sorted, with a running maximum of the ends, and answered by binary search. 5,000 lookups: 7x faster with 50 ranges, 49x with 500, 173x with 2,000. In `ask_rest`, a range inside one asked just before it is not asked again. main's locking (only the pages asked about are held) is kept as it is. The equivalence test is in the patch. - AddressHash, already in the project, in place of SipHash in per-frame maps (draw.rs, descriptor/host.rs, texture.rs, and memory.rs, which is used only by the ray-tracing builder): lookups 3.7-4.4x faster (8-17 -> 2-5 ns). The frame saving is an estimate: the lookups a frame were not counted. - texture.rs `digest`: AES rounds (VAES on 256 bits, AES-NI fallback, the same value either way; the old code is used without AES): 2.4-3.3x faster on data in cache, 1.5-1.7x from RAM. 4,000 variants (zero runs, swaps, single-bit flips) all distinct; a test checks that both paths agree. victory-hle - dstorage.rs `inflate`: libdeflate (C, MIT, whole-buffer decompressor) in place of main's reused zlib-rs state: 1.33-1.40x faster on meshes, text, already-packed and sparse data, in 64 KiB and 1 MiB chunks (measured against a reused, reset zlib-rs state; zlib-ng was slower than zlib-rs). All cases of the existing test hold, plus trailing bytes and a corrupt checksum. - dsp/convolve.rs, the DSP convolution, reworked: real-input FFTs (realfft) instead of a 2048-point complex FFT (8x faster); the sum over partitions register-blocked with AVX2+FMA (32 bins' sums kept in registers while every partition goes by, 1.3-2.1x faster); spectrum rows 64-byte aligned (misaligned rows measured 1.2-1.4x slower; a [bin][partition] layout measured 6-12x slower). A whole block is 1.6-7.6x faster, depending on the length of the response. Output within about 1e-6 of the original; existing tests plus new tests for the vector sum and against the original. victory-formats - bcpack.rs: BC7 block rebuilding with a compile-time 256-entry nibble table, anchors as a bit mask, and a bit writer on two u64 words instead of variable u128 shifts: 1.6x faster (150 -> 94 ns a block, all 8 BC7 modes, output identical on 80,000 random blocks). - bcpack.rs `lanes`: each round in two passes, every lane's step first (they are independent, so the core overlaps them on several ALUs), then the byte hand-out in lane order. BC7 end to end 1.11x; about 1.3x for all of BC7 together with the item above. - texture.rs: detiling of standard (S) modes as a transpose. A 256-byte micro tile is a column-major matrix of 16-byte cells; each micro tile is transposed in registers (vperm2i128) and written as whole 64-byte rows (two micro tiles side by side for 4-byte elements), with streaming stores where the destination is 64-byte aligned, as D3D12 upload memory is. The cell rule is checked against Layout::offset; everything else, the pipe and bank XOR modes included (their addresses are not a row's part plus a column's), takes the general path. Against main's general path, 2048^2 textures: 64KB_S 1.73x (8-byte elements), 2.20x (16), 2.46x (4); 4KB_S 1.92x; D modes unchanged. Tests compare it with the general path over 6 swizzle modes, 6 formats, odd and even sizes, mips, slices and aligned and unaligned destinations, and over the XOR modes of both consoles into aligned rows. Checks: victory-formats tests pass on Linux (58, every run of 25 in a row). victory-gpu and victory-hle no longer build on Linux, so the whole workspace was checked with cargo clippy --workspace --all-targets [--all-features] --locked --target x86_64-pc-windows-msvc: no errors, and no warnings in the files this changes. libdeflate's C build was stubbed for that Linux check, so it still needs a real MSVC build. Measured and left out: AVX2 16-lane rANS (0.94-1.10x), 4x-unrolled safe_merge assembly (0.85x on realistic change rates), target-cpu=x86-64-v3 and LTO (no gain on these kernels). Changes to the shader translator (FxHash maps, a dominance-based value table in the DXIL optimiser) were dropped: against main at d4b5d51 they measured no gain, with identical output. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 101 +++++++ Cargo.toml | 5 + crates/victory-formats/src/bcpack.rs | 91 +++++-- crates/victory-formats/src/texture.rs | 228 ++++++++++++++++ crates/victory-gpu/src/descriptor/host.rs | 8 +- crates/victory-gpu/src/draw.rs | 4 +- crates/victory-gpu/src/memory.rs | 18 +- crates/victory-gpu/src/texture.rs | 130 ++++++++- crates/victory-gpu/src/watch.rs | 122 ++++++++- crates/victory-hle/Cargo.toml | 2 + .../victory-hle/src/modules/dsp/convolve.rs | 251 +++++++++++++++--- crates/victory-hle/src/modules/dstorage.rs | 50 +--- 12 files changed, 882 insertions(+), 128 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9a656d8bf..1300a05ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -73,6 +73,12 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "bitflags" version = "2.13.2" @@ -248,6 +254,24 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libdeflate-sys" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7870e5fbd2766179a937c725fb11f4ca0ef025d982beb61bd3ce755425bd19c" +dependencies = [ + "cc", +] + +[[package]] +name = "libdeflater" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cbb8285d2e2bd4b8d4155840ae81929354b4ba0d7b3c272c84761ffa2141e1f" +dependencies = [ + "libdeflate-sys", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -284,6 +308,33 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "object" version = "0.41.0" @@ -317,6 +368,15 @@ version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" +[[package]] +name = "primal-check" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08" +dependencies = [ + "num-integer", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -341,6 +401,15 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "realfft" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "538895ccf2006b473aafbe8d72770e21038961ab67aae34f3c577485fc703a7d" +dependencies = [ + "rustfft", +] + [[package]] name = "regex-automata" version = "0.4.19" @@ -358,6 +427,20 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" +[[package]] +name = "rustfft" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "primal-check", + "strength_reduce", + "transpose", +] + [[package]] name = "rustix" version = "1.1.6" @@ -440,6 +523,12 @@ version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + [[package]] name = "strsim" version = "0.11.1" @@ -610,6 +699,16 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "transpose" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e" +dependencies = [ + "num-integer", + "strength_reduce", +] + [[package]] name = "unicode-ident" version = "1.0.27" @@ -690,7 +789,9 @@ dependencies = [ name = "victory-hle" version = "0.1.0" dependencies = [ + "libdeflater", "opus-pure", + "realfft", "tempfile", "tracing", "victory-formats", diff --git a/Cargo.toml b/Cargo.toml index 4e21b692d..c9d1762b3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,11 @@ blake3 = "1.8.7" memchr = "2.8.3" # SIMD-accelerated pure-Rust zlib/deflate (Zlib license, runtime AVX2/SSE4.2 dispatch). zlib-rs = { version = "0.6.8", default-features = false, features = ["std"] } +# libdeflate (C, MIT): whole-buffer zlib inflate for DirectStorage requests, +# 1.3-1.4x zlib-rs's speed on every kind of data measured. +libdeflater = "1.26" +# Real-input FFTs (pure Rust, MIT/Apache-2.0) for the DSP's convolutions. +realfft = "3.5" walkdir = "2.5.1" tempfile = "3.27.0" # Opus decoding for the console's audio decoder (BSD-3-Clause, pure Rust). diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs index 11dada0f9..bf2f8100c 100644 --- a/crates/victory-formats/src/bcpack.rs +++ b/crates/victory-formats/src/bcpack.rs @@ -427,12 +427,18 @@ fn lanes( let mut at = 0; while pos < blocks * per { let (mut taken, mut moved) = (0, false); - for (j, lane) in lanes.iter_mut().enumerate() { - let bit = 1 << j; - let before = taken; + // The lanes' steps first: each depends on its own lane alone, so the + // processor runs several lanes' decoding at once; the bytes, which go + // to the lanes in order, after. (One loop of both made every lane wait + // for the one before it: 1.35 times as long, measured.) + for lane in lanes.iter_mut() { if !lane.stalled { lane.step(t)?; } + } + for (j, lane) in lanes.iter_mut().enumerate() { + let bit = 1 << j; + let before = taken; let waiting = lane.out.is_some() && done & bit != 0; if lane.need && !waiting && taken < ROUND_BYTES { // Past the end nothing arrives; in a valid stream only finished lanes ask there. @@ -660,11 +666,36 @@ fn bc5_pack(v: &Plain, out: &mut [u8]) { bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..], &mut out[8..]); } -/// A byte's even and odd bits as two zigzag-coded 4-bit residuals. +/// A byte's even and odd bits as two zigzag-coded 4-bit residuals: from a +/// table made at compile time (the bit loops ran 32 times a block). +const NIBBLES: [[i16; 2]; 256] = { + let mut t = [[0i16; 2]; 256]; + let mut b = 0; + while b < 256 { + let mut halves = [0u8; 2]; + let mut h = 0; + while h < 2 { + let v = (b >> h) as u8; + let mut acc = 0u8; + let mut k = 0; + while k < 4 { + acc |= (v >> (2 * k) & 1) << k; + k += 1; + } + halves[h] = acc; + h += 1; + } + let z0 = (halves[0] >> 1) as i16 ^ -((halves[0] & 1) as i16); + let z1 = (halves[1] >> 1) as i16 ^ -((halves[1] & 1) as i16); + t[b] = [z0, z1]; + b += 1; + } + t +}; + +#[inline] fn nibbles(b: u8, odd_first: bool) -> [i16; 2] { - let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k); - let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); - let (even, odd) = (z(half(b)), z(half(b >> 1))); + let [even, odd] = NIBBLES[usize::from(b)]; if odd_first { [odd, even] } else { [even, odd] } } @@ -682,20 +713,40 @@ fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 { if bits == 0 { 0 } else { sum >> (16 - bits) } } -/// Little-endian bit writer for one 128-bit block. +/// Little-endian bit writer for one 128-bit block, on two 64-bit words +/// (shifts of a u128 by a variable amount took several instructions and a +/// branch each). #[derive(Default)] struct Bits { - v: u128, + lo: u64, + hi: u64, at: u32, } impl Bits { + #[inline] fn put(&mut self, value: u64, n: u32) { if n > 0 && self.at < 128 { - self.v |= (u128::from(value) & ((1u128 << n) - 1)) << self.at; + let v = if n >= 64 { value } else { value & ((1u64 << n) - 1) }; + let at = self.at; + if at < 64 { + self.lo |= v << at; + if at + n > 64 { + self.hi |= v >> (64 - at); + } + } else { + self.hi |= v << (at - 64); + } } self.at += n; } + + fn bytes(&self) -> [u8; 16] { + let mut out = [0u8; 16]; + out[..8].copy_from_slice(&self.lo.to_le_bytes()); + out[8..].copy_from_slice(&self.hi.to_le_bytes()); + out + } } // BC7. @@ -895,15 +946,15 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)), _ => {} } - let anchors: &[u8] = match subsets { - 2 => &[0, ANCHOR2[part]], - 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], - _ => &[0], + let anchors: u16 = match subsets { + 2 => 1 | 1 << ANCHOR2[part], + 3 => 1 | 1 << ANCHOR3A[part] | 1 << ANCHOR3B[part], + _ => 1, }; let mut indices = |set: usize| { - let bits = ix.bits[set]; + let bits = u32::from(ix.bits[set]); for (p, &v) in ix.ix[set].iter().enumerate() { - let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8))); + let n = bits - u32::from(anchors >> p & 1); w.put(u64::from(v as u16), n); } }; @@ -918,7 +969,7 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { } _ => indices(0), } - out.copy_from_slice(&w.v.to_le_bytes()); + out.copy_from_slice(&w.bytes()); } // BC6H. @@ -1165,7 +1216,7 @@ fn bc6<'a>( let v = (v as u16).wrapping_add(1 << (bits - 1)); w.put(v.into(), u32::from(bits) - u32::from(short)); } - block.copy_from_slice(&w.v.to_le_bytes()); + block.copy_from_slice(&w.bytes()); } Ok(()) } @@ -1347,7 +1398,7 @@ mod tests { } w.put(1, 1); w.put(1, 1); - assert_eq!(dst, w.v.to_le_bytes()); + assert_eq!(dst, w.bytes()); } #[test] @@ -1442,7 +1493,7 @@ mod tests { ] { w.put(v, n); } - assert_eq!(dst, w.v.to_le_bytes(), "mode {mode} rot 1"); + assert_eq!(dst, w.bytes(), "mode {mode} rot 1"); } } diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 5c6963e39..ad9970519 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -1012,9 +1012,88 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { + #[cfg(target_arch = "x86_64")] + if self.detile_transposed(tiled, mip, slice, linear, row_pitch) { + return Ok(()); + } self.walk::(tiled, linear, mip, slice, row_pitch, depth_pitch) } + /// [`Layout::detile`] of a 2D mip by micro tiles, where it can be. + /// + /// A standard micro tile (256 bytes) is a matrix of 16-byte cells stored + /// by columns: cell (column c, row y) at `(c * rows + y) * 16`, 4 x 4 + /// cells for elements of 8 and 16 bytes, 2 x 8 for 4 bytes. So a micro + /// tile is detiled as a transpose: its cells are read two rows at a time + /// (32 bytes), recombined in registers, and stored as rows of 64 bytes, + /// a whole cache line each (two micro tiles side by side for 4-byte + /// elements), with streaming stores where the rows are 64-byte aligned + /// (the upload memory this goes to is write-combined). The rule is + /// checked against [`Layout::offset`] for every element of the first + /// micro tile; whatever does not fit goes the general way. 1.6-2.6 times + /// the general way, near a plain copy (measured, 4 KiB and 64 KiB S + /// modes). False if not done (nothing was written then). + #[cfg(target_arch = "x86_64")] + fn detile_transposed(&self, tiled: &[u8], mip: u32, slice: u32, linear: &mut [u8], row_pitch: usize) -> bool { + let Some(m) = self.mips.get(mip as usize) else { return false }; + let n = self.desc.element_bytes as usize; + let (cols, rows) = match n { + 16 | 8 => (4usize, 4usize), + 4 => (2, 8), + _ => return false, + }; + let per_cell = 16 / n; + let (mw, mh) = ((cols * per_cell) as u32, rows as u32); + let worth = m.width as usize * m.height as usize * n >= 16 << 10; + if !worth + || m.tail.is_some() + || self.desc.dimension != Dimension::Tex2d + || self.desc.swizzle == Swizzle::LINEAR + // (The XOR modes mix a micro tile's column into its row's part + // of the address: not a row's part plus a column's.) + || self.xor.is_some() + || !self.addressable() + || slice >= self.slices + || !m.width.is_multiple_of(mw) + || !m.height.is_multiple_of(mh) + || row_pitch < m.width as usize * n + || !std::arch::is_x86_feature_detected!("avx2") + { + return false; + } + let at = |x: u32, y: u32| self.offset(mip, x, y, slice).ok().map(|v| v as usize); + let Some(origin) = at(0, 0) else { return false }; + for y in 0..mh { + for x in 0..mw { + let (c, e) = (x as usize / per_cell, x as usize % per_cell); + if at(x, y) != Some(origin + (c * rows + y as usize) * 16 + e * n) { + return false; + } + } + } + // An address is the row's part plus the column's ([`Layout::row`], + // [`Layout::column`]): per row and column of micro tiles. + let row_at: Option> = (0..m.height / mh).map(|ty| at(0, ty * mh)).collect(); + let col_at: Option> = (0..m.width / mw).map(|tx| at(tx * mw, 0).and_then(|v| v.checked_sub(origin))).collect(); + let (Some(row_at), Some(col_at)) = (row_at, col_at) else { return false }; + let last_src = row_at.iter().max().copied().unwrap_or(0) + col_at.iter().max().copied().unwrap_or(0) + 256; + let last_dst = (m.height as usize - 1) * row_pitch + m.width as usize * n; + if last_src > tiled.len() || last_dst > linear.len() { + return false; + } + let stream = (linear.as_ptr() as usize).is_multiple_of(64) && row_pitch.is_multiple_of(64); + let pairs = cols == 2 && col_at.len().is_multiple_of(2); + // Rows of 64 bytes not on cache lines gained nothing over the general + // way (measured): only where they can be streamed. + if cols == 4 && !stream { + return false; + } + // SAFETY: AVX2 is there; every micro tile read lies below `last_src` + // and every row written below `last_dst`, both checked above. + unsafe { transpose_tiles(tiled.as_ptr(), linear.as_mut_ptr(), row_pitch, &row_at, &col_at, rows, cols, mh as usize, stream, pairs) }; + true + } + /// The reverse of [`Layout::detile`]: linear rows into tiled memory. pub fn tile( &self, @@ -1281,6 +1360,88 @@ fn copy_runs( } } +/// The micro tiles of [`Layout::detile_transposed`]: for each row and column +/// of micro tiles, the cells at `src + row_at + col_at` to the rows at +/// `dst + (row * tile_rows) * pitch + column * cols * 16`. +/// +/// # Safety +/// AVX2; the reads and writes inside the buffers (the caller checks them); +/// with `stream`, `dst` and `pitch` multiples of 64. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +#[allow(clippy::too_many_arguments)] +unsafe fn transpose_tiles( + src: *const u8, + dst: *mut u8, + pitch: usize, + row_at: &[usize], + col_at: &[usize], + rows: usize, + cols: usize, + tile_rows: usize, + stream: bool, + pairs: bool, +) { + use std::arch::x86_64::*; + let seg = cols * 16; + // SAFETY: the caller's. + unsafe { + let put = |at: *mut u8, v: __m256i| { + if stream { + _mm256_stream_si256(at.cast(), v) + } else { + _mm256_storeu_si256(at.cast(), v) + } + }; + for (ty, &row) in row_at.iter().enumerate() { + let out = dst.add(ty * tile_rows * pitch); + if cols == 4 { + for (tx, &col) in col_at.iter().enumerate() { + let (s, d) = (src.add(row + col), out.add(tx * seg)); + for y in (0..4).step_by(2) { + let l0 = _mm256_loadu_si256(s.add(y * 16).cast()); + let l1 = _mm256_loadu_si256(s.add((4 + y) * 16).cast()); + let l2 = _mm256_loadu_si256(s.add((8 + y) * 16).cast()); + let l3 = _mm256_loadu_si256(s.add((12 + y) * 16).cast()); + let (r0, r1) = (d.add(y * pitch), d.add((y + 1) * pitch)); + put(r0, _mm256_permute2x128_si256::<0x20>(l0, l1)); + put(r0.add(32), _mm256_permute2x128_si256::<0x20>(l2, l3)); + put(r1, _mm256_permute2x128_si256::<0x31>(l0, l1)); + put(r1.add(32), _mm256_permute2x128_si256::<0x31>(l2, l3)); + } + } + } else if pairs { + // two micro tiles side by side: a row of each is 64 bytes, one line + for tx in (0..col_at.len()).step_by(2) { + let (a, b, d) = (src.add(row + col_at[tx]), src.add(row + col_at[tx + 1]), out.add(tx * seg)); + for y in (0..rows).step_by(2) { + let (a0, a1) = (_mm256_loadu_si256(a.add(y * 16).cast()), _mm256_loadu_si256(a.add((rows + y) * 16).cast())); + let (b0, b1) = (_mm256_loadu_si256(b.add(y * 16).cast()), _mm256_loadu_si256(b.add((rows + y) * 16).cast())); + let (r0, r1) = (d.add(y * pitch), d.add((y + 1) * pitch)); + put(r0, _mm256_permute2x128_si256::<0x20>(a0, a1)); + put(r0.add(32), _mm256_permute2x128_si256::<0x20>(b0, b1)); + put(r1, _mm256_permute2x128_si256::<0x31>(a0, a1)); + put(r1.add(32), _mm256_permute2x128_si256::<0x31>(b0, b1)); + } + } + } else { + for (tx, &col) in col_at.iter().enumerate() { + let (s, d) = (src.add(row + col), out.add(tx * seg)); + for y in (0..rows).step_by(2) { + let (l0, l1) = (_mm256_loadu_si256(s.add(y * 16).cast()), _mm256_loadu_si256(s.add((rows + y) * 16).cast())); + // half lines: no streaming + _mm256_storeu_si256(d.add(y * pitch).cast(), _mm256_permute2x128_si256::<0x20>(l0, l1)); + _mm256_storeu_si256(d.add((y + 1) * pitch).cast(), _mm256_permute2x128_si256::<0x31>(l0, l1)); + } + } + } + } + if stream { + _mm_sfence(); + } + } +} + /// What a DXGI format stores per element: bytes, texels per element side /// (4 for block compression), and whether its stencil is a second plane /// (the GPU keeps depth and stencil apart). @@ -1405,6 +1566,73 @@ impl Texture { } } +#[cfg(test)] +mod transpose_tests { + use super::*; + + /// The micro tile way writes what the general way writes, for every + /// standard and display mode, element size, odd and even size, mip and + /// slice; aligned and unaligned destinations. + #[test] + fn transposed_detiling_is_the_general_one() { + let modes = [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 swizzle in modes { + for (n, block) in [(4u32, 1u32), (8, 1), (8, 4), (16, 4), (16, 1), (2, 1)] { + for (w, h, mips, depth) in [(256u32, 256u32, 1u32, 1u32), (512, 128, 4, 2), (1000, 600, 3, 1), (2048, 64, 1, 1)] { + let d = Desc { dimension: Dimension::Tex2d, width: w, height: h, depth, mips, element_bytes: n, block, samples: 1, swizzle }; + let Ok(l) = Layout::new(&d) else { continue }; + let tiled: Vec = (0..l.size as usize).map(|i| (i.wrapping_mul(0x9e37_79b9) >> 11) as u8).collect(); + for slice in 0..depth { + for mip in 0..mips { + let m = &l.mips[mip as usize]; + let pitch = (m.width as usize * n as usize).next_multiple_of(256); + let len = pitch * m.height as usize; + for skew in [0usize, 16] { + let mut a = vec![0u8; len + 128]; + let mut b = vec![0u8; len + 128]; + let off = a.as_ptr().align_offset(64) + skew; + let offb = b.as_ptr().align_offset(64) + skew; + l.walk::(&tiled, &mut a[off..off + len], mip, slice, pitch, len).unwrap(); + l.detile(&tiled, mip, slice, &mut b[offb..offb + len], pitch, len).unwrap(); + let wb = m.width as usize * n as usize; + for y in 0..m.height as usize { + assert_eq!(a[off + y * pitch..][..wb], b[offb + y * pitch..][..wb], "{swizzle:?} n {n} {w}x{h} mip {mip} slice {slice} row {y} skew {skew}"); + } + } + } + } + } + } + } + } + + /// The XOR modes are not a row's part plus a column's: they take the + /// general way, and give what it gives, into cache-line aligned rows too. + #[test] + fn xor_modes_are_detiled_the_general_way() { + for swizzle in [Swizzle::SW_4KB_S_X, Swizzle::SW_64KB_S_X, Swizzle::SW_64KB_D_X] { + for config in [PipeConfig::Pipes8Packers4, PipeConfig::Pipes32Packers8] { + for (n, w, h) in [(4u32, 512u32, 256u32), (8, 512, 256), (16, 512, 256), (8, 40, 300), (4, 64, 512), (16, 96, 96)] { + let d = Desc { dimension: Dimension::Tex2d, width: w, height: h, depth: 1, mips: 1, element_bytes: n, block: 1, samples: 1, swizzle }; + let Ok(mut l) = Layout::new(&d) else { continue }; + l.configure_xor(config); + if !l.addressable() { + continue; + } + let tiled: Vec = (0..l.size as usize).map(|i| (i.wrapping_mul(0x9e37_79b9) >> 11) as u8).collect(); + let pitch = w as usize * n as usize; + let len = pitch * h as usize; + let (mut a, mut b) = (vec![0u8; len + 64], vec![0u8; len + 64]); + let (off, offb) = (a.as_ptr().align_offset(64), b.as_ptr().align_offset(64)); + l.walk::(&tiled, &mut a[off..off + len], 0, 0, pitch, len).unwrap(); + l.detile(&tiled, 0, 0, &mut b[offb..offb + len], pitch, len).unwrap(); + assert!(a[off..off + len] == b[offb..offb + len], "{swizzle:?} {config:?} n {n} {w}x{h}"); + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index f398f1bd4..79226bb0f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -163,7 +163,7 @@ pub(crate) struct HostHeap { /// The slots made from a texture whose memory was found away, with what /// they were made from and when that was /// ([`HostHeap::texture_slot_gone`]). - away: Mutex>, + away: Mutex>>, /// The host resource each slot views, held while the slot does: shaders /// index heaps directly, so a slot the title has not rewritten since it /// released the resource may still be read, and a freed host resource @@ -369,7 +369,7 @@ pub(crate) fn show_new_later() -> bool { /// Slots [`show_new_later`] holds back now: heap, slot, record. (A slot /// held back is held once, not again at each draw that reads it.) -static NEW_PENDING: std::sync::LazyLock>> = +static NEW_PENDING: std::sync::LazyLock>>> = std::sync::LazyLock::new(Default::default); /// Slots held back by [`show_new_later`] since the start. @@ -655,10 +655,10 @@ pub(crate) struct Spans { /// When a newer view makes an older one stale. rule: Rule, by_start: std::collections::BTreeMap)>, - by_slot: std::collections::HashMap, + by_slot: std::collections::HashMap>, /// The level each slot's view starts at, and where what it is read from /// ends ([`Spans::shows`]). - first: std::collections::HashMap, + first: std::collections::HashMap>, /// 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). diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 824b3beff..65fb9a8d3 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -823,7 +823,7 @@ pub(crate) struct BufferSweep { passes: u64, ranges: HeapRanges>, // Last refresh frame and covered interval for throttled, unwatched copies. - unwatched: std::collections::HashMap, + unwatched: std::collections::HashMap>, last_spans: usize, } @@ -1513,7 +1513,7 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho }); let mut found = Vec::with_capacity(spans.len()); if every > 1 { - let mut next_unwatched = std::collections::HashMap::with_capacity(unwatched.len()); + let mut next_unwatched = std::collections::HashMap::with_capacity_and_hasher(unwatched.len(), Default::default()); for (_, (shadow, from, to)) in spans { if shadow.unwatched() { let id = shadow.id(); diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 5a4a0faf1..13b11fb7a 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -71,7 +71,11 @@ //! shortcut: pages a list does not name are looked at again in turn, over //! [`SWEEP`] frames. -use std::collections::{HashMap, HashSet, VecDeque}; +/// Our own tables of addresses and page numbers: hashed by [`crate::host::AddressHash`] +/// (SipHash, the standard one, costs some five times as much a look). +type HashMap = std::collections::HashMap>; +type HashSet = std::collections::HashSet>; +use std::collections::VecDeque; use std::sync::{Arc, Mutex, OnceLock}; use victory_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY}; @@ -200,7 +204,7 @@ struct Memory { /// Places of pages that are free: the copy, the address in the arena. free: Vec<(usize, usize)>, /// Copies of title buffers the builder may store in. - open: std::collections::HashSet, + open: HashSet, /// Pages still held after a fault. fault_held: Faults, /// Per host view heap (by address): the first slot of its run, and how @@ -209,7 +213,7 @@ struct Memory { /// The frame the faults were last read in. frame: u64, /// Pages asked for this frame that are not the title's memory. - refused: std::collections::HashSet, + refused: HashSet, stats: Stats, #[cfg(feature = "diagnostics")] dump: dump::Dump, @@ -319,19 +323,19 @@ impl Memory { directory: (entries as *mut u32, directory), faults: (faults, data.cast::(), gpu), copies: Vec::new(), - numbers: HashMap::new(), + numbers: HashMap::default(), arenas: Vec::new(), - pages: HashMap::new(), + pages: HashMap::default(), order: Vec::new(), sweep: 0, windows: 0, - packed: HashMap::new(), + packed: HashMap::default(), packed_order: Vec::new(), packed_sweep: 0, free: Vec::new(), open: Default::default(), fault_held: Faults::default(), - heaps: HashMap::new(), + heaps: HashMap::default(), frame: u64::MAX, refused: Default::default(), stats: Stats::default(), diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 03b4dcbf0..dc103bb86 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -17,7 +17,8 @@ pub(crate) mod ahead; -use std::collections::HashMap; +/// Tables by our own addresses: hashed by [`crate::host::AddressHash`]. +type HashMap = std::collections::HashMap>; use std::sync::{Arc, Mutex}; use windows::Win32::Graphics::Direct3D12::*; @@ -251,7 +252,7 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { let Some(host) = host() else { return false }; let through = { let mut map = THROUGH.lock().unwrap_or_else(|e| e.into_inner()); - let map = map.get_or_insert_with(HashMap::new); + let map = map.get_or_insert_with(HashMap::default); match map.get(&(placed as usize)) { Some(through) => through.clone(), None => { @@ -643,7 +644,7 @@ pub(crate) fn let_go_staging(idle_ms: u64) -> (u64, u64) { /// Textures the host GPU wrote by a copy or resolve: their contents are on /// the host, not in title memory, which stays as it was. -static HOST_WRITTEN: Mutex>> = Mutex::new(None); +static HOST_WRITTEN: Mutex>>> = Mutex::new(None); /// A host copy or resolve writes `resource`. pub(crate) fn host_written(resource: This) { @@ -778,6 +779,115 @@ fn once() -> bool { /// cryptographic one, which took 0.27 ms a megabyte, four times the detiling /// it was to spare; nobody makes up textures to collide.) pub(crate) fn digest(bytes: &[u8]) -> Digest { + digest_aes(bytes).map_or_else(|| digest_plain(bytes), Digest) +} + +/// Round keys of the AES digest (any fixed values do). +const AES_KEYS: [u64; 4] = [0xbe4b_a423_396c_feb8, 0x1cad_21f7_2c81_017c, 0xdb97_9083_e96d_d4de, 0x1f67_b3b7_a4a4_4072]; + +/// [`digest`] with AES rounds: eight 16-byte lanes, each taking 16 bytes of +/// every 128 through one round (`aesenc` of the lane and the bytes), then +/// folded with the length. Some four times the speed of the multiplications +/// it replaces where the bytes are in the cache (a copy just made). Two of +/// the lanes a VAES instruction when the processor has it, else one an +/// AES-NI instruction each: the same digest either way. +fn digest_aes(bytes: &[u8]) -> Option { + #[cfg(target_arch = "x86_64")] + { + if std::arch::is_x86_feature_detected!("vaes") && std::arch::is_x86_feature_detected!("avx2") { + // SAFETY: the features are there. + return Some(unsafe { digest_vaes(bytes) }); + } + if std::arch::is_x86_feature_detected!("aes") { + // SAFETY: the feature is there. + return Some(unsafe { digest_aesni(bytes) }); + } + } + None +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2,vaes,aes")] +// The VAES intrinsics are stable from Rust 1.89; the toolchain is pinned to a +// later one (`rust-toolchain.toml`). +#[allow(clippy::incompatible_msrv)] +unsafe fn digest_vaes(bytes: &[u8]) -> u128 { + use std::arch::x86_64::*; + // SAFETY: loads of 32 bytes inside `bytes` or a local block. + unsafe { + let k = _mm256_loadu_si256(AES_KEYS.as_ptr().cast()); + let lane = |i: i64| _mm256_xor_si256(k, _mm256_set_epi64x(0, 2 * i + 1, 0, 2 * i)); + let mut h = [lane(0), lane(1), lane(2), lane(3)]; + let blocks = bytes.chunks_exact(128); + let rest = blocks.remainder(); + for block in blocks { + let p = block.as_ptr(); + for (i, h) in h.iter_mut().enumerate() { + *h = _mm256_aesenc_epi128(_mm256_xor_si256(*h, _mm256_loadu_si256(p.add(32 * i).cast())), k); + } + } + let mut last = [0u8; 128]; + last[..rest.len()].copy_from_slice(rest); + for (i, h) in h.iter_mut().enumerate() { + *h = _mm256_aesenc_epi128(_mm256_xor_si256(*h, _mm256_loadu_si256(last.as_ptr().add(32 * i).cast())), k); + } + let mut out = [[0u8; 16]; 8]; + for (i, h) in h.iter().enumerate() { + _mm_storeu_si128(out[2 * i].as_mut_ptr().cast(), _mm256_castsi256_si128(*h)); + _mm_storeu_si128(out[2 * i + 1].as_mut_ptr().cast(), _mm256_extracti128_si256::<1>(*h)); + } + aes_finish(&out, bytes.len()) + } +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "aes,sse2")] +unsafe fn digest_aesni(bytes: &[u8]) -> u128 { + use std::arch::x86_64::*; + // SAFETY: loads of 16 bytes inside `bytes` or a local block. + unsafe { + let keys: [__m128i; 2] = [_mm_loadu_si128(AES_KEYS.as_ptr().cast()), _mm_loadu_si128(AES_KEYS.as_ptr().add(2).cast())]; + let mut h: [__m128i; 8] = std::array::from_fn(|i| _mm_xor_si128(keys[i % 2], _mm_set_epi64x(0, i as i64))); + let blocks = bytes.chunks_exact(128); + let rest = blocks.remainder(); + for block in blocks { + let p = block.as_ptr(); + for (i, h) in h.iter_mut().enumerate() { + *h = _mm_aesenc_si128(_mm_xor_si128(*h, _mm_loadu_si128(p.add(16 * i).cast())), keys[i % 2]); + } + } + let mut last = [0u8; 128]; + last[..rest.len()].copy_from_slice(rest); + for (i, h) in h.iter_mut().enumerate() { + *h = _mm_aesenc_si128(_mm_xor_si128(*h, _mm_loadu_si128(last.as_ptr().add(16 * i).cast())), keys[i % 2]); + } + let mut out = [[0u8; 16]; 8]; + for (i, h) in h.iter().enumerate() { + _mm_storeu_si128(out[i].as_mut_ptr().cast(), *h); + } + aes_finish(&out, bytes.len()) + } +} + +/// The eight lanes and the length, folded to 128 bits (folded products, as +/// [`digest`] ends). +fn aes_finish(lanes: &[[u8; 16]; 8], len: usize) -> u128 { + let fold = |a: u64, b: u64| { + let p = u128::from(a) * u128::from(b); + p as u64 ^ (p >> 64) as u64 + }; + let w: Vec = lanes.iter().flat_map(|l| [u64::from_le_bytes(l[..8].try_into().unwrap_or_default()), u64::from_le_bytes(l[8..].try_into().unwrap_or_default())]).collect(); + let len = len as u64; + let (mut lo, mut hi) = (0x9e37_79b9_7f4a_7c15u64 ^ len, 0xc2b2_ae3d_27d4_eb4fu64 ^ len.rotate_left(29)); + for pair in w.chunks_exact(2) { + lo = fold(lo ^ pair[0], pair[1] ^ 0xa076_1d64_78bd_642f).wrapping_add(lo.rotate_left(23)); + hi = fold(hi ^ pair[1], pair[0] ^ 0xe703_7ed1_a0b4_28db).wrapping_add(hi.rotate_left(41)); + } + u128::from(lo) << 64 | u128::from(hi) +} + +/// [`digest`] without AES instructions. +fn digest_plain(bytes: &[u8]) -> Digest { const K: [u64; 8] = [ 0xa076_1d64_78bd_642f, 0xe703_7ed1_a0b4_28db, @@ -2394,7 +2504,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O // 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); + let map = map.get_or_insert_with(HashMap::default); if let Some(s) = map.get(&(resource as usize)) && s.first <= first.max(copy.base) && s.serial == copy.serial @@ -2860,6 +2970,18 @@ mod allocation_costs { /// The digest tells every length and every changed byte apart, zeros /// among them. + #[test] + fn the_aes_digest_is_the_same_on_both_paths() { + #[cfg(target_arch = "x86_64")] + if std::arch::is_x86_feature_detected!("vaes") && std::arch::is_x86_feature_detected!("aes") { + let bytes: Vec = (0..70_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); + for n in (0..300).chain([4096, 65_536, 65_537, 70_000]) { + // SAFETY: the features are there. + assert_eq!(unsafe { super::digest_vaes(&bytes[..n]) }, unsafe { super::digest_aesni(&bytes[..n]) }, "{n} bytes"); + } + } + } + #[test] fn a_digest_tells_bytes_apart() { use super::digest; diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 14bad641a..adcbb0ecc 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -202,7 +202,7 @@ struct Journal { /// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`]) /// and the asking that did: `writes` answers for a range inside one /// from the journal, without another kernel call. - ahead: Vec<(usize, usize)>, + ahead: Ahead, ahead_asked: u64, /// The ahead asking stands for a whole submission ([`ask_once`]): no /// other ahead asking is made, and `ahead` stays, until @@ -216,10 +216,65 @@ struct Journal { /// one lock for all of it those threads ran one at a time: 22 of 96 looks at /// the submitting thread, and one in six of those at the six threads beside /// it, found it waiting for that lock (run pooloff1). +/// The page ranges of an ahead asking, kept sorted by their first page with +/// the largest last page so far beside them: whether a range lies inside one +/// of them is a binary search ([`Ahead::holds`]), not a walk over all of them +/// at every `writes`, `asked` and `nothing_new` (thousands a frame). +#[derive(Clone)] +struct Ahead { + ranges: Vec<(usize, usize)>, + max_end: Vec, +} + +impl Ahead { + const fn new() -> Ahead { + Ahead { ranges: Vec::new(), max_end: Vec::new() } + } + + fn set(&mut self, mut ranges: Vec<(usize, usize)>) { + ranges.sort_unstable(); + let mut most = 0; + self.max_end = ranges.iter().map(|&(_, b)| { + most = most.max(b); + most + }).collect(); + self.ranges = ranges; + } + + fn clear(&mut self) { + self.ranges.clear(); + self.max_end.clear(); + } + + #[cfg(test)] + fn take(&mut self) -> Vec<(usize, usize)> { + self.max_end.clear(); + std::mem::take(&mut self.ranges) + } + + /// These ranges and `more`. + fn with(&self, more: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + let mut all = self.ranges.clone(); + all.extend(more); + all + } + + fn is_empty(&self) -> bool { + self.ranges.is_empty() + } + + /// Whether `[first, last)` lies inside one of the ranges: of those that + /// begin at or before `first`, the one that reaches furthest does. + fn holds(&self, first: usize, last: usize) -> bool { + let k = self.ranges.partition_point(|&(a, _)| a <= first); + k > 0 && self.max_end[k - 1] >= last + } +} + static JOURNAL: RwLock = RwLock::new(Journal { written: BTreeMap::new(), parts: std::collections::HashMap::with_hasher(std::hash::BuildHasherDefault::new()), - ahead: Vec::new(), + ahead: Ahead::new(), ahead_asked: 0, kept: false, }); @@ -526,7 +581,7 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { note_hot(&written); let mut j = journal_mut(); j.ahead_asked = next_asking(); - j.ahead = asked; + j.ahead.set(asked); let now = j.ahead_asked; for (page, parts) in written { j.note(page, parts, now); @@ -812,7 +867,7 @@ pub(crate) fn ask_more(ranges: &[(usize, usize)]) -> bool { // (Outside the journal's lock: `published` has locks of its own.) let all_held = ranges.iter().all(|&(start, end)| { let (first, last) = (start / PAGE, end.div_ceil(PAGE)); - start >= end || published(start, end) || held.iter().any(|&(a, b)| a <= first && last <= b) + start >= end || published(start, end) || held.holds(first, last) }); if all_held { return false; @@ -827,16 +882,21 @@ fn ask_rest(ranges: &[(usize, usize)]) { // (Read, not taken: holding only its own pages ([`hold_pages`]), this // asking lets other threads ask meanwhile, and the journal goes on // answering them for what `ask_ahead` asked.) - let mut ahead = journal().ahead.clone(); + let ahead = journal().ahead.clone(); // The ranges it asks about: those `ask_ahead` left, held until the // answers are in the journal. - let alone: Vec<(usize, usize)> = ranges + let mut alone: Vec<(usize, usize)> = ranges .iter() .filter(|&&(start, end)| start < end && !published(start, end)) .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE))) - .filter(|&(first, last)| !ahead.iter().any(|&(a, b)| a <= first && last <= b)) + .filter(|&(first, last)| !ahead.holds(first, last)) .collect(); let _held = Askings::hold_or_all(merged(alone.clone())); + // In order of their first page (the longest first of those that begin + // together): one inside another asked here is covered by that one, which + // began no later, so the largest end so far tells. + alone.sort_unstable_by_key(|&(first, last)| (first, std::cmp::Reverse(last))); + let (mut lone, mut reach) = (Vec::new(), 0usize); // `ask_ahead` leaves a range that lies alone to `writes`, which asks // once per flush: with one asking for the submission that was every // such range asked again at each of its 70 flushes (run 76: 2,300 @@ -846,14 +906,17 @@ fn ask_rest(ranges: &[(usize, usize)]) { // to ask about a range not held.) let mut written = Vec::new(); for (first, last) in alone { - if !ahead.iter().any(|&(a, b)| a <= first && last <= b) + if reach < last && !owned(first, last) && let Some(pages) = kernel_written(first, last) { written.extend(pages); - ahead.push((first, last)); + lone.push((first, last)); + reach = last; } } + let mut ahead = ahead; + ahead.set(ahead.with(lone)); note_hot(&written); let mut j = journal_mut(); // A number of its own, and the one this asking stands under: between @@ -940,7 +1003,7 @@ pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>) let (first, last) = (start / PAGE, end.div_ceil(PAGE)); let j = journal(); let of = |j: &Journal| j.written.range(first..last).map(|(&p, &w)| (p, w)).collect(); - if j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { + if j.ahead.holds(first, last) { return Some((j.ahead_asked, of(&j))); } // Its owner tells its writes: an asking of its own, with nothing asked. @@ -962,7 +1025,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let (first, last) = (start / PAGE, end.div_ceil(PAGE)); let of = |j: &Journal| -> Vec<(usize, u64)> { j.written.range(first..last).map(|(&p, &w)| (p, w)).collect() }; // Asked ahead with the submission's other ranges: the journal has it. - let ahead = |j: &Journal| j.ahead.iter().any(|&(a, b)| a <= first && last <= b).then(|| (j.ahead_asked, of(j))); + let ahead = |j: &Journal| j.ahead.holds(first, last).then(|| (j.ahead_asked, of(j))); if let Some(known) = ahead(&journal()) { return Some(known); } @@ -1052,7 +1115,7 @@ pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], } let known = known || owned(first, last); let j = journal(); - if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { + if !known && !j.ahead.holds(first, last) { return false; } let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else { @@ -3546,6 +3609,39 @@ pub(crate) mod test_books { } } +#[cfg(test)] +mod ahead_tests { + use super::Ahead; + + /// The binary search says what the walk over every range said. + #[test] + fn holds_as_a_walk_over_every_range_does() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as usize % n + }; + for count in [0usize, 1, 2, 7, 50, 400] { + let ranges: Vec<(usize, usize)> = (0..count).map(|_| { + let a = next(5_000); + (a, a + 1 + next(300)) + }).collect(); + let mut ahead = Ahead::new(); + ahead.set(ranges.clone()); + for _ in 0..4_000 { + let first = next(5_400); + let last = first + 1 + next(200); + let walk = ranges.iter().any(|&(a, b)| a <= first && last <= b); + assert_eq!(ahead.holds(first, last), walk, "{count} ranges, [{first}, {last})"); + } + assert_eq!(ahead.take().len(), count); + assert!(ahead.is_empty() && !ahead.holds(0, 1)); + } + } +} + #[cfg(test)] mod parts_tests { use super::*; @@ -3555,7 +3651,7 @@ mod parts_tests { let mut j = Journal { written: BTreeMap::new(), parts: std::collections::HashMap::with_hasher(std::hash::BuildHasherDefault::new()), - ahead: Vec::new(), + ahead: Ahead::new(), ahead_asked: 0, kept: false, }; diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index 8f4eb0898..eaa1df075 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -14,6 +14,8 @@ victory-pe.workspace = true victory-formats.workspace = true opus-pure.workspace = true zlib-rs.workspace = true +libdeflater.workspace = true +realfft.workspace = true tracing.workspace = true [target.'cfg(windows)'.dependencies] diff --git a/crates/victory-hle/src/modules/dsp/convolve.rs b/crates/victory-hle/src/modules/dsp/convolve.rs index ced4e8ca7..88fd51438 100644 --- a/crates/victory-hle/src/modules/dsp/convolve.rs +++ b/crates/victory-hle/src/modules/dsp/convolve.rs @@ -15,18 +15,36 @@ //! that block's part of the output k blocks later: each output block is the //! second half of IFFT(sum over k of X[t-k] * H[k]) / 2048. How the hardware //! scales its result is not known; `dsp::GAIN` makes up for it. +//! +//! Worked out for vectors (`VICTORY_DSP_CONVOLVE` as before): +//! - real-input FFTs (`realfft`: a 1024-point complex FFT and a twist), not a +//! 2048-point complex FFT of a signal whose imaginary half is all zeros: +//! eight times faster, measured; +//! - the spectra split (re / im), one row of 1024 bins per window, every row +//! 64-byte aligned (a whole number of cache lines, so no vector load is +//! split across two of them; misaligned rows were 1.2-1.4 times slower); +//! - the sum over windows register-blocked (with AVX2 and FMA): 32 bins' +//! sums stay in eight registers while the loop runs over every window, +//! instead of the sum being loaded and stored again for each window +//! (1.3-2 times faster). Bins are the vector lanes because they are what +//! lies contiguous; with windows contiguous instead ([bin][window]) the +//! same sum was six times slower. +//! +//! A block costs 1.7-6.5 times less than before (fewer windows: more). const N: usize = 2048; const B: usize = 1024; const TRAILER: u32 = 0xFFFF_ACE1; -/// A complex radix-2 FFT of 2048 points. +/// A complex radix-2 FFT of 2048 points (for [`layout`], the tests' builder). +#[cfg(test)] struct Fft { cos: Vec, sin: Vec, rev: Vec, } +#[cfg(test)] fn fft() -> &'static Fft { static FFT: std::sync::OnceLock = std::sync::OnceLock::new(); FFT.get_or_init(|| { @@ -42,6 +60,7 @@ fn fft() -> &'static Fft { }) } +#[cfg(test)] impl Fft { /// In place; `inverse` flips the sign of the exponent and does not scale. fn run(&self, re: &mut [f32; N], im: &mut [f32; N], inverse: bool) { @@ -73,19 +92,57 @@ impl Fft { } } +/// 64-byte aligned floats: rows of the spectra start on a cache line. +#[derive(Clone, Copy)] +#[repr(C, align(64))] +struct Line([f32; 16]); + +struct Aligned(Vec); + +impl Aligned { + fn zeros(floats: usize) -> Aligned { + Aligned(vec![Line([0.0; 16]); floats.div_ceil(16)]) + } + fn get(&self) -> &[f32] { + // SAFETY: `Line` is 16 floats with no padding. + unsafe { std::slice::from_raw_parts(self.0.as_ptr().cast(), self.0.len() * 16) } + } + fn get_mut(&mut self) -> &mut [f32] { + // SAFETY: as above. + unsafe { std::slice::from_raw_parts_mut(self.0.as_mut_ptr().cast(), self.0.len() * 16) } + } +} + +/// The real FFTs of 2048 points, forward and inverse, planned once. +fn plans() -> &'static (std::sync::Arc>, std::sync::Arc>) { + static PLANS: std::sync::OnceLock<(std::sync::Arc>, std::sync::Arc>)> = + std::sync::OnceLock::new(); + PLANS.get_or_init(|| { + let mut planner = realfft::RealFftPlanner::::new(); + (planner.plan_fft_forward(N), planner.plan_fft_inverse(N)) + }) +} + /// One mono convolution stream's state. pub(super) struct Convolver { - /// The response's windows: `parts` blocks of 1024 bins, split re/im. - h_re: Vec, - h_im: Vec, + /// The response's windows: `parts` rows of 1024 bins, split re/im. + h_re: Aligned, + h_im: Aligned, parts: usize, - /// The last `parts` input spectra, a ring; `head` is the newest. - x_re: Vec, - x_im: Vec, + /// The last `parts` input spectra, a ring of rows; `head` is the newest. + x_re: Aligned, + x_im: Aligned, head: usize, /// Input blocks in a row that were silent: once the ring holds only /// silence, the output is silence without any arithmetic. quiet: usize, + /// Per window, the ring row it meets this block (newest first). + rows: Vec, + y_re: Aligned, + y_im: Aligned, + time: Vec, + spectrum: Vec, + scratch: Vec, } impl Convolver { @@ -103,25 +160,33 @@ impl Convolver { blocks -= 1; } let parts = blocks.max(1); - let mut h_re = vec![0f32; parts * B]; - let mut h_im = vec![0f32; parts * B]; + let mut h_re = Aligned::zeros(parts * B); + let mut h_im = Aligned::zeros(parts * B); for k in 0..blocks { let block = &ir[k * N..(k + 1) * N]; for bin in 0..B { let (r, i) = (block[2 * bin], block[2 * bin + 1]); // a non-finite value is not response data; leave it out - h_re[k * B + bin] = if r.is_finite() { r } else { 0.0 }; - h_im[k * B + bin] = if i.is_finite() { i } else { 0.0 }; + h_re.get_mut()[k * B + bin] = if r.is_finite() { r } else { 0.0 }; + h_im.get_mut()[k * B + bin] = if i.is_finite() { i } else { 0.0 }; } } + let (forward, inverse) = plans(); + let scratch = forward.get_scratch_len().max(inverse.get_scratch_len()); Some(Self { h_re, h_im, parts, - x_re: vec![0f32; parts * B], - x_im: vec![0f32; parts * B], + x_re: Aligned::zeros(parts * B), + x_im: Aligned::zeros(parts * B), head: 0, quiet: usize::MAX, + rows: vec![0; parts], + y_re: Aligned::zeros(B), + y_im: Aligned::zeros(B), + time: vec![0.0; N], + spectrum: vec![Default::default(); B + 1], + scratch: vec![Default::default(); scratch], }) } @@ -131,50 +196,132 @@ impl Convolver { self.quiet = if silent { self.quiet.saturating_add(1) } else { 0 }; self.head = (self.head + 1) % self.parts; let slot = self.head * B; + let (forward, inverse) = plans(); if silent { - self.x_re[slot..slot + B].fill(0.0); - self.x_im[slot..slot + B].fill(0.0); + self.x_re.get_mut()[slot..slot + B].fill(0.0); + self.x_im.get_mut()[slot..slot + B].fill(0.0); if self.quiet >= self.parts { output.fill(0.0); return; } } else { - let mut re = [0f32; N]; - let mut im = [0f32; N]; - for (r, &v) in re.iter_mut().zip(input) { - *r = if v.is_finite() { v } else { 0.0 }; + for (t, &v) in self.time[..B].iter_mut().zip(input) { + *t = if v.is_finite() { v } else { 0.0 }; + } + self.time[B..].fill(0.0); + if forward.process_with_scratch(&mut self.time, &mut self.spectrum, &mut self.scratch).is_err() { + output.fill(0.0); + return; + } + let (xr, xi) = (&mut self.x_re.get_mut()[slot..slot + B], &mut self.x_im.get_mut()[slot..slot + B]); + for (bin, c) in self.spectrum[..B].iter().enumerate() { + xr[bin] = c.re; + xi[bin] = c.im; } - fft().run(&mut re, &mut im, false); - self.x_re[slot..slot + B].copy_from_slice(&re[..B]); - self.x_im[slot..slot + B].copy_from_slice(&im[..B]); } // sum over k of X[t-k] * H[k] - let mut yr = [0f32; N]; - let mut yi = [0f32; N]; - for k in 0..self.parts { - let x = ((self.head + self.parts - k) % self.parts) * B; - let h = k * B; - let (xr, xi) = (&self.x_re[x..x + B], &self.x_im[x..x + B]); - let (hr, hi) = (&self.h_re[h..h + B], &self.h_im[h..h + B]); - for bin in 0..B { - yr[bin] += xr[bin] * hr[bin] - xi[bin] * hi[bin]; - yi[bin] += xr[bin] * hi[bin] + xi[bin] * hr[bin]; - } + for (k, row) in self.rows.iter_mut().enumerate() { + *row = ((self.head + self.parts - k) % self.parts) * B; } - // the spectrum of a real signal: the upper half mirrors the lower (Nyquist bin stays 0) - for bin in 1..B { - yr[N - bin] = yr[bin]; - yi[N - bin] = -yi[bin]; + let (xr, xi, hr, hi) = (self.x_re.get(), self.x_im.get(), self.h_re.get(), self.h_im.get()); + let (yr, yi) = (self.y_re.get_mut(), self.y_im.get_mut()); + #[cfg(target_arch = "x86_64")] + let done = if std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("fma") { + // SAFETY: the features are there; every row holds B (a multiple of 32) floats from a 64-byte boundary. + unsafe { sum_avx2(xr, xi, hr, hi, &self.rows, yr, yi) }; + true + } else { + false + }; + #[cfg(not(target_arch = "x86_64"))] + let done = false; + if !done { + sum(xr, xi, hr, hi, &self.rows, yr, yi); + } + // the spectrum of a real signal: bins 0 to 1023 (Nyquist bin stays 0) + for (bin, c) in self.spectrum[..B].iter_mut().enumerate() { + *c = realfft::num_complex::Complex32::new(yr[bin], yi[bin]); + } + self.spectrum[0].im = 0.0; + self.spectrum[B] = Default::default(); + if inverse.process_with_scratch(&mut self.spectrum, &mut self.time, &mut self.scratch).is_err() { + output.fill(0.0); + return; } - yi[0] = 0.0; - fft().run(&mut yr, &mut yi, true); let scale = gain / N as f32; - for (o, &v) in output.iter_mut().zip(&yr[B..]) { + for (o, &v) in output.iter_mut().zip(&self.time[B..]) { *o = v * scale; } } } +/// The sum over windows, one window at a time (without AVX2 and FMA). +fn sum(xr: &[f32], xi: &[f32], hr: &[f32], hi: &[f32], rows: &[usize], yr: &mut [f32], yi: &mut [f32]) { + yr[..B].fill(0.0); + yi[..B].fill(0.0); + for (k, &x) in rows.iter().enumerate() { + let h = k * B; + let (xr, xi) = (&xr[x..x + B], &xi[x..x + B]); + let (hr, hi) = (&hr[h..h + B], &hi[h..h + B]); + for bin in 0..B { + yr[bin] += xr[bin] * hr[bin] - xi[bin] * hi[bin]; + yi[bin] += xr[bin] * hi[bin] + xi[bin] * hr[bin]; + } + } +} + +/// The sum over windows, 32 bins at a time with their sums in registers +/// while every window goes by; aligned loads. +/// +/// # Safety +/// AVX2 and FMA; `rows` and the response's rows hold `B` floats each from a +/// 64-byte boundary inside the slices; `yr`, `yi` hold `B` from one. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2,fma")] +unsafe fn sum_avx2(xr: &[f32], xi: &[f32], hr: &[f32], hi: &[f32], rows: &[usize], yr: &mut [f32], yi: &mut [f32]) { + use std::arch::x86_64::*; + assert!(yr.len() >= B && yi.len() >= B && hr.len() >= rows.len() * B && hi.len() >= rows.len() * B); + assert!(rows.iter().all(|&r| r + B <= xr.len() && r + B <= xi.len())); + let mut bin = 0; + while bin < B { + let zero = _mm256_setzero_ps(); + let (mut r0, mut r1, mut r2, mut r3) = (zero, zero, zero, zero); + let (mut i0, mut i1, mut i2, mut i3) = (zero, zero, zero, zero); + for (k, &row) in rows.iter().enumerate() { + // SAFETY: inside the slices (asserted above), on 32-byte boundaries. + unsafe { + let (px, pxi) = (xr.as_ptr().add(row + bin), xi.as_ptr().add(row + bin)); + let (ph, phi) = (hr.as_ptr().add(k * B + bin), hi.as_ptr().add(k * B + bin)); + macro_rules! eight { + ($o:expr, $r:ident, $i:ident) => {{ + let (a, b) = (_mm256_load_ps(px.add($o)), _mm256_load_ps(pxi.add($o))); + let (c, d) = (_mm256_load_ps(ph.add($o)), _mm256_load_ps(phi.add($o))); + $r = _mm256_fnmadd_ps(b, d, _mm256_fmadd_ps(a, c, $r)); + $i = _mm256_fmadd_ps(b, c, _mm256_fmadd_ps(a, d, $i)); + }}; + } + eight!(0, r0, i0); + eight!(8, r1, i1); + eight!(16, r2, i2); + eight!(24, r3, i3); + } + } + // SAFETY: inside `yr` and `yi`, on 32-byte boundaries. + unsafe { + let (py, pyi) = (yr.as_mut_ptr().add(bin), yi.as_mut_ptr().add(bin)); + _mm256_store_ps(py, r0); + _mm256_store_ps(py.add(8), r1); + _mm256_store_ps(py.add(16), r2); + _mm256_store_ps(py.add(24), r3); + _mm256_store_ps(pyi, i0); + _mm256_store_ps(pyi.add(8), i1); + _mm256_store_ps(pyi.add(16), i2); + _mm256_store_ps(pyi.add(24), i3); + } + bin += 32; + } +} + /// Builds a response in the hardware layout from time-domain samples, as /// the title's responses were found to be laid out. #[cfg(test)] @@ -220,6 +367,30 @@ mod tests { } } + #[test] + fn the_register_blocked_sum_is_the_plain_one() { + #[cfg(target_arch = "x86_64")] + if std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("fma") { + let parts = 5; + let fill = |seed: u32| { + let mut a = Aligned::zeros(parts * B); + for (i, v) in a.get_mut().iter_mut().enumerate() { + *v = ((i as u32).wrapping_mul(2_654_435_761).wrapping_add(seed) >> 20) as f32 / 4096.0 - 0.5; + } + a + }; + let (xr, xi, hr, hi) = (fill(1), fill(2), fill(3), fill(4)); + let rows: Vec = (0..parts).map(|k| ((3 + parts - k) % parts) * B).collect(); + let (mut ar, mut ai, mut br, mut bi) = (Aligned::zeros(B), Aligned::zeros(B), Aligned::zeros(B), Aligned::zeros(B)); + sum(xr.get(), xi.get(), hr.get(), hi.get(), &rows, ar.get_mut(), ai.get_mut()); + // SAFETY: the features are there; aligned rows. + unsafe { sum_avx2(xr.get(), xi.get(), hr.get(), hi.get(), &rows, br.get_mut(), bi.get_mut()) }; + for (a, b) in ar.get().iter().zip(br.get()).chain(ai.get().iter().zip(bi.get())) { + assert!((a - b).abs() < 1e-5, "{a} vs {b}"); + } + } + } + #[test] fn a_silent_ring_gives_silence() { let mut c = Convolver::new(&layout(&[1.0, 0.5])).unwrap(); diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 3196ac4f3..f79fe7100 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -1735,45 +1735,19 @@ fn execute(request: &Request) -> Result<(), HRESULT> { /// that ends short of `out` passes: the title's chunks fill it exactly, and /// nothing says that is required. fn inflate(source: &[u8], out: &mut [u8]) -> Result { + // libdeflate's whole-buffer decompressor (C): 1.3-1.4 times zlib-rs's + // streaming one on these requests, which arrive whole. It stops at the + // stream's end (bytes after it are left alone, as before), checks the + // Adler-32, and fails when `out` is too small. thread_local! { - static INFLATE: std::cell::RefCell = - std::cell::RefCell::new(zlib_rs::Inflate::new(true, 15)); - } - INFLATE.with_borrow_mut(|state| { - state.reset(true); - // `Inflate::decompress` cannot distinguish a valid empty stream from - // an insufficient buffer when `avail_out == 0`, so use a 1-byte scratch - // destination and verify `written <= out_len` afterward. - let out_len = out.len(); - let mut scratch = [0u8; 1]; - let dest = if out_len == 0 { &mut scratch[..] } else { out }; - let (mut in_pos, mut out_pos) = (0usize, 0usize); - let status = loop { - match state.decompress( - &source[in_pos..], - &mut dest[out_pos..], - zlib_rs::InflateFlush::NoFlush, - ) { - Ok(zlib_rs::Status::StreamEnd) => break Ok(zlib_rs::Status::StreamEnd), - Ok(zlib_rs::Status::Ok) => { - let next_in = state.total_in() as usize; - let next_out = state.total_out() as usize; - if next_in == in_pos && next_out == out_pos { - break Ok(zlib_rs::Status::BufError); - } - in_pos = next_in; - out_pos = next_out; - } - other => break other, - } - }; - let written = state.total_out() as usize; - match status { - Ok(zlib_rs::Status::StreamEnd) if written <= out_len => Ok(written), - other => { - tracing::debug!(?other, "dstorage: zlib stream"); - Err(INVALID_DATA) - } + static INFLATE: std::cell::RefCell = + std::cell::RefCell::new(libdeflater::Decompressor::new()); + } + INFLATE.with_borrow_mut(|state| match state.zlib_decompress(source, out) { + Ok(written) => Ok(written), + Err(error) => { + tracing::debug!(?error, "dstorage: zlib stream"); + Err(INVALID_DATA) } }) } From fbe9a8485e71d91806c0dc5935b612505ddf4429 Mon Sep 17 00:00:00 2001 From: user Date: Sat, 28 Nov 2026 02:48:29 +0100 Subject: [PATCH 2/2] perf: two-level write-watch journal, fused copy+digest asm, BCPack in C, f16 reverb Four deeper changes, kept apart from the first commit on purpose: they replace a core data structure (the write-watch journal), add assembly with its own fault-handling labels, add C code to a crate that had none, and add an approximate reverb. That makes them easier to review, test on Windows and revert one by one. Each one can also be switched at run time (see below), except the journal. IMPORTANT, how this was tested: the author of these changes does not own a copy of the game. Nothing here has been run with the game, and nothing has been run on Windows. Every number below comes from benchmarks on synthetic data that was made up for the purpose (random journals and ranges, buffers with made-up contents, random BCPack streams, made-up impulse responses), on Linux, on one core of an Intel i7-13620H (AVX2, VAES, F16C, no AVX-512). victory-gpu: the write-watch journal as a two-level page table - New watch/pages.rs replaces the journal's BTreeMap. Pages are grouped in chunks of 4,096 (256 MiB of title memory) made when a page of theirs is first noted. Each chunk keeps every page's asking (0: never), a bit per written page and a bit per word of those bits in use. Questions go through the words in use only: a word with few written pages visits them by their bits (tzcnt), a word with many is compared whole with AVX2 (4 pages an instruction). A range over more chunks than there are goes through the chunks there are, in order, not through every chunk number it covers. - Measured against the BTreeMap, journals of 2,000 and 200,000 written pages over 64 GiB: ranges of 16 pages 4.3-5.1x faster (list and nothing_new); 4,096 pages 0.95-1.7x; a range over the whole journal 1.05x when it is full; on a sparse journal such a range takes a few microseconds, 2.5-3x the tree's. Notes 19-28x faster. - An earlier version of this commit went through every chunk number of a range: a range over terabytes of addresses took milliseconds (up to 4.7 ms a question). Fixed here. - An equivalence test compares every answer with a BTreeMap over random notes and ranges, across chunk borders. victory-gpu: copy and digest in one pass, in assembly - safecopy.rs: victory_safe_copy_hash copies blocks of 128 bytes from title memory and takes each through the AES digest's round (VAES), reading the source once. The source loads are inside new fault labels in failing_exit; on any fault the call fails and the caller starts again the original way. It uses only ymm0-ymm5, the volatile registers of the Windows calling convention, so nothing needs saving. - texture.rs: copy_digest() uses it where a copy of title memory was followed by digest(): the refresh of textures in view memory, and fingerprint(). It gives the same digest as digest(). It only runs with the safe copy on, no soft views and VAES present; otherwise, or on a fault, it does copy_mapped() then digest(), as before. - Measured 1.16-1.39x faster than the safe copy (rep movsb) followed by the VAES digest, for 64 KiB to 8 MiB. The same bytes and the same digest as copy-then-digest for every length from 0 to 700 and for large ones. - New Windows test: the same bytes and digest as copy-then-digest, and a decommitted page makes the call fail without a crash. - VICTORY_COPY_DIGEST=0 turns it off. victory-formats: BCPack lane decoding in C - csrc/bcpack_lanes.c, built with the cc crate (MSVC on Windows) from a new build.rs: the same two-pass schedule as the Rust lanes(), which stays as the reference and the fallback. - decode() measured 1.17-1.20x faster on top of the first commit's optimizations (BC1 82 -> 98 MB/s, BC4 76 -> 89, BC7 50.5 -> 59.4). - The round-trip test now also checks that the C version gives the same records as the Rust one on every lane layout, and fails on truncated streams. - xtask/src/policy.rs: "c" added to the asset policy's allowed extensions, for this one file. That is the maintainers' call: without it, the C version (and this line) can be dropped and the Rust lanes() kept. - VICTORY_BCPACK_C=0 turns it off. victory-hle: the reverb's impulse response as half floats, opt-in - dsp/convolve.rs can keep the response as half floats (F16C) and widen them as they are loaded. That halves the bytes brought in from memory for every block, which is the limit with long responses. - A whole block, measured: 1.03x faster with a 0.2 s response, 1.15x with 1 s, 1.97x with 3 s, 1.82x with 6 s. - This is an approximation: the output differs from the float version by about -73 dB of its peak. On a_mono_convolution_is_computed's input that is up to 1.6e-4, over the 1e-4 the test allows; so it is off by default, and that test is unchanged. VICTORY_DSP_HALF=1 turns it on; a test bounds its error at -60 dB. Checks: victory-formats tests pass on Linux; the journal's and the convolution's tests pass on Linux from copies of the same files (those crates no longer build there). The whole workspace passes cargo clippy --workspace --all-targets [--all-features] --locked --target x86_64-pc-windows-msvc with no errors and no warnings in the files this changes; the C builds (libdeflate, BCPack) used a stand-in compiler for that, so they still need a real MSVC build. xtask's policy test passes for these files (main's lower.rs is over its size limit on its own). Before merging, run cargo test on Windows: the safecopy fault test and watch.rs's tests only run there. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 3 + Cargo.toml | 2 + crates/victory-formats/Cargo.toml | 3 + crates/victory-formats/build.rs | 5 + crates/victory-formats/csrc/bcpack_lanes.c | 71 +++++ crates/victory-formats/src/bcpack.rs | 57 +++- crates/victory-gpu/src/safecopy.rs | 100 +++++++ crates/victory-gpu/src/texture.rs | 78 +++++- crates/victory-gpu/src/watch.rs | 20 +- crates/victory-gpu/src/watch/pages.rs | 249 ++++++++++++++++++ .../victory-hle/src/modules/dsp/convolve.rs | 145 +++++++++- xtask/src/policy.rs | 2 + 12 files changed, 720 insertions(+), 15 deletions(-) create mode 100644 crates/victory-formats/build.rs create mode 100644 crates/victory-formats/csrc/bcpack_lanes.c create mode 100644 crates/victory-gpu/src/watch/pages.rs diff --git a/Cargo.lock b/Cargo.lock index 1300a05ae..69bb99dcc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -760,6 +760,9 @@ dependencies = [ [[package]] name = "victory-formats" version = "0.1.0" +dependencies = [ + "cc", +] [[package]] name = "victory-game" diff --git a/Cargo.toml b/Cargo.toml index c9d1762b3..114e29761 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,6 +44,8 @@ zlib-rs = { version = "0.6.8", default-features = false, features = ["std"] } libdeflater = "1.26" # Real-input FFTs (pure Rust, MIT/Apache-2.0) for the DSP's convolutions. realfft = "3.5" +# C compiler driver for the few C sources (victory-formats csrc). +cc = "1.2" walkdir = "2.5.1" tempfile = "3.27.0" # Opus decoding for the console's audio decoder (BSD-3-Clause, pure Rust). diff --git a/crates/victory-formats/Cargo.toml b/crates/victory-formats/Cargo.toml index 6f3efd957..ab9e3c467 100644 --- a/crates/victory-formats/Cargo.toml +++ b/crates/victory-formats/Cargo.toml @@ -7,5 +7,8 @@ rust-version.workspace = true license.workspace = true publish.workspace = true +[build-dependencies] +cc.workspace = true + [lints] workspace = true diff --git a/crates/victory-formats/build.rs b/crates/victory-formats/build.rs new file mode 100644 index 000000000..5d88af877 --- /dev/null +++ b/crates/victory-formats/build.rs @@ -0,0 +1,5 @@ +//! Builds the C part of BCPack's decoder (`csrc/bcpack_lanes.c`). +fn main() { + println!("cargo:rerun-if-changed=csrc/bcpack_lanes.c"); + cc::Build::new().file("csrc/bcpack_lanes.c").opt_level(3).warnings(true).compile("victory_bcpack_lanes"); +} diff --git a/crates/victory-formats/csrc/bcpack_lanes.c b/crates/victory-formats/csrc/bcpack_lanes.c new file mode 100644 index 000000000..d3b130ba6 --- /dev/null +++ b/crates/victory-formats/csrc/bcpack_lanes.c @@ -0,0 +1,71 @@ +// BCPack's lane decoding (victory-formats bcpack.rs `lanes`), in C: the same +// schedule, two passes a round (every lane's step, then the bytes in lane +// order). The Rust version stays the reference and the fallback +// (`VICTORY_BCPACK_C=0`); the tests compare the two. +#include +#include +#include +#define LOW (1u << 24) +#define ROUND_BYTES 8 +typedef struct { uint8_t width, phase, longf, reset, model, need, has_latch, latch, has_out, out, stalled; uint32_t x, left; } Lane; + +static size_t bucket_of(const uint32_t *start, const uint8_t *bucket, uint32_t slot) { + size_t b = bucket[slot >> 8]; + while (start[b + 1] <= slot) b++; + return b; +} + +/* freq [128][9], start [128][10], bucket [128][256], recip [128][9]: the tables + as bcpack.rs keeps them. 0: done; -1: the stream ends early or is corrupt. */ +int victory_bcpack_lanes(const uint32_t *freq /*[128][9]*/, const uint32_t *start /*[128][10]*/, + const uint8_t *bucket /*[128][256]*/, const uint64_t *recip /*[128][9]*/, + const uint8_t *widths, size_t nl, size_t per, size_t blocks, + const uint8_t *src, size_t srclen, uint8_t *records) { + Lane lanes[16]; memset(lanes, 0, sizeof lanes); + for (size_t j = 0; j < nl; j++) { lanes[j].width = widths[j]; lanes[j].need = 1; } + size_t stride = nl * per, pos = 0, at = 0, sp = 0; uint32_t done = 0, full = (1u << nl) - 1; int idle = 0; + while (pos < blocks * per) { + int taken = 0, moved = 0; + // pass 1: the lanes' steps, independent of each other + for (size_t j = 0; j < nl; j++) { + Lane *l = &lanes[j]; + if (!l->stalled) { + if (l->phase != 3) { + if (l->has_latch) { + uint8_t b = l->latch; l->has_latch = 0; l->need = 1; + if (l->phase == 0) { uint8_t g = l->width - (b >> 6); l->model = g * 16 + (b & 15); l->reset = (b & 0x10) != 0; l->longf = (b & 0x20) != 0; l->left = 0; l->phase = 1; } + else if (l->phase == 1 && l->longf) { l->left = b; l->phase = 2; } + else if (l->phase == 1) { l->left = (uint32_t)b + 1; l->phase = 3; } + else { l->left = (((uint32_t)b << 8) | l->left) + 257; l->phase = 3; } + } + } else { + uint32_t x = l->x; + if (x < LOW && l->has_latch) { l->has_latch = 0; l->left--; x = (x << 8) | l->latch; } + l->need = l->left != 0 && !l->has_latch; + if (x > LOW) { + const uint32_t *f = freq + l->model * 9, *st = start + l->model * 10; + uint32_t slot = x & 0xffff; + size_t b = bucket_of(st, bucket + l->model * 256, slot); + uint32_t sym, fr, rem; + if (b == 0) { sym = 0; fr = f[0] - 1; rem = slot - 1; } + else { uint32_t off = slot - st[b]; uint32_t q = (uint32_t)(((uint64_t)off * recip[l->model * 9 + b]) >> 32); sym = (1u << (b - 1)) + q; fr = f[b]; rem = off - q * f[b]; } + l->x = (x >> 16) * fr + rem; l->has_out = 1; l->out = (uint8_t)sym; + } else if (l->left != 0) { l->x = x; } + else { l->phase = 0; l->need = !l->has_latch; if (l->reset) l->x = 0; } + } + } + } + // pass 2: bytes, stalls and outputs, in lane order + for (size_t j = 0; j < nl; j++) { + Lane *l = &lanes[j]; uint32_t bit = 1u << j; int before = taken; + int waiting = l->has_out && (done & bit); + if (l->need && !waiting && taken < ROUND_BYTES) { if (sp < srclen) { l->latch = src[sp++]; l->has_latch = 1; taken++; } } + l->stalled = (l->need && before >= ROUND_BYTES) || waiting; + if (!l->stalled && l->has_out) { records[at + j * per] = l->out; l->has_out = 0; done |= bit; moved = 1; } + } + if (done == full) { pos++; at += (pos % per == 0) ? stride - per + 1 : 1; done = 0; moved = 1; } + idle = (taken > 0 || moved) ? 0 : idle + 1; + if (idle > 3) return -1; + } + return 0; +} diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs index bf2f8100c..6a701d12e 100644 --- a/crates/victory-formats/src/bcpack.rs +++ b/crates/victory-formats/src/bcpack.rs @@ -276,7 +276,11 @@ pub fn decode(bc: u8, src: &[u8], dst: &mut [u8], tables: &Tables) -> Result<(), let stride = widths.len() * per; let mut records = vec![0u8; blocks * stride]; let mut next = src.iter().copied(); - lanes(tables, widths, per, blocks, |_| next.next(), &mut records)?; + if c_lanes() { + lanes_c(tables, widths, per, blocks, src, &mut records)?; + } else { + lanes(tables, widths, per, blocks, |_| next.next(), &mut records)?; + } let records = records.chunks_exact(stride); let out = dst.chunks_exact_mut(block); let t = tables; @@ -475,6 +479,53 @@ fn lanes( Ok(()) } +unsafe extern "C" { + fn victory_bcpack_lanes( + freq: *const u32, + start: *const u32, + bucket: *const u8, + recip: *const u64, + widths: *const u8, + nl: usize, + per: usize, + blocks: usize, + src: *const u8, + srclen: usize, + records: *mut u8, + ) -> i32; +} + +/// Whether [`lanes_c`] decodes the lanes (`VICTORY_BCPACK_C=0`: [`lanes`]). +fn c_lanes() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BCPACK_C").is_none_or(|v| v != "0")) +} + +/// [`lanes`] in C (`csrc/bcpack_lanes.c`), the input taken from `src` in +/// order: the same records. The C compiler's code for this loop ran ahead of +/// rustc's (measured in the module's benchmark). +fn lanes_c(t: &Tables, widths: &[u8], per: usize, blocks: usize, src: &[u8], records: &mut [u8]) -> Result<(), Error> { + assert!(widths.len() <= 16 && records.len() >= blocks * widths.len() * per); + // SAFETY: the tables are plain arrays of the sizes the C side reads; the + // records hold every symbol the lanes deliver (asserted). + let rc = unsafe { + victory_bcpack_lanes( + t.freq.as_ptr().cast(), + t.start.as_ptr().cast(), + t.bucket.as_ptr().cast(), + t.recip.as_ptr().cast(), + widths.as_ptr(), + widths.len(), + per, + blocks, + src.as_ptr(), + src.len(), + records.as_mut_ptr(), + ) + }; + if rc == 0 { Ok(()) } else { Err(Error("the stream ends early or is corrupt")) } +} + // Blocks. /// The record's endpoint and index references. @@ -1687,6 +1738,10 @@ mod tests { let mut next = src.iter().copied(); lanes(&t, widths, per, blocks, |_| next.next(), &mut got).unwrap(); assert_eq!(got, records.concat(), "{widths:?} x{per}, {blocks} blocks"); + let mut from_c = vec![0u8; got.len()]; + lanes_c(&t, widths, per, blocks, &src, &mut from_c).unwrap(); + assert_eq!(from_c, got, "C: {widths:?} x{per}, {blocks} blocks"); + assert!(lanes_c(&t, widths, per, blocks, &src[..src.len() / 2], &mut from_c).is_err()); } } } diff --git a/crates/victory-gpu/src/safecopy.rs b/crates/victory-gpu/src/safecopy.rs index 244e82548..3c913345b 100644 --- a/crates/victory-gpu/src/safecopy.rs +++ b/crates/victory-gpu/src/safecopy.rs @@ -170,6 +170,57 @@ std::arch::global_asm!( "victory_safe_changed_failed:", "vzeroupper", "xor eax, eax", + "ret", ".globl victory_safe_copy_hash", + ".globl victory_safe_copy_hash_at", + ".globl victory_safe_copy_hash_after", + ".globl victory_safe_copy_hash_failed", + // rcx destination, rdx source, r8 blocks of 128 bytes, r9 the AES digest's + // state (four 32-byte lanes, then the 32-byte round key): copies the + // blocks and takes each through the digest's round (texture.rs + // `digest_vaes`), reading the source once; the lanes go back to the + // state. eax: whether all could be read. Only ymm0-ymm5 (volatile). + "victory_safe_copy_hash:", + "vmovdqu ymm1, ymmword ptr [r9]", + "vmovdqu ymm2, ymmword ptr [r9 + 32]", + "vmovdqu ymm3, ymmword ptr [r9 + 64]", + "vmovdqu ymm4, ymmword ptr [r9 + 96]", + "vmovdqu ymm5, ymmword ptr [r9 + 128]", + "test r8, r8", + "jz 3f", + "2:", + "victory_safe_copy_hash_at:", + "vmovdqu ymm0, ymmword ptr [rdx]", + "vmovdqu ymmword ptr [rcx], ymm0", + "vpxor ymm1, ymm1, ymm0", + "vaesenc ymm1, ymm1, ymm5", + "vmovdqu ymm0, ymmword ptr [rdx + 32]", + "vmovdqu ymmword ptr [rcx + 32], ymm0", + "vpxor ymm2, ymm2, ymm0", + "vaesenc ymm2, ymm2, ymm5", + "vmovdqu ymm0, ymmword ptr [rdx + 64]", + "vmovdqu ymmword ptr [rcx + 64], ymm0", + "vpxor ymm3, ymm3, ymm0", + "vaesenc ymm3, ymm3, ymm5", + "vmovdqu ymm0, ymmword ptr [rdx + 96]", + "vmovdqu ymmword ptr [rcx + 96], ymm0", + "vpxor ymm4, ymm4, ymm0", + "vaesenc ymm4, ymm4, ymm5", + "victory_safe_copy_hash_after:", + "add rcx, 128", + "add rdx, 128", + "dec r8", + "jnz 2b", + "3:", + "vmovdqu ymmword ptr [r9], ymm1", + "vmovdqu ymmword ptr [r9 + 32], ymm2", + "vmovdqu ymmword ptr [r9 + 64], ymm3", + "vmovdqu ymmword ptr [r9 + 96], ymm4", + "vzeroupper", + "mov eax, 1", + "ret", + "victory_safe_copy_hash_failed:", + "vzeroupper", + "xor eax, eax", "ret", ); @@ -190,6 +241,25 @@ unsafe extern "system" { fn victory_safe_changed_at(); fn victory_safe_changed_after(); fn victory_safe_changed_failed(); + fn victory_safe_copy_hash(dst: *mut u8, src: *const u8, blocks: usize, state: *mut [u8; 160]) -> u32; + fn victory_safe_copy_hash_at(); + fn victory_safe_copy_hash_after(); + fn victory_safe_copy_hash_failed(); +} + +/// Copies `blocks` blocks of 128 bytes and takes each through the AES +/// digest's round (`crate::texture::digest`, VAES), reading the source once: +/// `state` holds the digest's four lanes (updated) and its round key. False +/// if a page of the source cannot be read; then the destination and the +/// lanes are partly done (the caller starts again another way). +/// +/// # Safety +/// As [`copy`]'s, for `blocks * 128` bytes; the processor has VAES and AVX2. +/// [`on`] must have been asked. +pub(crate) unsafe fn copy_hash(dst: *mut u8, src: *const u8, blocks: usize, state: &mut [u8; 160]) -> bool { + // SAFETY: a fault reading the source leaves through the failing exit + // ([`failing_exit`]); the rest is the caller's. + unsafe { victory_safe_copy_hash(dst, src, blocks, state) != 0 } } /// The records of 32 bytes at `title` (`records` of them) that differ from @@ -416,6 +486,10 @@ pub(crate) fn failing_exit(at: usize) -> Option { if (from..to).contains(&at) { return Some(victory_safe_changed_failed as *const () as usize); } + let (from, to) = (victory_safe_copy_hash_at as *const () as usize, victory_safe_copy_hash_after as *const () as usize); + if (from..to).contains(&at) { + return Some(victory_safe_copy_hash_failed as *const () as usize); + } let (from, to) = (victory_safe_merge_at as *const () as usize, victory_safe_merge_after as *const () as usize); (from..to).contains(&at).then_some(victory_safe_merge_failed as *const () as usize) } @@ -471,6 +545,32 @@ mod tests { } } + /// The copy with the digest's round: the bytes and the digest of a copy + /// then `digest`, every length; a page that is not there fails. + #[test] + fn copies_with_the_digest_and_fails_on_a_missing_page() { + assert!(on()); + if !std::arch::is_x86_feature_detected!("vaes") { + return; + } + let pages = Pages::new(1 << 16); + pages.fill(); + // SAFETY: inside the allocation. + let title = unsafe { std::slice::from_raw_parts(pages.0, pages.1) }.to_vec(); + for len in [0usize, 1, 127, 128, 129, 4095, 4096, 4097, 40_000, 1 << 16] { + let mut read = vec![0xEEu8; len]; + let got = crate::texture::copy_digest(&mut read, pages.0); + assert_eq!(read[..], title[..len], "{len} bytes"); + assert_eq!(got, crate::texture::digest(&title[..len]), "{len} bytes"); + } + // SAFETY: a page of our allocation. + unsafe { VirtualFree(pages.0.add(8192).cast(), 4096, MEM_DECOMMIT) }; + let mut state = [0u8; 160]; + let mut read = vec![0u8; 3 << 12]; + // SAFETY: the third page is not there: the call fails, nothing faults. + assert!(!unsafe { copy_hash(read.as_mut_ptr(), pages.0, (3 << 12) / 128, &mut state) }); + } + /// The records that differ get their bits and go over those last seen; /// a page that is not there fails, with the records before it done. #[test] diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index dc103bb86..ab818f416 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -869,6 +869,78 @@ unsafe fn digest_aesni(bytes: &[u8]) -> u128 { } } +/// Copies the title memory at `src` into `read` and gives its [`digest`]: +/// with VAES and the safe copy, in one pass over the source (copy and the +/// digest's round together, `crate::safecopy::copy_hash`: 1.2-1.4 times the +/// copy then the digest, measured); else, or where a page cannot be read, +/// the copy (`crate::host::copy_mapped`) then [`digest`], as before. +/// `VICTORY_COPY_DIGEST=0`: always that way. +pub(crate) fn copy_digest(read: &mut [u8], src: *const u8) -> Digest { + #[cfg(target_arch = "x86_64")] + if fused_copy_digest() && crate::watch::soft().is_none() { + crate::watch::materialize(src as usize, read.len()); + // SAFETY: `read` is ours; VAES and the safe copy are there + // (`fused_copy_digest`); a source page that is not there fails. + if let Some(h) = unsafe { copy_digest_vaes(read, src) } { + return Digest(h); + } + } + crate::host::copy_mapped(read.as_mut_ptr(), src, read.len(), false); + digest(read) +} + +fn fused_copy_digest() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + #[cfg(target_arch = "x86_64")] + let can = std::arch::is_x86_feature_detected!("vaes") && std::arch::is_x86_feature_detected!("avx2"); + #[cfg(not(target_arch = "x86_64"))] + let can = false; + can && crate::safecopy::on() && std::env::var_os("VICTORY_COPY_DIGEST").is_none_or(|v| v != "0") + }) +} + +/// [`copy_digest`]'s pass: whole blocks of 128 bytes in assembly, the rest +/// copied, then [`digest_vaes`]'s last block and fold; the same digest. +/// +/// # Safety +/// VAES and AVX2; the safe copy is on; `src` as `crate::safecopy::copy`'s. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2,vaes,aes")] +#[allow(clippy::incompatible_msrv)] +unsafe fn copy_digest_vaes(read: &mut [u8], src: *const u8) -> Option { + use std::arch::x86_64::*; + let n = read.len(); + let mut state = [0u8; 160]; + // SAFETY: stores inside `state`; the copies' faults fail them. + unsafe { + let k = _mm256_loadu_si256(AES_KEYS.as_ptr().cast()); + for i in 0..4 { + let lane = _mm256_xor_si256(k, _mm256_set_epi64x(0, 2 * i as i64 + 1, 0, 2 * i as i64)); + _mm256_storeu_si256(state.as_mut_ptr().add(32 * i).cast(), lane); + } + _mm256_storeu_si256(state.as_mut_ptr().add(128).cast(), k); + let whole = n / 128 * 128; + if !crate::safecopy::copy_hash(read.as_mut_ptr(), src, n / 128, &mut state) + || !crate::safecopy::copy(read.as_mut_ptr().add(whole), src.add(whole), n - whole) + { + return None; + } + let mut h: [__m256i; 4] = std::array::from_fn(|i| _mm256_loadu_si256(state.as_ptr().add(32 * i).cast())); + let mut last = [0u8; 128]; + last[..n - whole].copy_from_slice(&read[whole..]); + for (i, h) in h.iter_mut().enumerate() { + *h = _mm256_aesenc_epi128(_mm256_xor_si256(*h, _mm256_loadu_si256(last.as_ptr().add(32 * i).cast())), k); + } + let mut out = [[0u8; 16]; 8]; + for (i, h) in h.iter().enumerate() { + _mm_storeu_si128(out[2 * i].as_mut_ptr().cast(), _mm256_castsi256_si128(*h)); + _mm_storeu_si128(out[2 * i + 1].as_mut_ptr().cast(), _mm256_extracti128_si256::<1>(*h)); + } + Some(aes_finish(&out, n)) + } +} + /// The eight lanes and the length, folded to 128 bits (folded products, as /// [`digest`] ends). fn aes_finish(lanes: &[[u8; 16]; 8], len: usize) -> u128 { @@ -1869,8 +1941,7 @@ impl Staging { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); let changed = with_read(size, |read| { - crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); - let hash = digest(read); + let hash = copy_digest(read, self.memory); if last.hash == Some(hash) { return false; } @@ -2178,8 +2249,7 @@ pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { read.resize(3 * WINDOW, 0); let mut take = |from: usize, bytes: usize| { read[..bytes].fill(0); - crate::host::copy_mapped(read.as_mut_ptr(), (at as usize + from) as *const u8, bytes, false); - print = print.rotate_left(37) ^ digest(&read[..bytes]).0; + print = print.rotate_left(37) ^ copy_digest(&mut read[..bytes], (at as usize + from) as *const u8).0; }; if len <= 3 * WINDOW { take(0, len); diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index adcbb0ecc..223dd7fc1 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -26,6 +26,8 @@ //! it has nothing). `VICTORY_VIEW_GUARD=0`: each address for itself, as //! before. +mod pages; + use std::collections::{BTreeMap, BTreeSet}; use std::ops::{Bound, RangeBounds}; use std::sync::{Condvar, Mutex, RwLock}; @@ -194,7 +196,7 @@ pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { struct Journal { /// Page number → the asking that last found it written. - written: BTreeMap, + written: pages::Pages, /// The same for each of a page's sixteen parts ([`KERNEL_PAGE`]), where /// the parts are known ([`parts_on`]); a page that is not here was /// written whole, as far as anyone knows. @@ -272,7 +274,7 @@ impl Ahead { } static JOURNAL: RwLock = RwLock::new(Journal { - written: BTreeMap::new(), + written: pages::Pages::new(), parts: std::collections::HashMap::with_hasher(std::hash::BuildHasherDefault::new()), ahead: Ahead::new(), ahead_asked: 0, @@ -1002,7 +1004,7 @@ fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> { let (first, last) = (start / PAGE, end.div_ceil(PAGE)); let j = journal(); - let of = |j: &Journal| j.written.range(first..last).map(|(&p, &w)| (p, w)).collect(); + let of = |j: &Journal| j.written.range(first, last); if j.ahead.holds(first, last) { return Some((j.ahead_asked, of(&j))); } @@ -1023,7 +1025,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve materialize(start, end.saturating_sub(start)); } let (first, last) = (start / PAGE, end.div_ceil(PAGE)); - let of = |j: &Journal| -> Vec<(usize, u64)> { j.written.range(first..last).map(|(&p, &w)| (p, w)).collect() }; + let of = |j: &Journal| -> Vec<(usize, u64)> { j.written.range(first, last) }; // Asked ahead with the submission's other ranges: the journal has it. let ahead = |j: &Journal| j.ahead.holds(first, last).then(|| (j.ahead_asked, of(j))); if let Some(known) = ahead(&journal()) { @@ -1122,7 +1124,7 @@ pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], return false; }; (ranged != 0 || taken.iter().all(|&at| at != 0)) - && j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged)) + && j.written.none_newer(first, last, taken, ranged) } impl Tracked { @@ -3649,7 +3651,7 @@ mod parts_tests { #[test] fn the_parts_of_a_page_written_since_it_was_taken() { let mut j = Journal { - written: BTreeMap::new(), + written: pages::Pages::new(), parts: std::collections::HashMap::with_hasher(std::hash::BuildHasherDefault::new()), ahead: Ahead::new(), ahead_asked: 0, @@ -4064,7 +4066,7 @@ mod tests { // SAFETY: committed pages of ours. unsafe { ((p + PAGE) as *mut u8).write_volatile(1) }; ask_rest(&ranges); - let last = journal().written.get(&(p / PAGE + 1)).copied(); + let last = journal().written.get(p / PAGE + 1); ask_once_end(); assert!(last.is_some_and(|last| last > copied), "{last:?} is not after {copied}"); // SAFETY: our allocation. @@ -4089,11 +4091,11 @@ mod tests { // SAFETY: committed pages of ours. unsafe { ((p + PAGE) as *mut u8).write_volatile(1) }; ask_first(vec![(p, p + 4 * PAGE)]).wait(); - assert!(journal().written.contains_key(&(p / PAGE + 1)), "the first asking did not note the page written"); + assert!(journal().written.get(p / PAGE + 1).is_some(), "the first asking did not note the page written"); // SAFETY: committed pages of ours. unsafe { ((q + 2 * PAGE) as *mut u8).write_volatile(1) }; assert!(ask_more(&[(p, p + 4 * PAGE), (q, q + 4 * PAGE)]), "a range nobody held was not asked about"); - assert!(journal().written.contains_key(&(q / PAGE + 2)), "the asking for more did not note the page written"); + assert!(journal().written.get(q / PAGE + 2).is_some(), "the asking for more did not note the page written"); ask_once_end(); // An empty asking is waited for like any other. ask_first(Vec::new()).wait(); diff --git a/crates/victory-gpu/src/watch/pages.rs b/crates/victory-gpu/src/watch/pages.rs new file mode 100644 index 000000000..4ca4293a2 --- /dev/null +++ b/crates/victory-gpu/src/watch/pages.rs @@ -0,0 +1,249 @@ +//! The journal's pages ([`super::Journal`]): page number → the asking that +//! last found it written, in the shape of a processor's page table, not a +//! sorted tree. +//! +//! The pages are grouped in chunks of [`CHUNK`] (256 MiB of title memory), +//! made when a page of theirs is first noted. A chunk holds every page's +//! asking (0: never written), a bit per page that is not 0, and a bit per +//! word of those bits that is not 0. A question about a range goes through +//! the words in use only: one with a few written pages visits them by their +//! bits, and a word of many is compared four pages an instruction (AVX2), +//! with no visit of single pages; a range over more chunks than there are +//! goes through the chunks there are. Against the tree it replaces +//! (measured): short ranges 3.5-5 times as fast, ranges of thousands of +//! pages as fast to 1.6 times; a range over a whole sparse journal, a few +//! microseconds, 2-3 times as long. + +use std::collections::HashMap; +use std::hash::BuildHasherDefault; + +/// Pages a chunk. +const CHUNK: usize = 4096; +/// Words of bits a chunk. +const WORDS: usize = CHUNK / 64; +/// A word with more written pages than this is compared whole. +const MANY: u32 = 12; + +struct Chunk { + asked: [u64; CHUNK], + bits: [u64; WORDS], + /// A bit per word of `bits` that is not 0. + words: u64, +} + +/// See the file. +pub(super) struct Pages { + chunks: HashMap, BuildHasherDefault>, + /// The chunks' numbers, in order: a range over more chunks than there + /// are goes through these, not through every chunk it could hold (a + /// range of a whole reservation, terabytes of addresses, was otherwise + /// a million hash looks). + order: Vec, + count: usize, +} + +impl Pages { + pub(super) const fn new() -> Pages { + Pages { chunks: HashMap::with_hasher(BuildHasherDefault::new()), order: Vec::new(), count: 0 } + } + + /// Notes `page` as last found written by `asked` (not 0); the asking + /// before, if there was one. + pub(super) fn insert(&mut self, page: usize, asked: u64) -> Option { + debug_assert!(asked != 0); + let order = &mut self.order; + let chunk = self.chunks.entry(page / CHUNK).or_insert_with(|| { + let c = page / CHUNK; + order.insert(order.partition_point(|&o| o < c), c); + // made on the heap at once (32 KiB): no copy through the stack + let zeroed = vec![0u64; CHUNK + WORDS + 1].into_boxed_slice(); + // SAFETY: `Chunk` is CHUNK + WORDS + 1 u64s, of u64 alignment, and + // all zeros is a valid one. + unsafe { Box::from_raw(Box::into_raw(zeroed).cast::()) } + }); + let at = page % CHUNK; + let before = std::mem::replace(&mut chunk.asked[at], asked); + if before == 0 { + chunk.bits[at / 64] |= 1 << (at % 64); + chunk.words |= 1 << (at / 64); + self.count += 1; + None + } else { + Some(before) + } + } + + #[cfg(test)] + pub(super) fn get(&self, page: usize) -> Option { + let v = self.chunks.get(&(page / CHUNK))?.asked[page % CHUNK]; + (v != 0).then_some(v) + } + + /// Pages written in all (for tests and the diagnostics). + #[allow(dead_code)] + pub(super) fn len(&self) -> usize { + self.count + } + + /// The chunks of `[first, last)`, each with the part of the range in it + /// (as positions inside the chunk) and the page number of its start. + fn spans(&self, first: usize, last: usize) -> impl Iterator + '_ { + let ends = if first < last { first / CHUNK..(last - 1) / CHUNK + 1 } else { 0..0 }; + // (Every chunk number of the range, or the chunks there are in it: + // whichever are fewer.) + let known = if ends.len() > self.order.len() { + let (a, b) = (self.order.partition_point(|&o| o < ends.start), self.order.partition_point(|&o| o < ends.end)); + &self.order[a..b] + } else { + &[][..] + }; + let every = if ends.len() > self.order.len() { 0..0 } else { ends }; + every.chain(known.iter().copied()).filter_map(move |c| { + let chunk = self.chunks.get(&c)?; + let base = c * CHUNK; + Some((&**chunk, first.max(base) - base, last.min(base + CHUNK) - base, base)) + }) + } + + /// `(page, asking)` of the written pages of `[first, last)`, in page order. + pub(super) fn range(&self, first: usize, last: usize) -> Vec<(usize, u64)> { + let mut out = Vec::new(); + for (chunk, from, to, base) in self.spans(first, last) { + for w in in_use(chunk, from, to) { + let mut m = word(chunk, w, from, to); + while m != 0 { + let at = w * 64 + m.trailing_zeros() as usize; + out.push((base + at, chunk.asked[at])); + m &= m - 1; + } + } + } + out + } + + /// Whether every written page of `[first, last)` was last found written + /// no later than `taken[page - first]` or `ranged`, whichever is later + /// (`taken` holds `last - first` askings). + pub(super) fn none_newer(&self, first: usize, last: usize, taken: &[u64], ranged: u64) -> bool { + assert!(taken.len() >= last.saturating_sub(first)); + for (chunk, from, to, base) in self.spans(first, last) { + for w in in_use(chunk, from, to) { + let m = word(chunk, w, from, to); + if m == 0 { + continue; + } + let lo = w * 64; + let whole = m == u64::MAX || m.count_ones() > MANY; + #[cfg(target_arch = "x86_64")] + if whole && lo >= from && lo + 64 <= to && std::arch::is_x86_feature_detected!("avx2") { + let t = &taken[base + lo - first..][..64]; + // SAFETY: AVX2 is there; 64 askings of both. + if unsafe { newer_avx2(&chunk.asked[lo..lo + 64], t, ranged) } { + return false; + } + continue; + } + let mut m = m; + while m != 0 { + let at = lo + m.trailing_zeros() as usize; + if chunk.asked[at] > taken[base + at - first].max(ranged) { + return false; + } + m &= m - 1; + } + } + } + true + } +} + +/// The words of `chunk`'s bits that are not 0 and hold a page of +/// `[from, to)`, in order. +fn in_use(chunk: &Chunk, from: usize, to: usize) -> impl Iterator { + let (lo, hi) = (from / 64, to.div_ceil(64)); + let below = if hi >= 64 { u64::MAX } else { (1u64 << hi) - 1 }; + let mut m = chunk.words & below & !((1u64 << lo) - 1); + std::iter::from_fn(move || { + (m != 0).then(|| { + let w = m.trailing_zeros() as usize; + m &= m - 1; + w + }) + }) +} + +/// The bits of word `w` of `chunk` that lie in `[from, to)`. +fn word(chunk: &Chunk, w: usize, from: usize, to: usize) -> u64 { + let lo = w * 64; + let mut m = chunk.bits[w]; + if from > lo { + m &= u64::MAX << (from - lo); + } + if to < lo + 64 { + m &= (1u64 << (to - lo)) - 1; + } + m +} + +/// Whether any of 64 askings is later than its `taken` and `ranged` both. +/// Askings stay below 2^63, so signed compares do. +/// +/// # Safety +/// AVX2; both hold 64. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn newer_avx2(asked: &[u64], taken: &[u64], ranged: u64) -> bool { + use std::arch::x86_64::*; + let r = _mm256_set1_epi64x(ranged as i64); + let mut bad = _mm256_setzero_si256(); + for k in 0..16 { + // SAFETY: inside both (64 each). + let (a, t) = unsafe { (_mm256_loadu_si256(asked.as_ptr().add(4 * k).cast()), _mm256_loadu_si256(taken.as_ptr().add(4 * k).cast())) }; + let t = _mm256_blendv_epi8(t, r, _mm256_cmpgt_epi64(r, t)); + bad = _mm256_or_si256(bad, _mm256_cmpgt_epi64(a, t)); + } + _mm256_testz_si256(bad, bad) == 0 +} + +#[cfg(test)] +mod tests { + use super::Pages; + use std::collections::BTreeMap; + + /// The same answers as the tree it replaces, over random notes and + /// ranges across chunks, sparse and dense. + #[test] + fn answers_as_the_tree_did() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |n: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed % n + }; + for density in [3u64, 30, 95] { + let (mut pages, mut tree) = (Pages::new(), BTreeMap::new()); + let span = 3 * super::CHUNK as u64 + 1000; + let base = 7 * super::CHUNK as u64 - 500; + for asked in 1..span * density / 100 { + let page = (base + next(span)) as usize; + assert_eq!(pages.insert(page, asked), tree.insert(page, asked)); + } + assert_eq!(pages.len(), tree.len()); + for _ in 0..3000 { + let first = (base - 100 + next(span + 200)) as usize; + let short = next(2) == 0; + let last = first + next(if short { 70 } else { 5000 }) as usize; + let want: Vec<(usize, u64)> = tree.range(first..last).map(|(&p, &w)| (p, w)).collect(); + assert_eq!(pages.range(first, last), want); + let limit = next(span); + let taken: Vec = (first..last).map(|_| limit + next(3) * next(span / 4 + 1)).collect(); + let ranged = if next(4) == 0 { next(span) } else { 0 }; + let want = tree.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged)); + assert_eq!(pages.none_newer(first, last, &taken, ranged), want, "[{first}, {last}) ranged {ranged}"); + let page = (base + next(span)) as usize; + assert_eq!(pages.get(page), tree.get(&page).copied()); + } + } + } +} diff --git a/crates/victory-hle/src/modules/dsp/convolve.rs b/crates/victory-hle/src/modules/dsp/convolve.rs index 88fd51438..5ad2dc79b 100644 --- a/crates/victory-hle/src/modules/dsp/convolve.rs +++ b/crates/victory-hle/src/modules/dsp/convolve.rs @@ -111,6 +111,32 @@ impl Aligned { // SAFETY: as above. unsafe { std::slice::from_raw_parts_mut(self.0.as_mut_ptr().cast(), self.0.len() * 16) } } + /// The same memory as half floats (two to a float). + fn halves(&self) -> &[u16] { + // SAFETY: `Line` is 32 u16s' worth of bytes with no padding. + unsafe { std::slice::from_raw_parts(self.0.as_ptr().cast(), self.0.len() * 32) } + } +} + +/// Whether the response is kept as half floats (`VICTORY_DSP_HALF=1`; off by +/// default, as floats). Half the bytes to bring in from memory for every +/// block: 1.1-1.4 times faster where the response is long (measured), the +/// sum then within about 2e-4 of its peak (-73 dB). Off by default because +/// the output is then no longer the floats' to 1e-4 (what +/// `a_mono_convolution_is_computed` holds it to). Needs F16C. +fn half_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| half_can() && std::env::var_os("VICTORY_DSP_HALF").is_some_and(|v| v == "1")) +} + +/// Whether this CPU can sum half floats (AVX2, FMA and F16C). +fn half_can() -> bool { + #[cfg(target_arch = "x86_64")] + return std::arch::is_x86_feature_detected!("avx2") + && std::arch::is_x86_feature_detected!("fma") + && std::arch::is_x86_feature_detected!("f16c"); + #[cfg(not(target_arch = "x86_64"))] + false } /// The real FFTs of 2048 points, forward and inverse, planned once. @@ -128,6 +154,8 @@ pub(super) struct Convolver { /// The response's windows: `parts` rows of 1024 bins, split re/im. h_re: Aligned, h_im: Aligned, + /// The same as half floats instead ([`half_on`]; the floats are then empty). + half: Option<(Aligned, Aligned)>, parts: usize, /// The last `parts` input spectra, a ring of rows; `head` is the newest. x_re: Aligned, @@ -148,6 +176,11 @@ pub(super) struct Convolver { impl Convolver { /// `None` when the response is not in the layout described above. pub(super) fn new(ir: &[f32]) -> Option { + Self::with_half(ir, half_on()) + } + + /// [`Convolver::new`], the response as half floats or not. + fn with_half(ir: &[f32], half: bool) -> Option { if ir.is_empty() || !ir.len().is_multiple_of(N) { return None; } @@ -171,11 +204,26 @@ impl Convolver { h_im.get_mut()[k * B + bin] = if i.is_finite() { i } else { 0.0 }; } } + #[cfg(target_arch = "x86_64")] + let half = half.then(|| { + let to_half = |from: &Aligned| { + let mut to = Aligned::zeros(parts * B / 2); + // SAFETY: F16C is there (`half_on`); both hold parts * B values. + unsafe { to_halves(&from.get()[..parts * B], to.0.as_mut_ptr().cast()) }; + to + }; + let pair = (to_half(&h_re), to_half(&h_im)); + (h_re, h_im) = (Aligned::zeros(0), Aligned::zeros(0)); + pair + }); + #[cfg(not(target_arch = "x86_64"))] + let half = half.then(|| unreachable!()); let (forward, inverse) = plans(); let scratch = forward.get_scratch_len().max(inverse.get_scratch_len()); Some(Self { h_re, h_im, + half, parts, x_re: Aligned::zeros(parts * B), x_im: Aligned::zeros(parts * B), @@ -226,7 +274,12 @@ impl Convolver { let (xr, xi, hr, hi) = (self.x_re.get(), self.x_im.get(), self.h_re.get(), self.h_im.get()); let (yr, yi) = (self.y_re.get_mut(), self.y_im.get_mut()); #[cfg(target_arch = "x86_64")] - let done = if std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("fma") { + let done = if let Some((hr, hi)) = &self.half { + // SAFETY: F16C, AVX2 and FMA are there (`half_on`); rows as below, + // the response's rows of half floats from 64-byte boundaries too. + unsafe { sum_avx2_half(xr, xi, hr.halves(), hi.halves(), &self.rows, yr, yi) }; + true + } else if std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("fma") { // SAFETY: the features are there; every row holds B (a multiple of 32) floats from a 64-byte boundary. unsafe { sum_avx2(xr, xi, hr, hi, &self.rows, yr, yi) }; true @@ -270,6 +323,72 @@ fn sum(xr: &[f32], xi: &[f32], hr: &[f32], hi: &[f32], rows: &[usize], yr: &mut } } +/// Floats to half floats, eight at a time (`n` a multiple of 8). +/// +/// # Safety +/// F16C; `to` holds `from.len()` u16s. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "f16c,avx")] +unsafe fn to_halves(from: &[f32], to: *mut u16) { + use std::arch::x86_64::*; + for (k, eight) in from.chunks_exact(8).enumerate() { + // SAFETY: inside both (the caller's). + unsafe { _mm_storeu_si128(to.add(8 * k).cast(), _mm256_cvtps_ph::<_MM_FROUND_TO_NEAREST_INT>(_mm256_loadu_ps(eight.as_ptr()))) }; + } +} + +/// [`sum_avx2`] with the response as half floats, widened as they are loaded. +/// +/// # Safety +/// F16C, AVX2 and FMA; as [`sum_avx2`], `hr` and `hi` holding the response's +/// rows of `B` halves each from 64-byte boundaries. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2,fma,f16c")] +unsafe fn sum_avx2_half(xr: &[f32], xi: &[f32], hr: &[u16], hi: &[u16], rows: &[usize], yr: &mut [f32], yi: &mut [f32]) { + use std::arch::x86_64::*; + assert!(yr.len() >= B && yi.len() >= B && hr.len() >= rows.len() * B && hi.len() >= rows.len() * B); + assert!(rows.iter().all(|&r| r + B <= xr.len() && r + B <= xi.len())); + let mut bin = 0; + while bin < B { + let zero = _mm256_setzero_ps(); + let (mut r0, mut r1, mut r2, mut r3) = (zero, zero, zero, zero); + let (mut i0, mut i1, mut i2, mut i3) = (zero, zero, zero, zero); + for (k, &row) in rows.iter().enumerate() { + // SAFETY: inside the slices (asserted above), on 16- and 32-byte boundaries. + unsafe { + let (px, pxi) = (xr.as_ptr().add(row + bin), xi.as_ptr().add(row + bin)); + let (ph, phi) = (hr.as_ptr().add(k * B + bin), hi.as_ptr().add(k * B + bin)); + macro_rules! eight { + ($o:expr, $r:ident, $i:ident) => {{ + let (a, b) = (_mm256_load_ps(px.add($o)), _mm256_load_ps(pxi.add($o))); + let c = _mm256_cvtph_ps(_mm_load_si128(ph.add($o).cast())); + let d = _mm256_cvtph_ps(_mm_load_si128(phi.add($o).cast())); + $r = _mm256_fnmadd_ps(b, d, _mm256_fmadd_ps(a, c, $r)); + $i = _mm256_fmadd_ps(b, c, _mm256_fmadd_ps(a, d, $i)); + }}; + } + eight!(0, r0, i0); + eight!(8, r1, i1); + eight!(16, r2, i2); + eight!(24, r3, i3); + } + } + // SAFETY: inside `yr` and `yi`, on 32-byte boundaries. + unsafe { + let (py, pyi) = (yr.as_mut_ptr().add(bin), yi.as_mut_ptr().add(bin)); + _mm256_store_ps(py, r0); + _mm256_store_ps(py.add(8), r1); + _mm256_store_ps(py.add(16), r2); + _mm256_store_ps(py.add(24), r3); + _mm256_store_ps(pyi, i0); + _mm256_store_ps(pyi.add(8), i1); + _mm256_store_ps(pyi.add(16), i2); + _mm256_store_ps(pyi.add(24), i3); + } + bin += 32; + } +} + /// The sum over windows, 32 bins at a time with their sums in registers /// while every window goes by; aligned loads. /// @@ -391,6 +510,30 @@ mod tests { } } + #[test] + fn half_floats_give_the_same_sound() { + if !half_can() { + return; + } + let ir: Vec = (0..48_000).map(|i| (((i as u32).wrapping_mul(2_654_435_761) >> 20) as f32 / 4096.0 - 0.5) * (-(i as f32) / 12_000.0).exp() * 0.05).collect(); + let lay = layout(&ir); + let (mut full, mut half) = (Convolver::with_half(&lay, false).unwrap(), Convolver::with_half(&lay, true).unwrap()); + assert!(half.half.is_some() && full.half.is_none()); + let (mut peak, mut most) = (0f32, 0f32); + for blk in 0..12 { + let input: Vec = (0..B).map(|i| (((i * 31 + blk * 7) % 97) as f32 - 48.0) / 100.0).collect(); + let (mut a, mut b) = (vec![0f32; B], vec![0f32; B]); + full.process(&input, &mut a, 1.0); + half.process(&input, &mut b, 1.0); + for (x, y) in a.iter().zip(&b) { + peak = peak.max(x.abs()); + most = most.max((x - y).abs()); + } + } + // -60 dB of the peak at most (measured: about -73) + assert!(most <= peak * 1e-3, "{most} of {peak}"); + } + #[test] fn a_silent_ring_gives_silence() { let mut c = Convolver::new(&layout(&[1.0, 0.5])).unwrap(); diff --git a/xtask/src/policy.rs b/xtask/src/policy.rs index d4d88be02..75461f567 100644 --- a/xtask/src/policy.rs +++ b/xtask/src/policy.rs @@ -16,6 +16,8 @@ const MAX_ENCODED_RUN: usize = 512; const ALLOWED_EXTENSIONS: &[&str] = &[ "rs", "toml", "md", "txt", "lock", "yml", "yaml", "json", "hlsl", "hlsli", "ps1", "cmd", "sh", "py", + // C source: `crates/victory-formats/csrc` (BCPack's rANS lanes). + "c", ]; const ALLOWED_NAMES: &[&str] = &[ ".gitignore",