From 03175e55e50e38b35e54db0339f491032639be68 Mon Sep 17 00:00:00 2001 From: Matartos Date: Sat, 28 Nov 2026 12:07:33 +0100 Subject: [PATCH 01/19] Document PL Plus development scope and release gates --- docs/PL-PLUS-ROADMAP.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 docs/PL-PLUS-ROADMAP.md diff --git a/docs/PL-PLUS-ROADMAP.md b/docs/PL-PLUS-ROADMAP.md new file mode 100644 index 0000000000..58f49a8c48 --- /dev/null +++ b/docs/PL-PLUS-ROADMAP.md @@ -0,0 +1,28 @@ +# VIctory-NVIDIA PL Plus — development roadmap + +Status: initial upstream baseline, no PL Plus engine features released. + +Upstream: https://github.com/trustno1-coder/VIctory-NVIDIA +Baseline: v2026.11.28.01 / 63b902fe1720a5188ee79d94a88c8de0470f6349. + +## Branches +- `main`: upstream mirror; no local feature commits. +- `pl-plus-dev`: reviewed incremental changes. +- `pl-plus-stable`: tested release candidates only; initially upstream baseline, not a certified build. +- `experimental`: isolated research; no automatic promotion. + +## Priorities +1. PL/EN menu localization, preserving existing options and defaults. +2. Read-only performance diagnostics and documented hardware tests. +3. Hardware profiles validated on RTX 3080 10 GB, i5-12500, 64 GB RAM. +4. Documented launcher interoperability and version metadata. +5. Save safety: backup, integrity verification and explicit restore; no silent overwrite. +6. Evaluate graphics-tool compatibility only with supported interfaces and verified licenses. No compatibility claim without evidence. + +## Release gates +- Preserve upstream notices and GPL-3.0-or-later licensing; distribute corresponding source when required. +- No game files or proprietary third-party SDK binaries in the repository or release packages. +- Record upstream commit and local diff; no forced synchronization of feature branches. +- Pass build and relevant automated tests; record real Windows hardware test results separately. +- Keep previous builds and user data intact. Mark untested features and builds explicitly. +- Do not automatically install new binaries or modify existing configurations. From 393b0136572c362d641879d9d2ea6a97adc5dd5e Mon Sep 17 00:00:00 2001 From: Matartos Date: Sat, 28 Nov 2026 12:09:08 +0100 Subject: [PATCH 02/19] Add read-only upstream metadata and merge-conflict audit --- .github/workflows/pl-plus-upstream-audit.yml | 64 ++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 .github/workflows/pl-plus-upstream-audit.yml diff --git a/.github/workflows/pl-plus-upstream-audit.yml b/.github/workflows/pl-plus-upstream-audit.yml new file mode 100644 index 0000000000..3b879a05e1 --- /dev/null +++ b/.github/workflows/pl-plus-upstream-audit.yml @@ -0,0 +1,64 @@ +name: PL Plus upstream audit + +on: + push: + branches: [pl-plus-dev] + paths: ['.github/workflows/pl-plus-upstream-audit.yml'] + workflow_dispatch: + schedule: + - cron: '17,47 * * * *' + +permissions: + contents: read + +concurrency: + group: pl-plus-upstream-audit + cancel-in-progress: false + +jobs: + audit: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Compare branches without executing repository code + shell: bash + run: | + set -euo pipefail + work="$(mktemp -d)" + cd "$work" + git init -q + git fetch --no-tags https://github.com/trustno1-coder/VIctory-NVIDIA.git main:refs/remotes/upstream/main + git fetch --no-tags https://github.com/Matartos/VIctory-NVIDIA-PL-Plus.git main:refs/remotes/fork/main pl-plus-dev:refs/remotes/fork/dev pl-plus-stable:refs/remotes/fork/stable + { + echo '## Upstream audit' + echo + echo "Upstream: $(git rev-parse upstream/main)" + echo "Mirror: $(git rev-parse fork/main)" + echo "Dev: $(git rev-parse fork/dev)" + echo "Stable: $(git rev-parse fork/stable)" + echo + echo "Upstream commits not in mirror: $(git rev-list --count fork/main..upstream/main)" + echo "Mirror commits not in upstream: $(git rev-list --count upstream/main..fork/main)" + } >> "$GITHUB_STEP_SUMMARY" + if ! git merge-base --is-ancestor fork/main upstream/main; then + echo 'Mirror diverged; manual review required.' >> "$GITHUB_STEP_SUMMARY" + exit 1 + fi + if git merge-base --is-ancestor upstream/main fork/dev; then + echo 'Dev already includes upstream.' >> "$GITHUB_STEP_SUMMARY" + else + if git merge-tree --write-tree fork/dev upstream/main > "$work/merge-check.txt"; then + echo 'Upstream update available; simulated merge has no conflicts. Review required.' >> "$GITHUB_STEP_SUMMARY" + else + echo 'Merge simulation failed or found conflicts. Manual review required.' >> "$GITHUB_STEP_SUMMARY" + exit 1 + fi + fi + echo 'No branches changed. No builds or releases published.' >> "$GITHUB_STEP_SUMMARY" + - name: Check latest release metadata + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + gh api repos/trustno1-coder/VIctory-NVIDIA/releases/latest --jq '"Latest upstream release: " + .tag_name + " (" + .published_at + ")"' >> "$GITHUB_STEP_SUMMARY" From c67be651cf16b24a5604df06e9c179b1078037ae Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 20:49:35 +0000 Subject: [PATCH 03/19] fix(policy): move lowering tests out of lower.rs to stay under the 640 KiB file limit The asset-policy test failed on lower.rs (667380 bytes > 655360). The unit tests move unchanged into emit/lower/tests.rs; no code or test changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- crates/victory-shader/src/emit/lower.rs | 781 +----------------- crates/victory-shader/src/emit/lower/tests.rs | 778 +++++++++++++++++ 2 files changed, 779 insertions(+), 780 deletions(-) create mode 100644 crates/victory-shader/src/emit/lower/tests.rs diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 8f97e871b2..3da122fc14 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -14367,783 +14367,4 @@ fn interp_mode(kind: Barycentric) -> Option { } #[cfg(test)] -mod tests { - use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; - use crate::native::{ - ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, - }; - use crate::{io, ir, resource, structure}; - - const S_ENDPGM: u32 = 0xBF81_0000; - - /// A 128-thread group whose divergent region both reads and writes LDS. With that branch - /// taken by both halves of a wave, the program lowers to wave 32 and the LDS sites meet - /// per wave. Without the branch marked, no meet is emitted in the divergent block. - #[test] - fn half_meet_orders_a_128_thread_lds_region() { - let words = [ - 0x7E02_0281, // v_mov_b32 v1, 1 - 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 - 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc - 0xBF88_0004, // s_cbranch_execz past the LDS pair - 0x36 << 26 | 0x0D << 18, // ds_write_b32 - 1 << 8 | 1, - 0x36 << 26 | 0x36 << 18, // ds_read_b32 - 2 << 24 | 1, - 0xBEFE_040C, // s_mov_b64 exec, s[12:13] - S_ENDPGM, - ]; - let code: Vec = words.into_iter().flat_map(u32::to_le_bytes).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: true, - vgprs: 16, - layout: vec![RootParam { - root: RootType::Constants, - table_offset_dwords: 0, - sgprs: 2, - base_register: 0, - user_data: 0, - slot: 0, - }], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 1 << 15 | 2 << 1, - threads: [128, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, true, 16).unwrap(); - let lds_blocks: Vec = p - .blocks - .iter() - .enumerate() - .filter(|(_, b)| { - b.insts.iter().any(|i| i.name() == "ds_write_b32" || i.name() == "ds_read_b32") - }) - .map(|(i, _)| i) - .collect(); - assert!(!lds_blocks.is_empty(), "the LDS pair did not decode"); - let branch = p - .blocks - .iter() - .position(|b| b.insts.iter().any(|i| i.name() == "s_cbranch_execz")) - .unwrap(); - let mut wide = std::collections::HashSet::new(); - wide.insert(branch); - let st = structure::structure_wide(&p, &wide).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = io::raise(&p, &native).unwrap(); - let was = super::TEST_HOST_WAVE.replace(Some(32)); - let lowered = super::with_half_meets(|| { - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - }) - }); - super::TEST_HOST_WAVE.set(was); - let lowered = lowered.expect("wave 32 with a per-wave meet"); - assert_eq!(lowered.wave_size, Some(32)); - assert!(lowered.half_meets >= 1, "the LDS region did not meet per wave"); - assert!(lowered.group_barriers >= 1, "the entry lost its group barrier"); - for b in &lds_blocks { - assert!( - !lowered.group_sync_blocks.contains(b), - "a group barrier landed inside the divergent LDS block {b}" - ); - } - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = io::raise(&p, &native).unwrap(); - let was = super::TEST_HOST_WAVE.replace(Some(32)); - let plain = super::with_half_meets(|| { - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - }) - }); - super::TEST_HOST_WAVE.set(was); - match plain { - Ok(l) => assert_eq!(l.half_meets, 0, "a meet was emitted where a half may not arrive"), - Err(e) => { - let crate::ShaderError::Unsupported { what, .. } = e else { - panic!("unexpected {e}"); - }; - assert!( - what == "a half-meet where not every lane runs" - || what == "no wave32 lowering for this wave64 program" - || what.ends_with("where not every lane runs"), - "unexpected refusal: {what}" - ); - } - } - } - - #[test] - fn packed_pixel_inputs_find_their_second_row() { - use super::super::container::SigElement; - use super::half_input_partners; - use crate::native::{PsInput, Usage}; - let entry = |row, row2, pack2| PsInput { - usage: Usage::Generic, - row, - mask: 0xF, - attr: row, - flat: false, - fp16: true, - pack2, - row2, - }; - let element = |row| SigElement { - name: "TEXCOORD".into(), - index: row, - kind: 0, - comp: 9, - interp: 2, - row: Some(row), - col: 0, - cols: 4, - usage: 0, - half: true, - }; - // Rows 0 and 3 pack and leave their second row out; 5 names its - // own (6). Unnamed 16-bit rows: 1, 4, 6, 7. - let io = StageIo::Ps { - inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)], - input_addr: 0, - db_shader_control: 0, - patches: vec![], - }; - let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into(); - let p = half_input_partners(&io, &sig); - assert_eq!(p.get(&0), Some(&1)); - assert_eq!(p.get(&3), Some(&4)); - assert_eq!(p.get(&5), None); - } - - /// The packed pedestrian layouts of the title: an element - /// behind another one in its register follows in the first parameter - /// with a dword left, and is not a half of its register's row. - #[test] - fn packed_elements_behind_another_take_the_first_free_dword() { - use super::super::container::SigElement; - use super::packed_half; - let element = |index, row, col, cols| SigElement { - name: "TEXCOORD".into(), - index, - kind: 0, - comp: 9, - interp: 2, - row: Some(row), - col, - cols, - usage: 0, - half: true, - }; - // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel - // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4 - // column 3; parameter 3 (rows 6 and 7) carries it in dword 3. - let sig = vec![ - element(1, 2, 0, 4), - element(2, 3, 0, 4), - element(4, 4, 0, 3), - element(6, 4, 3, 1), - element(3, 5, 0, 4), - element(5, 6, 0, 4), - element(7, 7, 0, 2), - element(9, 9, 0, 3), - element(11, 10, 0, 3), - element(15, 12, 0, 4), - ]; - let packs = [ - (2, Some(3)), - (4, Some(5)), - (6, Some(7)), - (9, Some(10)), - (12, None), - ]; - let at = |a, h| packed_half(&sig, &packs, a, h); - // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3. - assert_eq!(at(4, 2), Some((4, 2))); - assert_eq!(at(4, 3), None); - assert_eq!(at(4, 4), Some((5, 0))); - assert_eq!(at(4, 7), Some((5, 3))); - // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone. - assert_eq!(at(6, 3), Some((6, 3))); - assert_eq!(at(6, 5), Some((7, 1))); - assert_eq!(at(6, 6), Some((4, 3))); - assert_eq!(at(6, 7), None); - // Parameters without such an element are as before. - assert_eq!(at(9, 3), None); - assert_eq!(at(9, 4), Some((10, 0))); - assert_eq!(at(12, 3), Some((12, 3))); - assert_eq!(at(12, 4), None); - // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at - // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1, - // TEXCOORD7. - let sig = vec![ - element(0, 1, 0, 2), - element(7, 1, 2, 2), - element(1, 2, 0, 4), - element(2, 3, 0, 4), - element(4, 4, 0, 3), - ]; - let packs = [(3, Some(4)), (1, Some(2))]; - let at = |a, h| packed_half(&sig, &packs, a, h); - assert_eq!(at(1, 1), Some((1, 1))); - assert_eq!(at(1, 2), Some((2, 0))); - assert_eq!(at(1, 5), Some((2, 3))); - assert_eq!(at(1, 6), Some((1, 2))); - assert_eq!(at(1, 7), Some((1, 3))); - assert_eq!(at(3, 6), Some((4, 2))); - assert_eq!(at(3, 7), None); - // A row no element holds gives nothing, as before. - assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None); - } - - /// Whether a synthetic compute program translates with these input registers. - fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - }) - .map(|_| ()) - } - - /// Lowers a compute program with the root parameters `layout` (in user - /// SGPRs from s0 on) and the used resources `used`. - fn lower_with( - words: &[u32], - layout: Vec, - used: Vec, - ) -> Result { - lower_wave(words, layout, used, false) - } - - /// [`lower_with`] in wave64 if `wave64`. - fn lower_wave( - words: &[u32], - layout: Vec, - used: Vec, - wave64: bool, - ) -> Result { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64, - vgprs: 256, - layout, - used, - io: StageIo::Cs(ComputeIo { - // The layout's user SGPRs (at least two), 512 bytes of LDS. - rsrc2: 1 << 15 | sgprs.max(2) << 1, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, wave64, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - }) - } - - /// Root parameter `slot` in user SGPRs from `user_data` on. - fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { - RootParam { - root, - table_offset_dwords: 0, - sgprs: if root == RootType::Descriptor { 2 } else { 1 }, - base_register: 0, - user_data, - slot, - } - } - - /// Lowers a one-thread compute program that copies four root constants - /// (s0..s3) into v1..v4, runs `body`, and stores v0 to a raw buffer from a - /// descriptor table, so the vector instructions in `body` have an effect. - fn lowers_valu(body: &[u32]) -> Result<(), crate::ShaderError> { - let mut words = vec![ - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], 0 - 0xFA00_0000, - ]; - // v_mov_b32 v1..v4, s0..s3 - words.extend((0..4u32).map(|i| 0x7E00_0200 | (i + 1) << 17 | i)); - words.extend_from_slice(body); - words.extend_from_slice(&[ - 0xE070_0000, // buffer_store_dword v0, off, s[8:11], 0 - 0x8002_0000, - S_ENDPGM, - ]); - let constants = RootParam { - sgprs: 4, - ..root(RootType::Constants, 0, 0) - }; - let buffer = UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 4, - slot: 1, - }; - lower_with( - &words, - vec![constants, root(RootType::Table, 4, 1)], - vec![buffer], - ) - .map(|_| ()) - } - - #[test] - fn the_24_bit_multiplies_lower_both_halves() { - // VOP2 `op v0, v1, v2`: v_mul_i32_i24 and v_mul_u32_u24 (the low - // dword) and v_mul_hi_i32_i24 and v_mul_hi_u32_u24 (the high one). - for op in [0x09u32, 0x0A, 0x0B, 0x0C] { - let word = op << 25 | 2 << 9 | 0x101; - lowers_valu(&[word]).unwrap_or_else(|e| panic!("VOP2 {op:#x}: {e}")); - } - } - - #[test] - fn buffer_cache_invalidations_lower_as_no_ops() { - // MUBUF opcode 0x071/0x072 with no data operand: the title asks the - // host to invalidate its cached view of a buffer. - assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv"); - assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv"); - } - - #[test] - fn sums_of_absolute_differences_lower() { - // VOP3 `op v0, v1, v2, v3`: v_sad_u8, v_sad_hi_u8, v_sad_u16, - // v_sad_u32 and v_msad_u8. - for op in [0x15Au32, 0x15B, 0x15C, 0x15D, 0x171] { - let words = [0xD400_0000 | op << 16, 0x101 | 0x102 << 9 | 0x103 << 18]; - lowers_valu(&words).unwrap_or_else(|e| panic!("VOP3 {op:#x}: {e}")); - } - } - - #[test] - fn a_scalar_carry_chain_reaches_the_select() { - // The high dword of a 64-bit add or subtract, then a select on the - // carry (borrow) the high half leaves in SCC, and a branch on it - // (only code with an effect needs its operands). - let add = [ - 0xBE80_03C1, // s_mov_b32 s0, -1 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0x8000_8100, // s_add_u32 s0, s0, 1 - 0x8201_8001, // s_addc_u32 s1, s1, 0 - 0x8502_0001, // s_cselect_b32 s2, s1, s0 - 0xBF07_8002, // s_cmp_lg_u32 s2, 0 - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE83_0380, // s_mov_b32 s3, 0 - S_ENDPGM, - ]; - let sub = [ - 0xBE80_0380, // s_mov_b32 s0, 0 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0x8080_8100, // s_sub_u32 s0, s0, 1 - 0x8281_8001, // s_subb_u32 s1, s1, 0 - 0x8502_0001, // s_cselect_b32 s2, s1, s0 - 0xBF07_8002, // s_cmp_lg_u32 s2, 0 - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE83_0380, // s_mov_b32 s3, 0 - S_ENDPGM, - ]; - - for words in [add, sub] { - lowers(&words, 0).unwrap(); - } - } - - fn perm_features(selector: u32) -> u64 { - // Synthetic compute shader: - // v0 is the thread ID and can supply a dynamic selector. - // Store the result in LDS to keep the permutation live. - let words = [ - 0x7E02_02FFu32, - 0x817F_34AB, - 0x7E04_02FF, - 0xFE01_56CD, - 0xD744_0003, - 257 | (258 << 9) | (selector << 18), - 0x3408_0082, - 0xD834_0000, - 0x0000_0304, - S_ENDPGM, - ]; - - let code: Vec = words.iter() - .flat_map(|w| w.to_le_bytes()) - .collect(); - - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 1 << 15, - threads: [64, 1, 1], - }), - code, - }; - - let p = ir::build(&native.code, false, 256).unwrap(); - - assert!(p.blocks.iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "v_perm_b32")); - - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - - let io = io::raise(&p, &native).unwrap(); - - let emitted = lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - }).unwrap(); - - let container = - crate::Container::parse(&emitted.dxil).unwrap(); - - let features = - container.part(crate::FourCC::SFI0).unwrap(); - - u64::from_le_bytes(features.data.try_into().unwrap()) - } - - #[test] - fn perm_constant_selector_needs_no_int64() { - assert_eq!(perm_features(128) & 0x8000, 0); - } - - #[test] - fn perm_dynamic_selector_needs_no_int64() { - assert_eq!( - perm_features(256) & 0x8000, - 0, - "dynamic v_perm_b32 must not require INT64" - ); - } - - #[test] - fn a_descriptor_selected_by_scc_picks_its_heap_index() { - // Two buffer descriptors loaded from the table at s0, one picked by - // a root constant (s1) with s_cselect_b64 per half, and loaded - // through by index and stored to LDS so the load is needed. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xF408_0302, - 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 - 0xBF06_8001, // s_cmp_eq_u32 s1, 0 - 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] - 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] - 0xE030_2000, - 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - // Both are structured buffers of dwords in the table's range. - let used = || { - vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }] - }; - lower_with(&words, layout(), used()).unwrap(); - } - - /// Tables of 2D textures at s0 and samplers at s1. - fn texture_tables() -> (Vec, Vec) { - let range = |kind, user_data, slot| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, - user_data, - slot, - }; - ( - vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], - vec![ - range(ResourceType::Srv, 0, 0), - range(ResourceType::Sampler, 1, 1), - ], - ) - } - - #[test] - fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { - use crate::resource::tests::{ - WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, - }; - for (words, wave64) in [ - (WATERFALL_FETCHED_WAVE32, false), - (WATERFALL_FETCHED_WAVE64, true), - (WATERFALL_PICKED_WAVE32, false), - ] { - let (layout, used) = texture_tables(); - let l = lower_wave(words, layout, used, wave64).unwrap(); - // The loop's reads of the first lane became each lane's own - // dwords: no wave operation is left. - assert_eq!(l.nonuniform_handles, 1); - assert!(!l.wave_ops); - } - } - - /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. - pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { - let (layout, mut used) = texture_tables(); - used.push(UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 16, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 0, - slot: 0, - }); - (layout, used) - } - - #[test] - fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { - use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; - for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { - let (layout, used) = texture_and_uav_tables(); - let l = lower_wave(words, layout, used, false).unwrap(); - // One image handle, from the join's per-lane heap index. - assert_eq!(l.nonuniform_handles, 1); - assert!(!l.wave_ops); - } - } - - #[test] - fn scalar_bit_tests_lower() { - // Each tests one bit of a constant into SCC and branches on it (only - // code with an effect needs its operands). - let tail = [ - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE84_0380, // s_mov_b32 s4, 0 - S_ENDPGM, - ]; - let bit_tests: [&[u32]; 4] = [ - &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 - &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 - &[ - 0xBE80_0387, // s_mov_b32 s0, 7 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 - ], - &[ - 0xBE80_0387, // s_mov_b32 s0, 7 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 - ], - ]; - for head in bit_tests { - let words: Vec = head.iter().chain(&tail).copied().collect(); - lowers(&words, 0).unwrap(); - } - } - - #[test] - #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"] - fn a_missing_value_stays_missing_through_two_live_joins() { - let mut words = [ - 0xF490_0180, - 0, // s_memtime s[6:7] - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) - 0xBF85_0001, // skip the first overwrite - 0xBE86_0380, // s_mov_b32 s6, 0 - 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) - 0xBF85_0001, // skip the second overwrite - 0xBE86_0381, // s_mov_b32 s6, 1 - 0xBF07_8006, // s_cmp_lg_u32 s6, 0 - 0xBF85_0001, // use the result to branch - 0xBE83_0380, - S_ENDPGM, - ]; - let group_ids_xy = 3 << 7; - // Compare to a direct read so future timestamp support works in both cases. - let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { - Ok(()) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - }; - let direct = [&words[..2], &words[8..]].concat(); - assert_eq!(refusal(&words), refusal(&direct)); - words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead - lowers(&words, group_ids_xy).expect("dead timestamp"); - } - - #[test] - fn buffer_formats_by_number() { - // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, - // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. - assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); - assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); - assert_eq!( - buffer_format(50), - Some((&[10, 10, 10, 2][..], Numeric::Unorm)) - ); - assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); - assert_eq!( - buffer_format(77), - Some((&[32, 32, 32, 32][..], Numeric::Float)) - ); - // Invalid, past the table. - assert_eq!(buffer_format(0), None); - assert_eq!(buffer_format(78), None); - } - - #[test] - fn packed_buffer_formats_by_number() { - // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, - // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT - // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. - assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); - assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); - assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); - assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); - assert_eq!( - buffer_format(44), - Some((&[2, 10, 10, 10][..], Numeric::Unorm)) - ); - assert_eq!( - buffer_format(45), - Some((&[2, 10, 10, 10][..], Numeric::Snorm)) - ); - assert_eq!( - buffer_format(46), - Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) - ); - assert_eq!( - buffer_format(47), - Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) - ); - assert_eq!( - buffer_format(48), - Some((&[2, 10, 10, 10][..], Numeric::Uint)) - ); - assert_eq!( - buffer_format(49), - Some((&[2, 10, 10, 10][..], Numeric::Sint)) - ); - } - - /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as - /// `legacyF16ToF32` widens it. - fn half(h: u32) -> f32 { - let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); - let v = match e { - 0 => m as f32 * 2f32.powi(-24), - 31 if m == 0 => f32::INFINITY, - 31 => f32::NAN, - _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), - }; - if s == 1 { -v } else { v } - } - - #[test] - fn small_floats_widen_as_halves() { - // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a - // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. - let f11 = |x: u32| half(x << half_shift(11)); - let f10 = |x: u32| half(x << half_shift(10)); - assert_eq!(f11(0), 0.0); - assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal - assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal - assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal - assert_eq!(f11(0x3C0), 1.0); - assert_eq!(f11(0x3E0), 1.5); - assert_eq!(f11(0x7BF), 65024.0); // largest - assert_eq!(f11(0x7C0), f32::INFINITY); - assert!(f11(0x7C1).is_nan()); - assert_eq!(f10(0x001), 2f32.powi(-19)); - assert_eq!(f10(0x020), 2f32.powi(-14)); - assert_eq!(f10(0x1E0), 1.0); - assert_eq!(f10(0x3DF), 64512.0); - assert_eq!(f10(0x3E0), f32::INFINITY); - assert!(f10(0x3FF).is_nan()); - // A 16-bit float is a half already, sign included. - assert_eq!(half(0xBC00 << half_shift(16)), -1.0); - } -} +mod tests; diff --git a/crates/victory-shader/src/emit/lower/tests.rs b/crates/victory-shader/src/emit/lower/tests.rs new file mode 100644 index 0000000000..24efc275c3 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/tests.rs @@ -0,0 +1,778 @@ +use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +/// A 128-thread group whose divergent region both reads and writes LDS. With that branch +/// taken by both halves of a wave, the program lowers to wave 32 and the LDS sites meet +/// per wave. Without the branch marked, no meet is emitted in the divergent block. +#[test] +fn half_meet_orders_a_128_thread_lds_region() { + let words = [ + 0x7E02_0281, // v_mov_b32 v1, 1 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88_0004, // s_cbranch_execz past the LDS pair + 0x36 << 26 | 0x0D << 18, // ds_write_b32 + 1 << 8 | 1, + 0x36 << 26 | 0x36 << 18, // ds_read_b32 + 2 << 24 | 1, + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + S_ENDPGM, + ]; + let code: Vec = words.into_iter().flat_map(u32::to_le_bytes).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 16, + layout: vec![RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 2, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15 | 2 << 1, + threads: [128, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, true, 16).unwrap(); + let lds_blocks: Vec = p + .blocks + .iter() + .enumerate() + .filter(|(_, b)| { + b.insts.iter().any(|i| i.name() == "ds_write_b32" || i.name() == "ds_read_b32") + }) + .map(|(i, _)| i) + .collect(); + assert!(!lds_blocks.is_empty(), "the LDS pair did not decode"); + let branch = p + .blocks + .iter() + .position(|b| b.insts.iter().any(|i| i.name() == "s_cbranch_execz")) + .unwrap(); + let mut wide = std::collections::HashSet::new(); + wide.insert(branch); + let st = structure::structure_wide(&p, &wide).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let was = super::TEST_HOST_WAVE.replace(Some(32)); + let lowered = super::with_half_meets(|| { + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + }); + super::TEST_HOST_WAVE.set(was); + let lowered = lowered.expect("wave 32 with a per-wave meet"); + assert_eq!(lowered.wave_size, Some(32)); + assert!(lowered.half_meets >= 1, "the LDS region did not meet per wave"); + assert!(lowered.group_barriers >= 1, "the entry lost its group barrier"); + for b in &lds_blocks { + assert!( + !lowered.group_sync_blocks.contains(b), + "a group barrier landed inside the divergent LDS block {b}" + ); + } + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let was = super::TEST_HOST_WAVE.replace(Some(32)); + let plain = super::with_half_meets(|| { + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + }); + super::TEST_HOST_WAVE.set(was); + match plain { + Ok(l) => assert_eq!(l.half_meets, 0, "a meet was emitted where a half may not arrive"), + Err(e) => { + let crate::ShaderError::Unsupported { what, .. } = e else { + panic!("unexpected {e}"); + }; + assert!( + what == "a half-meet where not every lane runs" + || what == "no wave32 lowering for this wave64 program" + || what.ends_with("where not every lane runs"), + "unexpected refusal: {what}" + ); + } + } +} + +#[test] +fn packed_pixel_inputs_find_their_second_row() { + use super::super::container::SigElement; + use super::half_input_partners; + use crate::native::{PsInput, Usage}; + let entry = |row, row2, pack2| PsInput { + usage: Usage::Generic, + row, + mask: 0xF, + attr: row, + flat: false, + fp16: true, + pack2, + row2, + }; + let element = |row| SigElement { + name: "TEXCOORD".into(), + index: row, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: true, + }; + // Rows 0 and 3 pack and leave their second row out; 5 names its + // own (6). Unnamed 16-bit rows: 1, 4, 6, 7. + let io = StageIo::Ps { + inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }; + let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into(); + let p = half_input_partners(&io, &sig); + assert_eq!(p.get(&0), Some(&1)); + assert_eq!(p.get(&3), Some(&4)); + assert_eq!(p.get(&5), None); +} + +/// The packed pedestrian layouts of the title: an element +/// behind another one in its register follows in the first parameter +/// with a dword left, and is not a half of its register's row. +#[test] +fn packed_elements_behind_another_take_the_first_free_dword() { + use super::super::container::SigElement; + use super::packed_half; + let element = |index, row, col, cols| SigElement { + name: "TEXCOORD".into(), + index, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col, + cols, + usage: 0, + half: true, + }; + // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel + // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4 + // column 3; parameter 3 (rows 6 and 7) carries it in dword 3. + let sig = vec![ + element(1, 2, 0, 4), + element(2, 3, 0, 4), + element(4, 4, 0, 3), + element(6, 4, 3, 1), + element(3, 5, 0, 4), + element(5, 6, 0, 4), + element(7, 7, 0, 2), + element(9, 9, 0, 3), + element(11, 10, 0, 3), + element(15, 12, 0, 4), + ]; + let packs = [ + (2, Some(3)), + (4, Some(5)), + (6, Some(7)), + (9, Some(10)), + (12, None), + ]; + let at = |a, h| packed_half(&sig, &packs, a, h); + // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3. + assert_eq!(at(4, 2), Some((4, 2))); + assert_eq!(at(4, 3), None); + assert_eq!(at(4, 4), Some((5, 0))); + assert_eq!(at(4, 7), Some((5, 3))); + // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone. + assert_eq!(at(6, 3), Some((6, 3))); + assert_eq!(at(6, 5), Some((7, 1))); + assert_eq!(at(6, 6), Some((4, 3))); + assert_eq!(at(6, 7), None); + // Parameters without such an element are as before. + assert_eq!(at(9, 3), None); + assert_eq!(at(9, 4), Some((10, 0))); + assert_eq!(at(12, 3), Some((12, 3))); + assert_eq!(at(12, 4), None); + // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at + // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1, + // TEXCOORD7. + let sig = vec![ + element(0, 1, 0, 2), + element(7, 1, 2, 2), + element(1, 2, 0, 4), + element(2, 3, 0, 4), + element(4, 4, 0, 3), + ]; + let packs = [(3, Some(4)), (1, Some(2))]; + let at = |a, h| packed_half(&sig, &packs, a, h); + assert_eq!(at(1, 1), Some((1, 1))); + assert_eq!(at(1, 2), Some((2, 0))); + assert_eq!(at(1, 5), Some((2, 3))); + assert_eq!(at(1, 6), Some((1, 2))); + assert_eq!(at(1, 7), Some((1, 3))); + assert_eq!(at(3, 6), Some((4, 2))); + assert_eq!(at(3, 7), None); + // A row no element holds gives nothing, as before. + assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None); +} + +/// Whether a synthetic compute program translates with these input registers. +fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .map(|_| ()) +} + +/// Lowers a compute program with the root parameters `layout` (in user +/// SGPRs from s0 on) and the used resources `used`. +fn lower_with( + words: &[u32], + layout: Vec, + used: Vec, +) -> Result { + lower_wave(words, layout, used, false) +} + +/// [`lower_with`] in wave64 if `wave64`. +fn lower_wave( + words: &[u32], + layout: Vec, + used: Vec, + wave64: bool, +) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 256, + layout, + used, + io: StageIo::Cs(ComputeIo { + // The layout's user SGPRs (at least two), 512 bytes of LDS. + rsrc2: 1 << 15 | sgprs.max(2) << 1, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, wave64, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) +} + +/// Root parameter `slot` in user SGPRs from `user_data` on. +fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs: if root == RootType::Descriptor { 2 } else { 1 }, + base_register: 0, + user_data, + slot, + } +} + +/// Lowers a one-thread compute program that copies four root constants +/// (s0..s3) into v1..v4, runs `body`, and stores v0 to a raw buffer from a +/// descriptor table, so the vector instructions in `body` have an effect. +fn lowers_valu(body: &[u32]) -> Result<(), crate::ShaderError> { + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xFA00_0000, + ]; + // v_mov_b32 v1..v4, s0..s3 + words.extend((0..4u32).map(|i| 0x7E00_0200 | (i + 1) << 17 | i)); + words.extend_from_slice(body); + words.extend_from_slice(&[ + 0xE070_0000, // buffer_store_dword v0, off, s[8:11], 0 + 0x8002_0000, + S_ENDPGM, + ]); + let constants = RootParam { + sgprs: 4, + ..root(RootType::Constants, 0, 0) + }; + let buffer = UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }; + lower_with( + &words, + vec![constants, root(RootType::Table, 4, 1)], + vec![buffer], + ) + .map(|_| ()) +} + +#[test] +fn the_24_bit_multiplies_lower_both_halves() { + // VOP2 `op v0, v1, v2`: v_mul_i32_i24 and v_mul_u32_u24 (the low + // dword) and v_mul_hi_i32_i24 and v_mul_hi_u32_u24 (the high one). + for op in [0x09u32, 0x0A, 0x0B, 0x0C] { + let word = op << 25 | 2 << 9 | 0x101; + lowers_valu(&[word]).unwrap_or_else(|e| panic!("VOP2 {op:#x}: {e}")); + } +} + +#[test] +fn buffer_cache_invalidations_lower_as_no_ops() { + // MUBUF opcode 0x071/0x072 with no data operand: the title asks the + // host to invalidate its cached view of a buffer. + assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv"); + assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv"); +} + +#[test] +fn sums_of_absolute_differences_lower() { + // VOP3 `op v0, v1, v2, v3`: v_sad_u8, v_sad_hi_u8, v_sad_u16, + // v_sad_u32 and v_msad_u8. + for op in [0x15Au32, 0x15B, 0x15C, 0x15D, 0x171] { + let words = [0xD400_0000 | op << 16, 0x101 | 0x102 << 9 | 0x103 << 18]; + lowers_valu(&words).unwrap_or_else(|e| panic!("VOP3 {op:#x}: {e}")); + } +} + +#[test] +fn a_scalar_carry_chain_reaches_the_select() { + // The high dword of a 64-bit add or subtract, then a select on the + // carry (borrow) the high half leaves in SCC, and a branch on it + // (only code with an effect needs its operands). + let add = [ + 0xBE80_03C1, // s_mov_b32 s0, -1 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8000_8100, // s_add_u32 s0, s0, 1 + 0x8201_8001, // s_addc_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + let sub = [ + 0xBE80_0380, // s_mov_b32 s0, 0 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8080_8100, // s_sub_u32 s0, s0, 1 + 0x8281_8001, // s_subb_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + + for words in [add, sub] { + lowers(&words, 0).unwrap(); + } +} + +fn perm_features(selector: u32) -> u64 { + // Synthetic compute shader: + // v0 is the thread ID and can supply a dynamic selector. + // Store the result in LDS to keep the permutation live. + let words = [ + 0x7E02_02FFu32, + 0x817F_34AB, + 0x7E04_02FF, + 0xFE01_56CD, + 0xD744_0003, + 257 | (258 << 9) | (selector << 18), + 0x3408_0082, + 0xD834_0000, + 0x0000_0304, + S_ENDPGM, + ]; + + let code: Vec = words.iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15, + threads: [64, 1, 1], + }), + code, + }; + + let p = ir::build(&native.code, false, 256).unwrap(); + + assert!(p.blocks.iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32")); + + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + + let io = io::raise(&p, &native).unwrap(); + + let emitted = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }).unwrap(); + + let container = + crate::Container::parse(&emitted.dxil).unwrap(); + + let features = + container.part(crate::FourCC::SFI0).unwrap(); + + u64::from_le_bytes(features.data.try_into().unwrap()) +} + +#[test] +fn perm_constant_selector_needs_no_int64() { + assert_eq!(perm_features(128) & 0x8000, 0); +} + +#[test] +fn perm_dynamic_selector_needs_no_int64() { + assert_eq!( + perm_features(256) & 0x8000, + 0, + "dynamic v_perm_b32 must not require INT64" + ); +} + +#[test] +fn a_descriptor_selected_by_scc_picks_its_heap_index() { + // Two buffer descriptors loaded from the table at s0, one picked by + // a root constant (s1) with s_cselect_b64 per half, and loaded + // through by index and stored to LDS so the load is needed. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xF408_0302, + 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] + 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] + 0xE030_2000, + 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + // Both are structured buffers of dwords in the table's range. + let used = || { + vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }] + }; + lower_with(&words, layout(), used()).unwrap(); +} + +/// Tables of 2D textures at s0 and samplers at s1. +fn texture_tables() -> (Vec, Vec) { + let range = |kind, user_data, slot| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, + user_data, + slot, + }; + ( + vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], + vec![ + range(ResourceType::Srv, 0, 0), + range(ResourceType::Sampler, 1, 1), + ], + ) +} + +#[test] +fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { + use crate::resource::tests::{ + WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, + }; + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + (WATERFALL_PICKED_WAVE32, false), + ] { + let (layout, used) = texture_tables(); + let l = lower_wave(words, layout, used, wave64).unwrap(); + // The loop's reads of the first lane became each lane's own + // dwords: no wave operation is left. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } +} + +/// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. +pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { + let (layout, mut used) = texture_tables(); + used.push(UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 16, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }); + (layout, used) +} + +#[test] +fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { + use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; + for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { + let (layout, used) = texture_and_uav_tables(); + let l = lower_wave(words, layout, used, false).unwrap(); + // One image handle, from the join's per-lane heap index. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } +} + +#[test] +fn scalar_bit_tests_lower() { + // Each tests one bit of a constant into SCC and branches on it (only + // code with an effect needs its operands). + let tail = [ + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let bit_tests: [&[u32]; 4] = [ + &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 + &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 + ], + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 + ], + ]; + for head in bit_tests { + let words: Vec = head.iter().chain(&tail).copied().collect(); + lowers(&words, 0).unwrap(); + } +} + +#[test] +#[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"] +fn a_missing_value_stays_missing_through_two_live_joins() { + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // skip the first overwrite + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) + 0xBF85_0001, // skip the second overwrite + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // use the result to branch + 0xBE83_0380, + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + // Compare to a direct read so future timestamp support works in both cases. + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[8..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); + words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead + lowers(&words, group_ids_xy).expect("dead timestamp"); +} + +#[test] +fn buffer_formats_by_number() { + // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, + // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. + assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); + assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); + assert_eq!( + buffer_format(50), + Some((&[10, 10, 10, 2][..], Numeric::Unorm)) + ); + assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); + assert_eq!( + buffer_format(77), + Some((&[32, 32, 32, 32][..], Numeric::Float)) + ); + // Invalid, past the table. + assert_eq!(buffer_format(0), None); + assert_eq!(buffer_format(78), None); +} + +#[test] +fn packed_buffer_formats_by_number() { + // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, + // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT + // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. + assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); + assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); + assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); + assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); + assert_eq!( + buffer_format(44), + Some((&[2, 10, 10, 10][..], Numeric::Unorm)) + ); + assert_eq!( + buffer_format(45), + Some((&[2, 10, 10, 10][..], Numeric::Snorm)) + ); + assert_eq!( + buffer_format(46), + Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) + ); + assert_eq!( + buffer_format(47), + Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) + ); + assert_eq!( + buffer_format(48), + Some((&[2, 10, 10, 10][..], Numeric::Uint)) + ); + assert_eq!( + buffer_format(49), + Some((&[2, 10, 10, 10][..], Numeric::Sint)) + ); +} + +/// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as +/// `legacyF16ToF32` widens it. +fn half(h: u32) -> f32 { + let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); + let v = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 if m == 0 => f32::INFINITY, + 31 => f32::NAN, + _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), + }; + if s == 1 { -v } else { v } +} + +#[test] +fn small_floats_widen_as_halves() { + // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a + // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. + let f11 = |x: u32| half(x << half_shift(11)); + let f10 = |x: u32| half(x << half_shift(10)); + assert_eq!(f11(0), 0.0); + assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal + assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal + assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal + assert_eq!(f11(0x3C0), 1.0); + assert_eq!(f11(0x3E0), 1.5); + assert_eq!(f11(0x7BF), 65024.0); // largest + assert_eq!(f11(0x7C0), f32::INFINITY); + assert!(f11(0x7C1).is_nan()); + assert_eq!(f10(0x001), 2f32.powi(-19)); + assert_eq!(f10(0x020), 2f32.powi(-14)); + assert_eq!(f10(0x1E0), 1.0); + assert_eq!(f10(0x3DF), 64512.0); + assert_eq!(f10(0x3E0), f32::INFINITY); + assert!(f10(0x3FF).is_nan()); + // A 16-bit float is a half already, sign included. + assert_eq!(half(0xBC00 << half_shift(16)), -1.0); +} From 96f0acb51a4bdf0c3d478aaa4581e08902009e7c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:08:15 +0000 Subject: [PATCH 04/19] chore: keep pl-plus-dev files off the Kemerd port branch Both files are unchanged on pl-plus-dev; removing them here keeps the PR to ampere-sm86-perf-exp1 limited to the Kemerd port. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- .github/workflows/pl-plus-upstream-audit.yml | 64 -------------------- docs/PL-PLUS-ROADMAP.md | 28 --------- 2 files changed, 92 deletions(-) delete mode 100644 .github/workflows/pl-plus-upstream-audit.yml delete mode 100644 docs/PL-PLUS-ROADMAP.md diff --git a/.github/workflows/pl-plus-upstream-audit.yml b/.github/workflows/pl-plus-upstream-audit.yml deleted file mode 100644 index 3b879a05e1..0000000000 --- a/.github/workflows/pl-plus-upstream-audit.yml +++ /dev/null @@ -1,64 +0,0 @@ -name: PL Plus upstream audit - -on: - push: - branches: [pl-plus-dev] - paths: ['.github/workflows/pl-plus-upstream-audit.yml'] - workflow_dispatch: - schedule: - - cron: '17,47 * * * *' - -permissions: - contents: read - -concurrency: - group: pl-plus-upstream-audit - cancel-in-progress: false - -jobs: - audit: - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - name: Compare branches without executing repository code - shell: bash - run: | - set -euo pipefail - work="$(mktemp -d)" - cd "$work" - git init -q - git fetch --no-tags https://github.com/trustno1-coder/VIctory-NVIDIA.git main:refs/remotes/upstream/main - git fetch --no-tags https://github.com/Matartos/VIctory-NVIDIA-PL-Plus.git main:refs/remotes/fork/main pl-plus-dev:refs/remotes/fork/dev pl-plus-stable:refs/remotes/fork/stable - { - echo '## Upstream audit' - echo - echo "Upstream: $(git rev-parse upstream/main)" - echo "Mirror: $(git rev-parse fork/main)" - echo "Dev: $(git rev-parse fork/dev)" - echo "Stable: $(git rev-parse fork/stable)" - echo - echo "Upstream commits not in mirror: $(git rev-list --count fork/main..upstream/main)" - echo "Mirror commits not in upstream: $(git rev-list --count upstream/main..fork/main)" - } >> "$GITHUB_STEP_SUMMARY" - if ! git merge-base --is-ancestor fork/main upstream/main; then - echo 'Mirror diverged; manual review required.' >> "$GITHUB_STEP_SUMMARY" - exit 1 - fi - if git merge-base --is-ancestor upstream/main fork/dev; then - echo 'Dev already includes upstream.' >> "$GITHUB_STEP_SUMMARY" - else - if git merge-tree --write-tree fork/dev upstream/main > "$work/merge-check.txt"; then - echo 'Upstream update available; simulated merge has no conflicts. Review required.' >> "$GITHUB_STEP_SUMMARY" - else - echo 'Merge simulation failed or found conflicts. Manual review required.' >> "$GITHUB_STEP_SUMMARY" - exit 1 - fi - fi - echo 'No branches changed. No builds or releases published.' >> "$GITHUB_STEP_SUMMARY" - - name: Check latest release metadata - shell: bash - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - gh api repos/trustno1-coder/VIctory-NVIDIA/releases/latest --jq '"Latest upstream release: " + .tag_name + " (" + .published_at + ")"' >> "$GITHUB_STEP_SUMMARY" diff --git a/docs/PL-PLUS-ROADMAP.md b/docs/PL-PLUS-ROADMAP.md deleted file mode 100644 index 58f49a8c48..0000000000 --- a/docs/PL-PLUS-ROADMAP.md +++ /dev/null @@ -1,28 +0,0 @@ -# VIctory-NVIDIA PL Plus — development roadmap - -Status: initial upstream baseline, no PL Plus engine features released. - -Upstream: https://github.com/trustno1-coder/VIctory-NVIDIA -Baseline: v2026.11.28.01 / 63b902fe1720a5188ee79d94a88c8de0470f6349. - -## Branches -- `main`: upstream mirror; no local feature commits. -- `pl-plus-dev`: reviewed incremental changes. -- `pl-plus-stable`: tested release candidates only; initially upstream baseline, not a certified build. -- `experimental`: isolated research; no automatic promotion. - -## Priorities -1. PL/EN menu localization, preserving existing options and defaults. -2. Read-only performance diagnostics and documented hardware tests. -3. Hardware profiles validated on RTX 3080 10 GB, i5-12500, 64 GB RAM. -4. Documented launcher interoperability and version metadata. -5. Save safety: backup, integrity verification and explicit restore; no silent overwrite. -6. Evaluate graphics-tool compatibility only with supported interfaces and verified licenses. No compatibility claim without evidence. - -## Release gates -- Preserve upstream notices and GPL-3.0-or-later licensing; distribute corresponding source when required. -- No game files or proprietary third-party SDK binaries in the repository or release packages. -- Record upstream commit and local diff; no forced synchronization of feature branches. -- Pass build and relevant automated tests; record real Windows hardware test results separately. -- Keep previous builds and user data intact. Mark untested features and builds explicitly. -- Do not automatically install new binaries or modify existing configurations. From 970bcbc1b0e33ed58d7fc9d3ff518c38531f362b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:08:15 +0000 Subject: [PATCH 05/19] perf(texture): VICTORY_STAGING_NO_ZERO, staging pieces not zeroed twice (off by default) Ported from Kemerd/VIctory-NVIDIA-RT rt-test-11 (0549d44c330bf0a1f808f8b012d8e22168dfad91), GPL-3.0. A pooled staging piece used before was zero-filled when handed out and then written again by the detiling. With VICTORY_STAGING_NO_ZERO=1 the fill is left out only where detile_covers shows the detiling writes every byte the copies read (row bytes, rows and depth of each subresource from GetCopyableFootprints). A piece no detiling wrote whole is zero-filled where its copy is recorded (record_upload and PreludeUpload::record), under the staging's last lock. A failed detile zero-fills the remaining subresources. The card's detile path is unchanged. A 5-second log line counts pieces left, zeroed at record and zeroed when made. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- crates/victory-gpu/src/host.rs | 1 + crates/victory-gpu/src/pool.rs | 59 ++++++++++--- crates/victory-gpu/src/texture.rs | 142 ++++++++++++++++++++++++++++-- 3 files changed, 183 insertions(+), 19 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 276173b4c4..b5fdf85404 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -10474,6 +10474,7 @@ impl Meter { crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20 ); } + crate::texture::staging_zeros_line(); let served = crate::descriptor::host::SERVED.each_ref().map(|n| n.swap(0, Ordering::Relaxed)); if served[0] + served[3] > 0 { tracing::info!( diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 93d92ae68c..2588776070 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -653,9 +653,33 @@ impl Drop for StagingPiece { } } -/// `bytes` of upload memory, all zeros: the buffer it lies in, where in -/// that buffer, and its mapping. `None`: not pooled. -pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPiece, ID3D12Resource, u64, *mut u8)> { +/// Whether a staging piece the detiling is known to write whole may be +/// handed out as it is, its zeros left to the detiling or to a fill where +/// a copy from it is recorded (`VICTORY_STAGING_NO_ZERO=1`, off by +/// default; see `crate::texture::Staging::zero_if_unwritten`). Without it +/// every piece cut from a part of a block used before is zero-filled when +/// it is handed out, and the detiling then writes the same bytes again: +/// upload memory written twice per texture byte, on the thread that makes +/// the staging buffer. It saves thread time of the texture pass and bytes +/// written, not frame time: judge it by microseconds per upload. +/// +/// Ported from Kemerd/VIctory-NVIDIA-RT `rt-test-11` +/// (0549d44c330bf0a1f808f8b012d8e22168dfad91), GPL-3.0; docs/KEMERD-AUDIT.md. +pub(crate) fn no_zero() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_STAGING_NO_ZERO").is_some_and(|v| v == "1")) +} + +/// `bytes` of upload memory: the buffer it lies in, where in that buffer, +/// its mapping, and whether the piece was used before. All zeros, unless +/// `leave` and it was used before ([`no_zero`]): then it holds what it held, +/// and the caller sees to every byte a copy reads from it. `None`: not +/// pooled. +pub(crate) fn staging( + host: &crate::host::Host, + bytes: u64, + leave: bool, +) -> Option<(StagingPiece, ID3D12Resource, u64, *mut u8, bool)> { if !on() { return None; } @@ -676,13 +700,13 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi let owned = StagingPiece(piece); // SAFETY: the piece lies in the block's mapping. let data = unsafe { memory.1.add(piece.start as usize) }; - if again { + if again && !leave { // What is not detiled into it (an unmapped texture) uploads zeros, // as from a buffer of its own. // SAFETY: the piece is ours alone. unsafe { std::ptr::write_bytes(data, 0, bytes as usize) }; } - Some((owned, memory.0, piece.start, data)) + Some((owned, memory.0, piece.start, data, again)) } /// An object the host texture holds and releases when it goes: its piece @@ -1615,12 +1639,12 @@ mod tests { let stop = std::sync::atomic::AtomicBool::new(false); let mut ms = Vec::new(); let mut keep = Vec::new(); - keep.extend(staging(host, 64 << 10)); + keep.extend(staging(host, 64 << 10, false)); std::thread::scope(|s| { s.spawn(|| { let mut held = std::collections::VecDeque::new(); while !stop.load(Ordering::Relaxed) { - held.extend(staging(host, 8 << 20)); + held.extend(staging(host, 8 << 20, false)); if held.len() > 64 { held.pop_front(); } @@ -1629,7 +1653,7 @@ mod tests { std::thread::sleep(std::time::Duration::from_millis(100)); for _ in 0..1000 { let began = std::time::Instant::now(); - keep.extend(staging(host, 64 << 10)); + keep.extend(staging(host, 64 << 10, false)); ms.push(began.elapsed().as_secs_f64() * 1e3); } stop.store(true, Ordering::Relaxed); @@ -1710,16 +1734,16 @@ mod tests { for t in 0..8u8 { s.spawn(move || { // 8 of 8 MiB a thread: 64 MiB each, so new blocks are made. - let pieces: Vec<_> = (0..8).filter_map(|_| staging(host, BYTES as u64)).collect(); + let pieces: Vec<_> = (0..8).filter_map(|_| staging(host, BYTES as u64, false)).collect(); assert_eq!(pieces.len(), 8); - for (_, _, _, data) in &pieces { + for (_, _, _, data, _) in &pieces { // SAFETY: the piece's mapping, ours alone. unsafe { assert!(looked(*data).all(|b| b == 0), "a piece is not zeros"); std::ptr::write_bytes(*data, t + 1, BYTES); } } - for (_, _, _, data) in &pieces { + for (_, _, _, data, _) in &pieces { assert!(looked(*data).all(|b| b == t + 1), "another thread wrote this piece"); } }); @@ -1754,13 +1778,22 @@ mod tests { assert_eq!(resting(), before + 1); // SAFETY: the piece's mapping, 4096 bytes of it ours. unsafe { - let (piece, _, at, data) = staging(host, 4096).unwrap(); + let (piece, _, at, data, _) = staging(host, 4096, false).unwrap(); assert!(at.is_multiple_of(512)); std::ptr::write_bytes(data, 0xAB, 4096); drop(piece); lock(&STAGING).rested(u64::MAX); - let (_piece, _, _, data) = staging(host, 4096).unwrap(); + let (piece, _, _, data, again) = staging(host, 4096, false).unwrap(); + assert!(again); assert!((0..4096).all(|i| *data.add(i) == 0)); + // Left as it was (`VICTORY_STAGING_NO_ZERO`): what it held, and + // said to have been used before. + std::ptr::write_bytes(data, 0xCD, 4096); + drop(piece); + lock(&STAGING).rested(u64::MAX); + let (_piece, _, _, data, again) = staging(host, 4096, true).unwrap(); + assert!(again); + assert!((0..4096).all(|i| *data.add(i) == 0xCD)); // SAFETY: plain query. assert!(host.device.GetDeviceRemovedReason().is_ok()); } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 7254d31f1d..186b91ac4f 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -101,6 +101,48 @@ pub(crate) struct Staging { /// (and the levels' mask and the pattern tables after them), and this /// what the card detiles them into and the list copies from. gpu: Option, + /// With `VICTORY_STAGING_NO_ZERO=1` ([`crate::pool::no_zero`]): the + /// piece was used before and was handed out as it was, and nothing has + /// written all of it since. The detiling clears it when it has written + /// every subresource; a copy recorded from the buffer while it is still + /// set zero-fills the buffer first ([`Staging::zero_if_unwritten`]). + unzeroed: std::sync::atomic::AtomicBool, +} + +/// Since the last pass line, with [`crate::pool::no_zero`]: staging pieces +/// handed out without their zero-fill, those zero-filled where a copy from +/// them was recorded (nothing had detiled them whole), and those +/// zero-filled when made because the detiling would not write all a copy +/// reads ([`detile_covers`]). +pub(crate) static STAGING_ZEROS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// The line of [`STAGING_ZEROS`], with the pass's 5-second lines. +pub(crate) fn staging_zeros_line() { + use std::sync::atomic::Ordering::Relaxed; + if !crate::pool::no_zero() { + return; + } + let [left, at_record, at_making] = [0, 1, 2].map(|i| STAGING_ZEROS[i].swap(0, Relaxed)); + if left + at_record + at_making > 0 { + tracing::info!( + "staging pieces used before, in the last 5 seconds (VICTORY_STAGING_NO_ZERO=1): {left} handed out without \ + their zero-fill, {at_record} of them zero-filled where a copy was recorded (nothing had detiled them whole), \ + {at_making} zero-filled when made (the detiling would not write all a copy reads)" + ); + } +} + +/// Whether detiling writes every byte the copies of a staging buffer read: +/// for each subresource, the level's (bytes a row, rows, depth) as the +/// detiling writes them (`victory_formats::texture::Layout::detile` writes +/// `width * element_bytes` bytes of each of `height` rows of each of `depth` +/// slices, or returns before writing), against the copy's (bytes a row, +/// rows, depth) from `GetCopyableFootprints`. A level the layout does not +/// have (`None`) covers nothing. +fn detile_covers(parts: impl IntoIterator, (u64, u32, u32))>) -> bool { + parts.into_iter().all(|(level, (row_bytes, rows, depth))| { + level.is_some_and(|(written, high, deep)| written >= row_bytes && high >= rows && deep >= depth) + }) } /// A texture's detiling on the card ([`Staging::gpu`]). @@ -1145,6 +1187,7 @@ impl PreludeUpload { /// Records the copy of the staging buffer into the host texture on /// `list` (the prelude), the host texture in the copy destination state. pub(crate) fn record(&self, list: &ID3D12GraphicsCommandList) { + self.staging.zero_if_unwritten(); let texture = &self.copy.texture; // The staging buffer lives as long as `self.staging`, which the // list's steps hold until it is reset. @@ -1184,6 +1227,9 @@ fn record_upload( ) { use std::sync::atomic::Ordering::Relaxed; const COPY_DEST: u32 = 0x400; + // (Recorded before the check that detiles it: its zeros now, if it was + // handed out without them.) + staging.zero_if_unwritten(); // A texture cut from a block may lie where another did: what the card // holds of that one is done with before the first upload into this one. if !staging.uploaded.load(Relaxed) && crate::pool::is_pooled(texture) { @@ -1991,6 +2037,9 @@ impl Staging { DETILED[1].fetch_add(size as u64, Relaxed); DETILED[2].fetch_add(1, Relaxed); let _timed = DetileTimed(started); + // (Never set without `VICTORY_STAGING_NO_ZERO`.) + let unzeroed = self.unzeroed.load(Relaxed); + let mut failed = false; for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { let (mip, slice) = self.part(i); let f = footprint.Footprint; @@ -2009,14 +2058,49 @@ impl Staging { linear.fill(0); continue; } + // A piece handed out as it was (`unzeroed`): after a failure + // this subresource and every later one are zeros, as a piece + // zero-filled when made would hold them. + if failed { + linear.fill(0); + continue; + } if let Err(e) = self.layout .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) { tracing::warn!(?e, mip, slice, "texture not detiled"); - return; + if !unzeroed { + return; + } + linear.fill(0); + failed = true; } } + // Every byte a copy reads is written now ([`detile_covers`]). + if unzeroed { + self.unzeroed.store(false, Relaxed); + } + } + + /// Where a copy from the staging buffer is recorded: a piece handed out + /// without its zero-fill that nothing has detiled whole (the texture's + /// memory was never mapped, or its read failed) is zero-filled now, as + /// it would have been when made, so the copy uploads zeros and not the + /// bytes of the texture that used the piece before. Under `last`'s + /// lock, as the detiling writes. + fn zero_if_unwritten(&self) { + use std::sync::atomic::Ordering::Relaxed; + if !self.unzeroed.load(Relaxed) { + return; + } + let _last = self.last.lock().unwrap_or_else(|e| e.into_inner()); + if self.unzeroed.swap(false, Relaxed) { + // SAFETY: the staging buffer's own bytes of its mapping, written + // only under `last`'s lock, which is held. + unsafe { std::ptr::write_bytes(self.data, 0, self.bytes as usize) }; + STAGING_ZEROS[1].fetch_add(1, Relaxed); + } } } @@ -2424,6 +2508,9 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; let mut rows = vec![0u32; count as usize]; let mut total = 0; + // With `VICTORY_STAGING_NO_ZERO`, the bytes of each row a copy reads too. + let no_zero = crate::pool::no_zero(); + let mut row_bytes = if no_zero { vec![0u64; count as usize] } else { Vec::new() }; // SAFETY: outputs for `count` subresources. unsafe { host.device.GetCopyableFootprints( @@ -2433,10 +2520,24 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O 0, Some(footprints.as_mut_ptr()), Some(rows.as_mut_ptr()), - None, + if no_zero { Some(row_bytes.as_mut_ptr()) } else { None }, Some(&mut total), ); } + // A pooled piece may be handed out without its zero-fill only where + // the detiling writes all that the copies read; subresources counted + // as `Staging::part` counts them. + let leave = no_zero && { + let levels = mips - first; + detile_covers((0..count as usize).map(|i| { + let mip = first + i as u32 % levels; + let level = layout + .mips + .get(mip as usize) + .map(|m| (u64::from(m.width) * u64::from(layout.desc.element_bytes), m.height, m.depth)); + (level, (row_bytes[i], rows[i], footprints[i].Footprint.Depth)) + })) + }; // On the card's way (`VICTORY_GPU_DETILE`): the dispatches, if every // subresource can be detiled so, and the buffer they write. Only full // textures starting at mip 0 use the GPU path so `footprints` matches @@ -2459,9 +2560,14 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O None }; let upload_bytes = gpu.as_ref().map_or(total, |g| g.raw.bytes); - let pooled_piece = if gpu.is_some() { None } else { crate::pool::staging(host, upload_bytes) }; - let (piece, buffer, base, data) = match pooled_piece { - Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data), + let pooled_piece = if gpu.is_some() { None } else { crate::pool::staging(host, upload_bytes, leave) }; + let (piece, buffer, base, data, unzeroed) = match pooled_piece { + Some((piece, buffer, base, data, again)) => { + if no_zero && again { + STAGING_ZEROS[if leave { 0 } else { 2 }].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + (Some(piece), buffer, base, data, leave && again) + } None => { let speculative = PICKING.get().is_some() && !BAKING.get(); if crate::residency::upload_refused() @@ -2477,7 +2583,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O d.Width, d.Height, d.DepthOrArraySize, d.Format.0 ) }); - (None, buffer, 0, data) + (None, buffer, 0, data, false) } }; if let Some(gpu) = &gpu { @@ -2519,6 +2625,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O waiting: std::sync::atomic::AtomicU64::new(0), exact: std::sync::atomic::AtomicBool::new(BAKING.get()), gpu, + unzeroed: std::sync::atomic::AtomicBool::new(unzeroed), }); map.insert(resource as usize, s.clone()); Some(s) @@ -3002,3 +3109,26 @@ mod allocation_costs { } } } + +/// [`detile_covers`]: when a staging piece may keep what it held. +#[cfg(test)] +mod detile_covers_tests { + use super::detile_covers; + + #[test] + fn a_piece_is_left_only_where_the_detiling_writes_every_byte_read() { + // Equal rows, rows and slices: covered. + assert!(detile_covers([(Some((256, 16, 1)), (256, 16, 1)), (Some((128, 8, 1)), (128, 8, 1))])); + // The detiling writing more than the copy reads (a wider level than + // the footprint's rows) still covers. + assert!(detile_covers([(Some((272, 17, 1)), (256, 16, 1))])); + // A row more, fewer bytes a row, or fewer slices than the copy reads: not. + assert!(!detile_covers([(Some((256, 16, 1)), (256, 17, 1))])); + assert!(!detile_covers([(Some((240, 16, 1)), (256, 16, 1))])); + assert!(!detile_covers([(Some((256, 16, 4)), (256, 16, 8))])); + // A level the layout does not have covers nothing. + assert!(!detile_covers([(Some((256, 16, 1)), (256, 16, 1)), (None, (16, 1, 1))])); + // No subresources: nothing read. + assert!(detile_covers([])); + } +} From 19b484b1cb62eb6089a6b12a9ebdf64675d09622 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:08:15 +0000 Subject: [PATCH 06/19] docs: Kemerd rt-test-11 audit (sampler table already present, staging no-zero ported) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- docs/KEMERD-AUDIT.md | 113 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 docs/KEMERD-AUDIT.md diff --git a/docs/KEMERD-AUDIT.md b/docs/KEMERD-AUDIT.md new file mode 100644 index 0000000000..d5a09165b6 --- /dev/null +++ b/docs/KEMERD-AUDIT.md @@ -0,0 +1,113 @@ +# Audyt Kemerd/VIctory-NVIDIA-RT (RT wyłączony) + +Źródło: https://github.com/Kemerd/VIctory-NVIDIA-RT, tag `rt-test-11` += `0549d44c330bf0a1f808f8b012d8e22168dfad91`. Licencja: GPL-3.0, ta sama co nasza. +Baza porównania: `ampere-sm86-perf-exp1` @ `49f164c66110351f18a22b7f16f694eba605e021`. + +Każdy przenoszony mechanizm jest za własnym przełącznikiem, domyślnie wyłączony. +Rollback: nie ustawiać przełącznika albo cofnąć commit (`git revert`). + +## 1. VICTORY_PIPELINE_SAMPLER_TABLE: ALREADY PRESENT (inny mechanizm) + +Problem, który rozwiązuje Kemerd: pipeline'y ze statycznymi samplerami omijają bibliotekę +pipeline'ów (`library::with_static_samplers`), bo sterownik NVIDIA zapisuje w PSO pozycje +samplerów w swojej tabeli, a te pozycje różnią się między procesami. Kemerd podaje, że +około 1100 PSO było kompilowanych od nowa przy każdym starcie. + +Kemerd, `crates/victory-gpu/src/pipeline/host.rs`: `sampler_table()`, `sampler_key()`, +`table_sampler()`, `sampler_block()`. Samplery statyczne zamienia na tablicę w ogonie sterty +samplerów (`SAMPLER_TAIL = 256`), co wymaga zmian w `descriptor/host.rs` (`HostHeap::new`) i +`draw.rs` (`sampler_table`). Gdy w stercie nie ma miejsca, draw jest pomijany +(`sampler_refused`). + +U nas: `crates/victory-gpu/src/pipeline/samplers.rs`, `VICTORY_SAMPLER_ORDER`, domyślnie +WŁĄCZONY. `prime()` (wołane z `host.rs`, tworzenie urządzenia) tworzy wszystkie znane +samplery statyczne w stałej kolejności z pliku `static-samplers.txt`, zanim powstanie +jakikolwiek pipeline. `know()` (`pipeline/host.rs`, `shader_cache.rs`) dopisuje nowe na końcu. +Pozycje w tabeli sterownika są więc takie same w każdym procesie i dysk-cache sterownika +znajduje PSO ponownie. Kolejność wchodzi do odcisku cache (`known.rs`, `samplers::order()`). +Ten moduł powstał w upstreamie (64d4931, 2026-11-27) po rozgałęzieniu Kemerd. W `rt-test-11` +nie ma `pipeline/samplers.rs`. + +Klucz i samplery: +- Kemerd `SamplerKey` = 13 słów (filtr, 3 tryby adresowania, bias, anizotropia, porównanie, + kolor ramki jako 4 floaty RGBA, min/max LOD). +- Nasz `Words` = 10 słów, to samo, ale kolor ramki jako enum `D3D12_STATIC_BORDER_COLOR` + (statyczne samplery mają tylko enum). Dwa samplery różniące się czymkolwiek, co zmienia + obraz, dostają różne słowa. Identyczne trafiają w ten sam wpis. + +Różnica, która zostaje: u nas te PSO nadal idą przez `CreatePipelineState`, ale trafiają w +dysk-cache sterownika, a nie w `LoadGraphicsPipeline` z naszej biblioteki. Pomiar z +`samplers.rs`: 120 PSO w 13,6 s na zimno, potem 0,6 s w tej samej kolejności. Przeniesienie +wersji Kemerd zmieniłoby sterty deskryptorów i dodałoby ryzyko pominiętych drawów. Nie +przenoszę. + +Jak porównać kompilacje: linia logu `host pipeline library saved` (`library.rs`, pola +`made`, `loaded`, `started_early`) oraz `static samplers made in the order of the cache's +list` (`samplers.rs`). + +## 2. VICTORY_STAGING_NO_ZERO: IMPLEMENTED (ten PR) + +Kemerd: `pool.rs` `no_zero()`, `staging(.., leave)`; `texture.rs` `detile_covers()`, +`Staging::unzeroed`, `Staging::zero_if_unwritten()`, `staging_zeros_line()`. +U nas po zmianie: te same nazwy w `crates/victory-gpu/src/pool.rs` i +`crates/victory-gpu/src/texture.rs`, linia logu wołana z `host.rs` (blok 5-sekundowy). +Zależność od RT: brak, to ścieżka uploadu tekstur. + +Co robi: kawałek bloku staging użyty wcześniej był zerowany przy wydaniu, a potem detiling +pisał te same bajty drugi raz. Z przełącznikiem zerowanie jest pomijane, ale tylko gdy da się +wykazać, że detiling zapisze każdy bajt czytany przez GPU. + +Dowód pokrycia: +1. `victory_formats::texture::Layout::detile` (`walk`) dla każdego `z < depth` i `y < height` + kopiuje `width * element_bytes` bajtów (przebiegi `runs` dzielą cały zakres `[0, bytes)`). + Wszystkie kontrole rozmiaru są przed pierwszym zapisem, więc błąd = nic nie zapisane. +2. `CopyTextureRegion` z footprintu czyta w każdym wierszu tylko `RowSizeInBytes`, a nie + `RowPitch`. Wypełnienie do pitcha, przerwy między podzasobami (wyrównanie 512) i ogon + kawałka nie są czytane. +3. `detile_covers` porównuje dla każdego podzasobu (`mip = first + i % levels`, tak jak + `Staging::part`) wartości z layoutu (`width * element_bytes`, `height`, `depth`) z + `GetCopyableFootprints` (`RowSizeInBytes`, `NumRows`, `Depth`). Jeśli choć jeden podzasób + nie jest pokryty, kawałek jest zerowany jak dawniej (licznik `at_making`). +4. Mipy, których tytuł nie trzyma, są jawnie zerowane w pętli (`linear.fill(0)`). Błąd + detilingu w połowie: reszta podzasobów jest zerowana, tak jak w kawałku wyzerowanym przy + wydaniu. +5. Gdy kopia jest nagrywana, zanim cokolwiek zdetilowało kawałek w całości (pamięć + niezmapowana, nieudany odczyt), `zero_if_unwritten` zeruje bufor pod blokadą `last`. + Wołane w `record_upload` i `PreludeUpload::record`, czyli w obu miejscach, które kopiują + ze staging. `Through` (kopie aliasów) i klatki filmów mają własne bufory. +6. Ścieżka GPU (`VICTORY_GPU_DETILE`) nie bierze kawałków z puli, więc się nie zmienia. + +Ryzyko, gdyby dowód był błędny: na teksturze na chwilę widać bajty innej tekstury zamiast +czerni. Dlatego przełącznik jest domyślnie wyłączony. + +Pomiar: linia co sekundę `texture detiling per frame: on the PC X ms for Y MB` oraz linia co +5 s `staging pieces used before ... (VICTORY_STAGING_NO_ZERO=1)` (tylko z przełącznikiem). + +Test jednostkowy: `texture::detile_covers_tests`, `pool::tests::a_texture_gives_its_piece_back_when_it_goes` +(sprawdza, że `leave=false` zeruje, a `leave=true` zostawia). + +## 3. VICTORY_REFRESH_SET: DISCOVERED (osobny PR) + +Kemerd `host/lean.rs`. Jeden `Step::RefreshSet` na listę zamiast około 245 `Step::Refresh`. +Dotyka `Memory::bring_up` (`memory.rs`) i wszystkich przejść po krokach submisji. Do +osobnego audytu. + +## 4. VICTORY_SEND_THREAD: DISCOVERED (osobny PR) + +Kemerd `host/send_thread.rs` (320 linii) i 5 miejsc w `host.rs`. Zależności u nas: +1. Działa tylko z `late()` (`host.rs`, `late_stage()`): `VICTORY_LATE_WAIT` 1/2/3 albo relay + (`shadow::relay()`). Bez tego przełącznik nic nie robi. +2. Kolejność submitów: wartość fence rezerwuje wątek submitujący (`*submitted += 1`), a + `Flight` trafia do `line()` z tego wątku, przed następną submisją. Wątek wysyłający robi + tylko `ExecuteCommandLists` + `Signal` + `awake::sent` + `card_sent`. U nas ten ogon jest + w bloku `if late {` w `Host::submit` (okolice `awake::sent`). +3. Fence: każda wartość musi zostać zasygnalizowana, także po panice i pustej liście, bo + inaczej czekanie na flight wisi. +4. `card_before` (`host.rs`) i inne ścieżki wkładające listy na kolejkę muszą wołać + `send_thread::wait_idle()` przed swoim `ExecuteCommandLists`. U nas są dodatkowe + wywołania `ExecuteCommandLists` (`host.rs`, `pool.rs`), które trzeba zinwentaryzować. +5. Czas życia zasobów: listy są zamknięte, a bajty zamrożone przez `send::take`, zanim job + trafi do wątku. Zasoby trzyma lista do resetu po fence, więc wątek nic nie zwalnia. + +Nasz `host.rs` różni się od Kemerd o około 2700 linii. Port ręczny, osobny PR. From a376dd7d7fc801b52481d065d3acf981fbabcdf6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:13:54 +0000 Subject: [PATCH 07/19] perf(pipeline): VICTORY_PIPELINE_WAIT_BACKLOG, no draw wait past n queued (off by default) Ported from Kemerd/VIctory-NVIDIA-RT rt-test-11 (0549d44c330bf0a1f808f8b012d8e22168dfad91), GPL-3.0. With more pipelines queued than the workers can make within the frame's budget, a draw's wait cannot end in time and only costs the frame. Past n queued, the draw is dropped at once, as when the budget runs out, and drawn again in a later frame. Graphics only: dispatches and passes over the screen are never left out by this rule. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- crates/victory-gpu/src/pipeline/make.rs | 45 +++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 41ba271d60..d20bf097a3 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -518,6 +518,36 @@ fn shared_budget() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_SHARED").is_none_or(|v| v != "0")) } +/// `VICTORY_PIPELINE_WAIT_BACKLOG=n` (read once, unset by default): past +/// `n` pipelines queued, a draw's pipeline is not waited for at all and the +/// draw is dropped at once, as it is when the budget runs out; it is drawn +/// again in a later frame. Unset, every draw waits as before. +/// +/// With more queued than the workers can make within the budget, the +/// pipeline asked for here will not arrive in time, and waiting only costs +/// the frame (Kemerd/VIctory-NVIDIA-RT rt-test-11, 0549d44c, GPL-3.0: a run +/// spent the whole 500 ms in every frame for two minutes while 470 were +/// queued; another sat at 3 fps with 600 queued). Only graphics: passes over +/// the screen keep their own budget, and a dispatch is never dropped here +/// (it waits unless `VICTORY_PIPELINE_COMPUTE_WAIT=0`, and not by this rule +/// even then). docs/KEMERD-AUDIT.md. +fn backlog() -> Option { + static MOST: OnceLock> = OnceLock::new(); + *MOST.get_or_init(|| { + let most = std::env::var("VICTORY_PIPELINE_WAIT_BACKLOG").ok().and_then(|v| v.trim().parse::().ok()); + if let Some(most) = most { + tracing::info!(most, "host pipelines are not waited for while more than this many are queued"); + } + most + }) +} + +/// Whether a draw's wait is left out for the backlog ([`backlog`]): more +/// than `most` queued. +fn over_backlog(most: Option, queued: u64) -> bool { + most.is_some_and(|most| queued > most) +} + /// Waits for `p` while frame `frame` has budget left. fn wait(p: &Pending, frame: u64) { let screen = p.screen && screens_first(); @@ -525,6 +555,9 @@ fn wait(p: &Pending, frame: u64) { if budget.is_zero() { return; } + if !screen && p.graphics.is_some() && over_backlog(backlog(), WAITING.load(Ordering::Relaxed)) { + return; + } // The frame the budget belongs to, and what was waited of it (or is // taken by a thread waiting now); of the passes over the screen too. static SPENT: [Mutex<(u64, Duration)>; 2] = [const { Mutex::new((u64::MAX, Duration::ZERO)) }; 2]; @@ -829,6 +862,18 @@ fn drained() { #[cfg(test)] mod tests { + /// [`super::over_backlog`]: unset never skips; set, only more queued than + /// asked skips. + #[test] + fn a_wait_is_left_out_only_past_the_backlog() { + use super::over_backlog; + assert!(!over_backlog(None, u64::MAX)); + assert!(!over_backlog(Some(64), 0)); + assert!(!over_backlog(Some(64), 64)); + assert!(over_backlog(Some(64), 65)); + assert!(over_backlog(Some(0), 1)); + } + use super::*; #[test] From fbdb2ae29ae508d3f98f13dcc321c87b17b10867 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:13:54 +0000 Subject: [PATCH 08/19] docs: Kemerd audit, pipeline wait switches Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- docs/KEMERD-AUDIT.md | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/docs/KEMERD-AUDIT.md b/docs/KEMERD-AUDIT.md index d5a09165b6..32d0a81f06 100644 --- a/docs/KEMERD-AUDIT.md +++ b/docs/KEMERD-AUDIT.md @@ -87,13 +87,46 @@ Pomiar: linia co sekundę `texture detiling per frame: on the PC X ms for Y MB` Test jednostkowy: `texture::detile_covers_tests`, `pool::tests::a_texture_gives_its_piece_back_when_it_goes` (sprawdza, że `leave=false` zeruje, a `leave=true` zostawia). -## 3. VICTORY_REFRESH_SET: DISCOVERED (osobny PR) +## 3. VICTORY_PIPELINE_WAIT_BACKLOG: IMPLEMENTED (ten PR) + +Kemerd: `pipeline/make.rs` `backlog()` i warunek na początku `wait()`. +U nas: `crates/victory-gpu/src/pipeline/make.rs` `backlog()`, `over_backlog()`, warunek w +`wait()`. Zależność od RT: brak. + +Co robi: gdy w kolejce czeka więcej niż `n` pipeline'ów, draw nie czeka na swój pipeline, +tylko jest pomijany od razu, tak jak dziś po wyczerpaniu budżetu `VICTORY_PIPELINE_WAIT_MS` +(500 ms na klatkę). Draw wraca w kolejnej klatce. Kemerd podaje runy z 470 i 600 PSO w +kolejce, gdzie każda klatka zużywała cały budżet (do 3 fps). + +Koszt: obiekty pojawiają się o kilka klatek później przy zimnym cache. Dlatego przełącznik +jest domyślnie wyłączony i ma sens tylko na niewygrzanym cache. + +Bezpieczeństwo: tylko grafika (`p.graphics.is_some()`). Dispatche compute nie przechodzą +przez tę regułę, nawet z `VICTORY_PIPELINE_COMPUTE_WAIT=0`. Przejścia po ekranie mają własny +budżet i też są wyłączone. + +Pomiar: linia FPS co sekundę, `dropped N without a host pipeline (M being made)`, oraz +`host pipelines are not waited for while more than this many are queued` na starcie. +Test: `pipeline::make::tests::a_wait_is_left_out_only_past_the_backlog`. + +## 4. VICTORY_PIPELINE_WAIT_ONCE: DISCOVERED + +Pomija czekanie, które nie zdąży w budżecie (`skip_wait`). Wymaga `asked_ms` w `Pending` i +`FRONT_MS` w kolejce. Autor: „Compiled and tested, not yet seen in a run”. Odłożone. + +## 5. VICTORY_PIPELINE_SLOW_WORKERS: DISCOVERED + +Dodatkowe wątki do wolnych pipeline'ów, gdy nic nie jest zamówione. Limit +`procesory - workery - 4`. Dla i5-12600K: 16 - 10 - 4 = 2 wątki. Autor: „not verified in a +run”. Mały zysk, odłożone. + +## 6. VICTORY_REFRESH_SET: DISCOVERED (osobny PR) Kemerd `host/lean.rs`. Jeden `Step::RefreshSet` na listę zamiast około 245 `Step::Refresh`. Dotyka `Memory::bring_up` (`memory.rs`) i wszystkich przejść po krokach submisji. Do osobnego audytu. -## 4. VICTORY_SEND_THREAD: DISCOVERED (osobny PR) +## 7. VICTORY_SEND_THREAD: DISCOVERED (osobny PR) Kemerd `host/send_thread.rs` (320 linii) i 5 miejsc w `host.rs`. Zależności u nas: 1. Działa tylko z `late()` (`host.rs`, `late_stage()`): `VICTORY_LATE_WAIT` 1/2/3 albo relay From 6d39c9438765643b0f2f943c34526da7b28443c4 Mon Sep 17 00:00:00 2001 From: Kemerd <6404720+Kemerd@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:19:22 +0000 Subject: [PATCH 09/19] Files: the title's synchronous read-only opens of its package past the system's cache can read through it (VICTORY_FILES_BUFFERED, 1 or count, off by default) From Kemerd/VIctory-NVIDIA-RT 1053639 (in rt-test-11 0549d44c330bf0a1f808f8b012d8e22168dfad91), GPL-3.0, applied unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- crates/victory-hle/src/modules/files.rs | 162 ++++++++++++++++++++++++ 1 file changed, 162 insertions(+) diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index 9acd261667..8a27f2fa1d 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -258,6 +258,133 @@ fn widen(mode: *const c_char) -> Vec { type Handle = *mut c_void; type File = *mut c_void; +/// What `VICTORY_FILES_BUFFERED` asks of the title's opens. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Buffered { + /// `count`: the opens and the title's reads are counted, nothing else. + Count, + /// `1`: counted, and a synchronous read-only open of an existing file + /// on a virtual drive that bypasses the system's file cache reads + /// through it ([`buffered_flags`]). + Clear, +} + +/// `VICTORY_FILES_BUFFERED` (off by default; `count` or `1`). +/// +/// The title opens some of its package files past the system's file cache +/// (the no-buffering flag) and reads them synchronously, one small read +/// after another: through menu and loading the game's disk did 235-1,474 +/// reads a second of 4-8 KB, one at a time (two runs of 2026-11-26), and a +/// second start ten minutes later put the same reads through the disk +/// again, which a cached handle would have served from memory. With `1` +/// such an open reads through the cache: the title's own reads then go +/// disk, system cache, title buffer, one kernel copy more (at most about +/// 7 MB/s before the world), read by the title's CPU. Nothing is claimed +/// for frame time: in the world the disk did 4-13 reads a second. Nothing +/// is gained on the first read after a restart of the PC; the gain is in +/// later starts while the pages stay in standby. An open that reads +/// overlapped is passed through untouched (and counted): the title's opens +/// were not seen to, and on a cached handle such a read can finish inside +/// the call. The DirectStorage files (`super::dstorage`, flags 0) are +/// opened through [`CreateFileW`] too and are in the count. Compiled only, +/// not run. +/// +/// From Kemerd/VIctory-NVIDIA-RT (1053639, in rt-test-11 0549d44c), +/// GPL-3.0; docs/KEMERD-AUDIT.md. +fn buffered() -> Option { + static MODE: std::sync::OnceLock> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_FILES_BUFFERED").as_deref().map(str::trim) { + Ok("count") => Some(Buffered::Count), + Ok("1") => Some(Buffered::Clear), + _ => None, + }) +} + +const GENERIC_READ: u32 = 0x8000_0000; +const OPEN_EXISTING: u32 = 3; +const FILE_FLAG_NO_BUFFERING: u32 = 0x2000_0000; +const FILE_FLAG_OVERLAPPED: u32 = 0x4000_0000; + +/// The flags an open is made with: `flags` without the no-buffering flag +/// when `clear` and the open is of a path on a virtual drive (`rewritten`), +/// for reading only, of a file that exists, and not overlapped; else +/// `flags` as the title gave them. No other bit changes. +fn buffered_flags(access: u32, disposition: u32, flags: u32, rewritten: bool, clear: bool) -> u32 { + if clear + && rewritten + && access == GENERIC_READ + && disposition == OPEN_EXISTING + && flags & FILE_FLAG_NO_BUFFERING != 0 + && flags & FILE_FLAG_OVERLAPPED == 0 + { + flags & !FILE_FLAG_NO_BUFFERING + } else { + flags + } +} + +/// With [`buffered`]: opens; of them those that asked to bypass the cache, +/// those of these that read overlapped (passed through), and those read +/// through the cache now; the title's `ReadFile` calls, their bytes and +/// their microseconds in the host's call. +static FILES_BUFFERED: [std::sync::atomic::AtomicU64; 7] = [const { std::sync::atomic::AtomicU64::new(0) }; 7]; + +/// The (access, flags, on a virtual drive, cleared) kinds of open seen. +static OPEN_KINDS: Mutex>> = Mutex::new(None); + +/// The flags to open with, the open counted ([`buffered`]): a line the +/// first time each kind of open is seen (no path in it). +fn open_flags(access: u32, disposition: u32, flags: u32, rewritten: bool) -> u32 { + use std::sync::atomic::Ordering::Relaxed; + let Some(mode) = buffered() else { + return flags; + }; + let out = buffered_flags(access, disposition, flags, rewritten, mode == Buffered::Clear); + let cleared = out != flags; + let n = FILES_BUFFERED[0].fetch_add(1, Relaxed) + 1; + if flags & FILE_FLAG_NO_BUFFERING != 0 { + FILES_BUFFERED[1].fetch_add(1, Relaxed); + if flags & FILE_FLAG_OVERLAPPED != 0 { + FILES_BUFFERED[2].fetch_add(1, Relaxed); + } + } + if cleared { + FILES_BUFFERED[3].fetch_add(1, Relaxed); + } + let new = OPEN_KINDS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert_with(Default::default) + .insert((access, flags, rewritten, cleared)); + if new { + tracing::info!( + access = format_args!("{access:#x}"), + flags = format_args!("{flags:#x}"), + on_a_virtual_drive = rewritten, + cleared, + "files: a kind of open not seen before (VICTORY_FILES_BUFFERED)" + ); + } + if n.is_power_of_two() { + files_line(); + } + out +} + +/// The totals of [`FILES_BUFFERED`], at powers of two of the opens and of +/// the reads. +fn files_line() { + use std::sync::atomic::Ordering::Relaxed; + let [opens, bypass, overlapped, cleared, reads, bytes, micros] = [0, 1, 2, 3, 4, 5, 6].map(|i| FILES_BUFFERED[i].load(Relaxed)); + tracing::info!( + "files since the start (VICTORY_FILES_BUFFERED): {opens} opens, {bypass} of them past the system's file cache \ + ({overlapped} of these overlapped, passed through), {cleared} read through the cache now; the title's ReadFile: \ + {reads} calls, {} MB, {:.1} ms in the host's call", + bytes >> 20, + micros as f64 / 1e3 + ); +} + // kernel32 and its file API sets. pub extern "system" fn CreateFileW( @@ -270,6 +397,7 @@ pub extern "system" fn CreateFileW( template: Handle, ) -> Handle { let p = wide(path); + let flags = open_flags(access, disposition, flags, p.1.is_some()); host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( p.ptr(), access, @@ -292,6 +420,7 @@ pub extern "system" fn CreateFileA( ) -> Handle { match narrow(path) { Some(p) => { + let flags = open_flags(access, disposition, flags, true); host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( p.as_ptr(), access, @@ -303,6 +432,8 @@ pub extern "system" fn CreateFileA( ) } None => { + // (Counted only: not on a virtual drive.) + let flags = open_flags(access, disposition, flags, false); host!("kernel32.dll", "CreateFileA": extern "system" fn(*const c_char, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( path, access, @@ -536,12 +667,27 @@ pub extern "system" fn ReadFile( overlapped: *mut c_void, ) -> i32 { let writing = victory_gpu::kernel_writing(buffer as usize, len as usize); + // (Timed only with `VICTORY_FILES_BUFFERED`.) + let started = buffered().map(|_| std::time::Instant::now()); let done = host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)( file, buffer, len, read, overlapped, ); // The call's error is the title's to ask for. // SAFETY: plain calls. let error = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + if let Some(started) = started { + use std::sync::atomic::Ordering::Relaxed; + let micros = started.elapsed().as_micros() as u64; + // SAFETY: the title's count, written by the host's call when it + // succeeded (null tolerated). + let got = if done != 0 && !read.is_null() { u64::from(unsafe { read.read_unaligned() }) } else { 0 }; + let n = FILES_BUFFERED[4].fetch_add(1, Relaxed) + 1; + FILES_BUFFERED[5].fetch_add(got, Relaxed); + FILES_BUFFERED[6].fetch_add(micros, Relaxed); + if n >= 1024 && n.is_power_of_two() { + files_line(); + } + } // shortcut: a read that goes on after the call (overlapped) is written // into pages the kernel has locked by now: it lands all the same, but a // refresh that guards its blocks before it does will not see it. @@ -772,6 +918,22 @@ mod tests { s.encode_utf16().chain([0]).collect() } + /// Only a synchronous read-only open of an existing file on a virtual + /// drive loses the no-buffering flag, and only that bit; counting alone + /// changes nothing. + #[test] + fn only_a_plain_read_of_the_package_reads_through_the_cache() { + let past = FILE_FLAG_NO_BUFFERING | 0x80; + assert_eq!(buffered_flags(GENERIC_READ, OPEN_EXISTING, past, true, true), 0x80); + assert_eq!(buffered_flags(GENERIC_READ, OPEN_EXISTING, past, true, false), past); + assert_eq!(buffered_flags(GENERIC_READ, OPEN_EXISTING, past, false, true), past); + assert_eq!(buffered_flags(GENERIC_READ | 0x4000_0000, OPEN_EXISTING, past, true, true), past); + assert_eq!(buffered_flags(GENERIC_READ, 4, past, true, true), past); + let overlapped = past | FILE_FLAG_OVERLAPPED; + assert_eq!(buffered_flags(GENERIC_READ, OPEN_EXISTING, overlapped, true, true), overlapped); + assert_eq!(buffered_flags(GENERIC_READ, OPEN_EXISTING, 0x80, true, true), 0x80); + } + #[test] fn kernel_reads_reach_the_buffer() { use std::os::windows::io::AsRawHandle; From 22ccd833cb3c1fab34d8b96d1237b425ee87bdf1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:19:22 +0000 Subject: [PATCH 10/19] docs: Kemerd audit, files read through the system cache Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- docs/KEMERD-AUDIT.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/KEMERD-AUDIT.md b/docs/KEMERD-AUDIT.md index 32d0a81f06..916ed1a928 100644 --- a/docs/KEMERD-AUDIT.md +++ b/docs/KEMERD-AUDIT.md @@ -109,6 +109,26 @@ Pomiar: linia FPS co sekundę, `dropped N without a host pipeline (M being made) `host pipelines are not waited for while more than this many are queued` na starcie. Test: `pipeline::make::tests::a_wait_is_left_out_only_past_the_backlog`. +## 3a. VICTORY_FILES_BUFFERED: IMPLEMENTED (ten PR) + +Kemerd: commit `1053639`, `crates/victory-hle/src/modules/files.rs` (`buffered()`, +`buffered_flags()`, `open_flags()`, `files_line()`, liczniki w `ReadFile`). Nasz plik był +identyczny z rodzicem tego commita, więc patch nałożony bez zmian, autorstwo Kemerd. +Późniejszych poprawek w `rt-test-11` nie ma. Zależność od RT: brak. + +Co robi: `1` zdejmuje `FILE_FLAG_NO_BUFFERING` tylko z otwarć pliku z wirtualnego dysku gry, +które są: tylko do odczytu (`GENERIC_READ`), `OPEN_EXISTING` i nie `OVERLAPPED`. Żaden inny bit +się nie zmienia. Odczyt idzie wtedy przez cache Windows i kolejny start gry czyta te same +dane z RAM, a nie z dysku. Przy 64 GB RAM cache ma dużo miejsca. `count` tylko liczy. + +Bezpieczeństwo: odczyt przez cache zwraca te same bajty. Wyrównane odczyty, których wymaga +`NO_BUFFERING`, działają też na zwykłym uchwycie. Zapis i odczyt asynchroniczny (overlapped) nie +są ruszane. Autor: „Compiled only, not run”, czyli trzeba to sprawdzić w grze. + +Pomiar: `files since the start (VICTORY_FILES_BUFFERED): ...` (otwarcia, ile przez cache, +`ReadFile`: wywołania, MB, ms) oraz czas od startu do menu i do świata. Zysk dopiero na drugim +starcie po restarcie PC. Test: `files::tests::only_a_plain_read_of_the_package_reads_through_the_cache`. + ## 4. VICTORY_PIPELINE_WAIT_ONCE: DISCOVERED Pomija czekanie, które nie zdąży w budżecie (`skip_wait`). Wymaga `asked_ms` w `Pending` i From 595b8cc2c40feb3efe0c7ed74202d4cc7c526bae Mon Sep 17 00:00:00 2001 From: D Everett Hinton Date: Thu, 26 Nov 2026 23:44:12 -0800 Subject: [PATCH 11/19] Card copies: a title buffer copy finds the copies it touches by where they start (VICTORY_SEND_COPIED_FIND, off by default), and the card copies line says what the look costs From Kemerd/VIctory-NVIDIA-RT 84d94c5 (in rt-test-11 0549d44c330bf0a1f808f8b012d8e22168dfad91), GPL-3.0, applied unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- crates/victory-gpu/src/host.rs | 8 +- crates/victory-gpu/src/shadow.rs | 159 ++++++++++++++++++++++++++++--- 2 files changed, 153 insertions(+), 14 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b5fdf85404..970683c4d2 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -10645,7 +10645,8 @@ impl Meter { tracing::info!( "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \ {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \ - ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)", + ({:.1} MB) with {:.1} more waits for the card ({:.1} ms); title buffer copies done on the CPU \ + looked for among them {:.1} times ({:.2} ms), {:.1} copies found (VICTORY_SEND_COPIED_FIND)", card[7], card[8] >> 20, card[9] >> 20, @@ -10655,7 +10656,10 @@ impl Meter { per_frame(3), per_frame(4) / 1e6, per_frame(5), - per_frame(6) / 1e3 + per_frame(6) / 1e3, + per_frame(10), + per_frame(11) / 1e6, + per_frame(12) ); } let [raw_srv, raw_uav] = crate::descriptor::host::raw_view_counts(); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 215be62bf4..5a728bccb7 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -325,8 +325,60 @@ pub(crate) fn card_room_kept() -> u64 { card_limits().1.min(SEEN).saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed)) } -/// The copies in the card's memory. -static CARDED: Mutex>> = Mutex::new(Vec::new()); +/// The copies in the card's memory, and with [`find_copied`] the same +/// copies by where they start, behind the one lock. +static CARDED: Mutex = Mutex::new(Carded { list: Vec::new(), by_start: BTreeMap::new(), longest: 0 }); + +/// What [`CARDED`] holds. +struct Carded { + list: Vec>, + /// With [`find_copied`]: every copy of `list` by (start, [`Shadow::id`]) + /// (two live copies can start at one address: a tail and a window of + /// the loose copies, a window around a small buffer beside the buffer's + /// own copy, a buffer made again while lists hold the old copy), with + /// where it ends. Empty without the switch. + by_start: BTreeMap<(usize, u64), (usize, std::sync::Weak)>, + /// The longest copy `by_start` ever held: a copy that reaches into an + /// address starts at most so far below it. Never shrinks. + longest: usize, +} + +/// Whether [`send_copied`] finds the copies a title buffer copy touches by +/// where they start (`VICTORY_SEND_COPIED_FIND=1`, off by default), not by +/// upgrading every copy in the card's memory and testing its span: 4,029 +/// copies in the frame of the complaint, of which one or two hold a given +/// destination, and most such copies go to memory no copy holds. +/// +/// It is thread time of the submitting thread, which does every title +/// buffer copy recorded on the CPU: about 0.5 ms a frame at 15 copies and +/// 3 ms at 100, by a bench of the same loop outside the tree (34 us a call +/// over 4,029 copies, warm). No measurable change of a streaming frame is +/// to be expected while that thread stands waiting for translation. The +/// line of the card's copies says what the look costs, in both states. +fn find_copied() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SEND_COPIED_FIND").is_some_and(|v| v == "1")) +} + +/// Of `by_start` (copies by (start, id), each with its end), those that hold +/// some of `[dst, dst + len)`: a copy that does starts below `dst + len` +/// and, being at most `longest` long, at or above `dst - longest`. +fn overlapping( + by_start: &BTreeMap<(usize, u64), (usize, V)>, + longest: usize, + dst: usize, + len: usize, +) -> impl Iterator { + let end = dst.saturating_add(len); + by_start + .range((dst.saturating_sub(longest), 0)..(end, 0)) + .filter(move |&(&(start, _), &(stop, _))| start < end && stop > dst) + .map(|(&(_, id), (_, v))| (id, v)) +} + +/// Since the last frame line, [`send_copied`]'s calls, its nanoseconds and +/// the copies it found holding the destination. +pub(crate) static SEND_COPIED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; /// The copies in the card's memory whose `touched` was set since /// [`card_dirty`] last took them (a copy may be on it twice). Before, each @@ -344,10 +396,18 @@ fn carded(shadow: &Arc) { }; let _ = card.me.set(Arc::downgrade(shadow)); let mut carded = CARDED.lock().unwrap_or_else(|e| e.into_inner()); - carded.push(Arc::downgrade(shadow)); - if carded.len() >= 2 * KEPT.load(Ordering::Relaxed).max(1024) { - carded.retain(|weak| weak.strong_count() > 0); - KEPT.store(carded.len(), Ordering::Relaxed); + let carded = &mut *carded; + carded.list.push(Arc::downgrade(shadow)); + if find_copied() { + // (Start and length are set once, when the copy is made.) + let (start, len) = (shadow.start as usize, shadow.len as usize); + carded.by_start.insert((start, shadow.id), (start + len, Arc::downgrade(shadow))); + carded.longest = carded.longest.max(len); + } + if carded.list.len() >= 2 * KEPT.load(Ordering::Relaxed).max(1024) { + carded.list.retain(|weak| weak.strong_count() > 0); + carded.by_start.retain(|_, (_, weak)| weak.strong_count() > 0); + KEPT.store(carded.list.len(), Ordering::Relaxed); } } @@ -363,13 +423,16 @@ pub(crate) fn live_span_bytes() -> u64 { } /// [`CARD_STATS`], taken; then the copies in the card's memory, their -/// bytes and their "before" twins' bytes. -pub(crate) fn card_stats() -> [u64; 10] { - let mut out = [0u64; 10]; +/// bytes and their "before" twins' bytes; then [`SEND_COPIED`], taken. +pub(crate) fn card_stats() -> [u64; 13] { + let mut out = [0u64; 13]; for (i, stat) in CARD_STATS.iter().enumerate() { out[i] = stat.swap(0, Ordering::Relaxed); } - out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64; + for (i, stat) in SEND_COPIED.iter().enumerate() { + out[10 + i] = stat.swap(0, Ordering::Relaxed); + } + out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).list.iter().filter(|w| w.strong_count() > 0).count() as u64; out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed) + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed); @@ -790,23 +853,95 @@ pub(crate) fn copy_all(copies: Vec<(usize, usize, usize)>) { /// CPU side held the same before or not. Left out is what shaders in the air /// may be writing (such a copy waits for them, or is done on the card). pub(crate) fn send_copied(dst: usize, len: usize) { - for shadow in carded_copies() { + let started = std::time::Instant::now(); + // With the switch the copies are taken under the lock and dealt with + // after it: `carded` is called under the loose copies' and the buffers' + // locks, and the copies may be let go here. + let found = if find_copied() { + let carded = CARDED.lock().unwrap_or_else(|e| e.into_inner()); + let found: Vec> = + overlapping(&carded.by_start, carded.longest, dst, len).filter_map(|(_, weak)| weak.upgrade()).collect(); + // Both ways under one holding of the lock: a copy made between two + // looks would be a false alarm. + #[cfg(feature = "diagnostics")] + { + let fast: std::collections::BTreeSet = found.iter().map(|s| s.id).collect(); + let end = dst.saturating_add(len); + let slow: std::collections::BTreeSet = carded + .list + .iter() + .filter_map(std::sync::Weak::upgrade) + .filter(|s| (s.start as usize) < end && ((s.start + s.len) as usize) > dst) + .map(|s| s.id) + .collect(); + static SAID: [std::sync::Once; 2] = [const { std::sync::Once::new() }; 2]; + if slow.difference(&fast).next().is_some() { + SAID[0].call_once(|| tracing::warn!(dst, len, "send_copied: the copies by start missed one the list holds")); + } + if fast.difference(&slow).next().is_some() { + SAID[1].call_once(|| tracing::warn!(dst, len, "send_copied: the copies by start found one the list does not hold")); + } + } + found + } else { + carded_copies() + }; + let mut hits = 0; + for shadow in found { let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize); let (from, to) = (dst.max(start), (dst + len).min(end)); if from >= to { continue; } + hits += 1; let busy: Vec<(usize, usize)> = shadow.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().copied().filter(|&(a, b)| a < to && b > from).collect(); for (a, b) in outside(from, to, busy) { shadow.copy(a, b); } } + SEND_COPIED[0].fetch_add(1, Ordering::Relaxed); + SEND_COPIED[1].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + SEND_COPIED[2].fetch_add(hits, Ordering::Relaxed); } /// The copies in the card's memory (diagnostics: `crate::host::upcheck`). pub(crate) fn carded_copies() -> Vec> { - CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter_map(std::sync::Weak::upgrade).collect() + CARDED.lock().unwrap_or_else(|e| e.into_inner()).list.iter().filter_map(std::sync::Weak::upgrade).collect() +} + +/// [`overlapping`]: the copies a title buffer copy touches, by their start. +#[cfg(test)] +mod overlapping_tests { + use super::overlapping; + use std::collections::BTreeMap; + + /// A copy that starts below and reaches in is found, one that ends at + /// the destination or starts at its end is not, two that start at one + /// address are both found, and a destination below the longest copy + /// does not wrap. + #[test] + fn finds_every_copy_that_holds_a_byte() { + let mut tree = BTreeMap::new(); + let mut add = |start: usize, len: usize, id: u64| { + tree.insert((start, id), (start + len, id)); + }; + add(0x1000, 0x800, 1); // ends exactly at 0x1800 + add(0x1400, 0x1000, 2); // starts below, reaches in + add(0x1800, 0x100, 3); // the same start as 4 + add(0x1800, 0x10, 4); + add(0x1900, 0x100, 5); // starts at the end + add(0x10, 0x20, 6); // far below + let longest = 0x1000; + let mut found: Vec = overlapping(&tree, longest, 0x1800, 0x100).map(|(id, _)| id).collect(); + found.sort_unstable(); + assert_eq!(found, [2, 3, 4]); + // Below the longest copy: the walk starts at 0. + let low: Vec = overlapping(&tree, longest, 0x20, 4).map(|(id, _)| id).collect(); + assert_eq!(low, [6]); + assert_eq!(overlapping(&tree, longest, 0x3000, 0x100).count(), 0); + assert_eq!(overlapping(&tree, longest, usize::MAX - 8, 0x100).count(), 0); + } } /// Ranges in order, those that overlap or touch as one. From 8fff3e8a62030c662beb530fc57aaeba2fb23fc5 Mon Sep 17 00:00:00 2001 From: D Everett Hinton Date: Thu, 26 Nov 2026 23:38:33 -0800 Subject: [PATCH 12/19] Textures: a guarded texture nothing wrote is read whole at most once a frame (VICTORY_TEXTURE_LOOK_ONCE, off by default), and a line counts the second looks either way From Kemerd/VIctory-NVIDIA-RT 35cafeb (in rt-test-11 0549d44c330bf0a1f808f8b012d8e22168dfad91), GPL-3.0; only the frame-line call in host.rs placed after this tree's detiling line. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- crates/victory-gpu/src/host.rs | 1 + crates/victory-gpu/src/texture.rs | 120 +++++++++++++++++++++++++++++- 2 files changed, 117 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 970683c4d2..dc07f7a0c6 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -10357,6 +10357,7 @@ impl Meter { modes.join(", ") ); } + crate::texture::look_once_line(frames); let [through, left, filled, short] = [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); if through + left + filled > 0.0 { diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 186b91ac4f..818478f562 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -213,6 +213,11 @@ struct Last { /// first checks, and after the hash found a change the guard had not /// seen ([`hot_textures`]). 0: not checked under the guard yet. hot_until: u64, + /// The frame a guarded texture was last read and digested whole in, as + /// the guard's check read it before the read ([`look_once`]). Noted + /// only where all of it was read: not for a partly mapped texture, a + /// first filling from the pages there, or a kernel read that failed. + looked: Option, } /// Frames a guarded texture is hashed at every check from its first check, @@ -510,6 +515,70 @@ pub(crate) static UNLOCKED: [std::sync::atomic::AtomicU64; 4] = [const { std::sy /// was not there). pub(crate) static EXACT_UNLOCKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// Whether a guarded texture the guard saw no write to is read and +/// digested at most once a frame (`VICTORY_TEXTURE_LOOK_ONCE=1`, off by +/// default). Without it such a texture, while it is hot or on its turn, is +/// read whole at every check: once per submission whose lists sample it, +/// and again after every step of that submission that writes title memory +/// (17-30 submissions a frame). With it, a check in the frame the texture +/// was last read whole in finds nothing to do. A write the guard saw is +/// read as before; exact refreshes (bakes) are never passed over. +/// +/// What it saves is time of the threads that refresh, not frame time: the +/// frame line's "textures" (the submitting thread's wall time) was 0.9 ms +/// of 24 in ordinary frames and 9.75 of 390 while the world streamed in +/// with ray tracing (logs of 2026-11-26), and in streaming the submitting +/// thread stands about 178 ms a frame waiting for translation. How much +/// the hashing of second looks is shows in [`look_once_line`] with the +/// switch off; if it is small the switch has nothing to give. +/// +/// The risk, said plainly: a texture written by a way the guard cannot see +/// (another view of its pages) between two samplings in one frame shows +/// the older bytes to the later one; written so every frame, it stays one +/// write behind for the later sampling as long as that goes on. A texture +/// that is not hot is still found within eight frames, as now. It relies +/// on the frame counter advancing, as the turns of [`Staging::refresh`] +/// already do. +fn look_once() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_LOOK_ONCE").is_some_and(|v| v == "1")) +} + +/// Since the last frame-rate line, guarded textures the guard saw no write +/// to that went to a read anyway (hot or on their turn) and their bytes; +/// of them, those that had been read whole in the same frame already and +/// their bytes; and with [`look_once`], those passed over for that and +/// their bytes. Kept whether the switch is on or not. +pub(crate) static LOOK_ONCE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + +/// Whether a texture last read whole in frame `looked` (`None`: not since +/// it was made or forgotten) was read whole in `frame` already. A frame +/// counter that moved on during the read makes the next look a first one. +fn looked_already(looked: Option, frame: u64) -> bool { + looked == Some(frame) +} + +/// The periodic line of [`LOOK_ONCE`], per frame (`frames` since the last). +pub(crate) fn look_once_line(frames: f64) { + use std::sync::atomic::Ordering::Relaxed; + if frames <= 0.0 { + return; + } + let [looks, bytes, again, again_bytes, skipped, skipped_bytes] = + [0, 1, 2, 3, 4, 5].map(|i| LOOK_ONCE[i].swap(0, Relaxed) as f64 / frames); + if looks + skipped > 0.0 { + tracing::info!( + "guarded textures read with no write told, per frame: {looks:.1} ({:.1} MB), of them {again:.1} ({:.1} MB) \ + read whole in the same frame already; {skipped:.1} ({:.1} MB) passed over for that \ + (VICTORY_TEXTURE_LOOK_ONCE=1: now {})", + bytes / 1e6, + again_bytes / 1e6, + skipped_bytes / 1e6, + if look_once() { "on" } else { "off" } + ); + } +} + /// Whether an exact refresh (the uploads before a bake, `BAKING`) that /// finds the runtime remapping title memory first reads the texture whole /// through the kernel, and waits for the remapping to end only if a page of @@ -1700,6 +1769,9 @@ impl Staging { static GUARD: std::sync::OnceLock = std::sync::OnceLock::new(); // The guard saw no write: a change the hash finds came another way. let mut blind = false; + // The frame the guard's check below read, noted in `last.looked` + // where the texture is then read whole ([`look_once`]). + let mut looked = None; if !alone && *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) @@ -1720,6 +1792,24 @@ impl Staging { if !exact && unwritten && !turn && !hot { return 0; } + looked = Some(frame); + // Hot or on its turn with no write told: read whole at every + // such check today, possibly several times in one frame. + if !exact && unwritten { + use std::sync::atomic::Ordering::Relaxed; + let again = looked_already(last.looked, frame); + if again && look_once() { + LOOK_ONCE[4].fetch_add(1, Relaxed); + LOOK_ONCE[5].fetch_add(size as u64, Relaxed); + return 0; + } + LOOK_ONCE[0].fetch_add(1, Relaxed); + LOOK_ONCE[1].fetch_add(size as u64, Relaxed); + if again { + LOOK_ONCE[2].fetch_add(1, Relaxed); + LOOK_ONCE[3].fetch_add(size as u64, Relaxed); + } + } blind = unwritten; } // A change the guard did not see: hashed at every check for a while. @@ -1765,13 +1855,13 @@ impl Staging { // texture is read through the kernel instead, whole or not at // all (`no_wait`). let Some(mapped) = crate::watch::title_memory_reading_now() else { - return self.refresh_unlocked(last, size); + return self.refresh_unlocked(last, size, looked); }; mapped } else if exact && exact_unlocked() { match crate::watch::title_memory_reading_now() { Some(mapped) => mapped, - None => match self.refresh_exact_unlocked(last, size) { + None => match self.refresh_exact_unlocked(last, size, looked) { Some(read) => { if read { found_blind(last); @@ -1828,6 +1918,7 @@ impl Staging { if through_copy() || !crate::watch::soft_runs(start, size).is_empty() { return with_title(self.memory, size, |tiled| { let hash = digest(tiled); + last.looked = looked; #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); if last.hash == Some(hash) { @@ -1845,6 +1936,7 @@ impl Staging { // stays committed while `_mapped` is held. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; let hash = digest(tiled); + last.looked = looked; #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); if last.hash == Some(hash) { @@ -1865,12 +1957,13 @@ impl Staging { /// next refresh (what was learnt about writes to it is forgotten, so /// that it is not passed over as unwritten); one never filled takes the /// pages that are there ([`Staging::fill`]). Returns the bytes read. - fn refresh_unlocked(&self, last: &mut Last, size: usize) -> usize { + fn refresh_unlocked(&self, last: &mut Last, size: usize, looked: Option) -> usize { use std::sync::atomic::Ordering::Relaxed; let read = with_read(size, |read| { if !crate::host::read_into(self.memory, read) { return false; } + last.looked = looked; let hash = digest(read); if last.hash != Some(hash) { last.hash = Some(hash); @@ -1897,13 +1990,14 @@ impl Staging { /// lock would be. `Some(changed)` if read (and detiled if it changed), /// `None` if a page was missing: then the refresh waits for the lock /// as before. - fn refresh_exact_unlocked(&self, last: &mut Last, size: usize) -> Option { + fn refresh_exact_unlocked(&self, last: &mut Last, size: usize, looked: Option) -> Option { use std::sync::atomic::Ordering::Relaxed; let mut changed = false; let read = with_read(size, |read| { if !crate::host::read_into(self.memory, read) { return false; } + last.looked = looked; let hash = digest(read); if last.hash != Some(hash) { last.hash = Some(hash); @@ -2768,6 +2862,24 @@ mod title_memory_tests { } } +/// [`looked_already`]: what `VICTORY_TEXTURE_LOOK_ONCE` passes over. +#[cfg(test)] +mod look_once_tests { + use super::{Last, looked_already}; + + /// A texture never read whole, or forgotten, is read at its first look + /// of a frame; one read whole in this frame is passed over; one read in + /// the frame before, or read while the counter moved on, is read again. + #[test] + fn only_a_second_look_in_the_same_frame_is_passed_over() { + assert!(!looked_already(Last::default().looked, 0)); + assert!(!looked_already(None, 7)); + assert!(looked_already(Some(7), 7)); + assert!(!looked_already(Some(6), 7)); + assert!(!looked_already(Some(7), 8)); + } +} + /// [`claim_upload`] (ported from Belobug/VIctory-Belobug-AMD 5d6bd84). #[cfg(test)] mod prelude_upload_tests { From a5f964ab09e1643b54478b4a6fdb877b2b48c88c Mon Sep 17 00:00:00 2001 From: Kemerd <6404720+Kemerd@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:43:42 +0000 Subject: [PATCH 13/19] Streaming: the reviewers' findings (the parts for the switches ported here) From Kemerd/VIctory-NVIDIA-RT ef8f00c (in rt-test-11 0549d44c330bf0a1f808f8b012d8e22168dfad91), GPL-3.0. Taken: a staging piece is zero-filled in PreludeUpload::finish_refresh, before the prelude is recorded under the list's states lock (VICTORY_STAGING_NO_ZERO); look-once counters count only whole reads (note_looked); the copy finder's list copies are let go after the CARDED lock and its timing covers the look alone. Left out: read-ahead, arenas and slow workers, which are not in this tree. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- crates/victory-gpu/src/shadow.rs | 28 +++++++++------ crates/victory-gpu/src/texture.rs | 59 +++++++++++++++++++++++-------- 2 files changed, 63 insertions(+), 24 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 5a728bccb7..bbe84219d5 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -862,18 +862,23 @@ pub(crate) fn send_copied(dst: usize, len: usize) { let found: Vec> = overlapping(&carded.by_start, carded.longest, dst, len).filter_map(|(_, weak)| weak.upgrade()).collect(); // Both ways under one holding of the lock: a copy made between two - // looks would be a false alarm. + // looks would be a false alarm. The list's copies are upgraded here + // and compared after the lock is let go, so one whose last owner went + // meanwhile is not destroyed under it. + #[cfg(feature = "diagnostics")] + let end = dst.saturating_add(len); + #[cfg(feature = "diagnostics")] + let listed: Vec> = carded + .list + .iter() + .filter_map(std::sync::Weak::upgrade) + .filter(|s| (s.start as usize) < end && ((s.start + s.len) as usize) > dst) + .collect(); + drop(carded); #[cfg(feature = "diagnostics")] { let fast: std::collections::BTreeSet = found.iter().map(|s| s.id).collect(); - let end = dst.saturating_add(len); - let slow: std::collections::BTreeSet = carded - .list - .iter() - .filter_map(std::sync::Weak::upgrade) - .filter(|s| (s.start as usize) < end && ((s.start + s.len) as usize) > dst) - .map(|s| s.id) - .collect(); + let slow: std::collections::BTreeSet = listed.iter().map(|s| s.id).collect(); static SAID: [std::sync::Once; 2] = [const { std::sync::Once::new() }; 2]; if slow.difference(&fast).next().is_some() { SAID[0].call_once(|| tracing::warn!(dst, len, "send_copied: the copies by start missed one the list holds")); @@ -881,11 +886,14 @@ pub(crate) fn send_copied(dst: usize, len: usize) { if fast.difference(&slow).next().is_some() { SAID[1].call_once(|| tracing::warn!(dst, len, "send_copied: the copies by start found one the list does not hold")); } + drop(listed); } found } else { carded_copies() }; + // the look alone: the bytes of the copies found below are not its cost. + let looked = started.elapsed(); let mut hits = 0; for shadow in found { let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize); @@ -901,7 +909,7 @@ pub(crate) fn send_copied(dst: usize, len: usize) { } } SEND_COPIED[0].fetch_add(1, Ordering::Relaxed); - SEND_COPIED[1].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + SEND_COPIED[1].fetch_add(looked.as_nanos() as u64, Ordering::Relaxed); SEND_COPIED[2].fetch_add(hits, Ordering::Relaxed); } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 818478f562..3b72398473 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -1158,6 +1158,25 @@ fn claim_upload(uploaded: &std::sync::atomic::AtomicBool, dirty: &std::sync::ato (!was_uploaded || was_dirty).then_some(!was_uploaded) } +/// Notes a whole read of a guarded texture: the frame it was read in +/// ([`look_once`]) and, for a look the guard told no write of (`blind`: +/// whether it was a second look in its frame), the counts of [`LOOK_ONCE`]. +/// Called only where all of the texture was read, so the line counts reads +/// and not looks that went on to a throttle or a failed read. (Kemerd +/// ef8f00c, GPL-3.0.) +fn note_looked(last: &mut Last, looked: Option, blind: Option, size: usize) { + use std::sync::atomic::Ordering::Relaxed; + last.looked = looked; + if let Some(again) = blind { + LOOK_ONCE[0].fetch_add(1, Relaxed); + LOOK_ONCE[1].fetch_add(size as u64, Relaxed); + if again { + LOOK_ONCE[2].fetch_add(1, Relaxed); + LOOK_ONCE[3].fetch_add(size as u64, Relaxed); + } + } +} + /// A title texture a list samples, its upload decided at the list's /// submission ([`prelude_uploads`]): its staging buffer, its host copy (both /// held by the list until it is reset), and its levels on demand. (Ported @@ -1229,6 +1248,12 @@ impl PreludeUpload { }; #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexUploads, 1); + // A piece handed out without its zeros that nothing detiled whole is + // zero-filled here, before the prelude is recorded under the list's + // states lock: `record` would make the submit thread wait for `last` + // there, with that lock held. A load and nothing more once the flag + // is clear. (Kemerd ef8f00c, GPL-3.0.) + self.staging.zero_if_unwritten(); // A host copy that took the place of one with fewer levels: the slots // that show that one are made again once this upload has run. if self.staging.first == self.staging.level0 && self.copy.grown.swap(false, Relaxed) { @@ -1256,6 +1281,7 @@ impl PreludeUpload { /// Records the copy of the staging buffer into the host texture on /// `list` (the prelude), the host texture in the copy destination state. pub(crate) fn record(&self, list: &ID3D12GraphicsCommandList) { + // (Done in `finish_refresh` already; kept for any other caller.) self.staging.zero_if_unwritten(); let texture = &self.copy.texture; // The staging buffer lives as long as `self.staging`, which the @@ -1772,6 +1798,10 @@ impl Staging { // The frame the guard's check below read, noted in `last.looked` // where the texture is then read whole ([`look_once`]). let mut looked = None; + // With no write told: whether this look is a second one in its frame, + // counted on [`LOOK_ONCE`] only where the texture is then read whole + // ([`note_looked`]). + let mut blind_look = None; if !alone && *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) @@ -1803,12 +1833,7 @@ impl Staging { LOOK_ONCE[5].fetch_add(size as u64, Relaxed); return 0; } - LOOK_ONCE[0].fetch_add(1, Relaxed); - LOOK_ONCE[1].fetch_add(size as u64, Relaxed); - if again { - LOOK_ONCE[2].fetch_add(1, Relaxed); - LOOK_ONCE[3].fetch_add(size as u64, Relaxed); - } + blind_look = Some(again); } blind = unwritten; } @@ -1855,13 +1880,13 @@ impl Staging { // texture is read through the kernel instead, whole or not at // all (`no_wait`). let Some(mapped) = crate::watch::title_memory_reading_now() else { - return self.refresh_unlocked(last, size, looked); + return self.refresh_unlocked(last, size, looked, blind_look); }; mapped } else if exact && exact_unlocked() { match crate::watch::title_memory_reading_now() { Some(mapped) => mapped, - None => match self.refresh_exact_unlocked(last, size, looked) { + None => match self.refresh_exact_unlocked(last, size, looked, blind_look) { Some(read) => { if read { found_blind(last); @@ -1918,7 +1943,7 @@ impl Staging { if through_copy() || !crate::watch::soft_runs(start, size).is_empty() { return with_title(self.memory, size, |tiled| { let hash = digest(tiled); - last.looked = looked; + note_looked(last, looked, blind_look, size); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); if last.hash == Some(hash) { @@ -1936,7 +1961,7 @@ impl Staging { // stays committed while `_mapped` is held. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; let hash = digest(tiled); - last.looked = looked; + note_looked(last, looked, blind_look, size); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); if last.hash == Some(hash) { @@ -1957,13 +1982,13 @@ impl Staging { /// next refresh (what was learnt about writes to it is forgotten, so /// that it is not passed over as unwritten); one never filled takes the /// pages that are there ([`Staging::fill`]). Returns the bytes read. - fn refresh_unlocked(&self, last: &mut Last, size: usize, looked: Option) -> usize { + fn refresh_unlocked(&self, last: &mut Last, size: usize, looked: Option, blind_look: Option) -> usize { use std::sync::atomic::Ordering::Relaxed; let read = with_read(size, |read| { if !crate::host::read_into(self.memory, read) { return false; } - last.looked = looked; + note_looked(last, looked, blind_look, size); let hash = digest(read); if last.hash != Some(hash) { last.hash = Some(hash); @@ -1990,14 +2015,20 @@ impl Staging { /// lock would be. `Some(changed)` if read (and detiled if it changed), /// `None` if a page was missing: then the refresh waits for the lock /// as before. - fn refresh_exact_unlocked(&self, last: &mut Last, size: usize, looked: Option) -> Option { + fn refresh_exact_unlocked( + &self, + last: &mut Last, + size: usize, + looked: Option, + blind_look: Option, + ) -> Option { use std::sync::atomic::Ordering::Relaxed; let mut changed = false; let read = with_read(size, |read| { if !crate::host::read_into(self.memory, read) { return false; } - last.looked = looked; + note_looked(last, looked, blind_look, size); let hash = digest(read); if last.hash != Some(hash) { last.hash = Some(hash); From 578e47a8c41ee8e01e74ab9420b5d7fb150f2fe2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:43:42 +0000 Subject: [PATCH 14/19] docs: Kemerd audit, copy finder, look once, review fixes, authorship correction Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- docs/KEMERD-AUDIT.md | 55 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/docs/KEMERD-AUDIT.md b/docs/KEMERD-AUDIT.md index 916ed1a928..8fbe69a888 100644 --- a/docs/KEMERD-AUDIT.md +++ b/docs/KEMERD-AUDIT.md @@ -111,9 +111,11 @@ Test: `pipeline::make::tests::a_wait_is_left_out_only_past_the_backlog`. ## 3a. VICTORY_FILES_BUFFERED: IMPLEMENTED (ten PR) -Kemerd: commit `1053639`, `crates/victory-hle/src/modules/files.rs` (`buffered()`, -`buffered_flags()`, `open_flags()`, `files_line()`, liczniki w `ReadFile`). Nasz plik był -identyczny z rodzicem tego commita, więc patch nałożony bez zmian, autorstwo Kemerd. +Commit `1053639` w repo Kemerd, autor D Everett Hinton, `crates/victory-hle/src/modules/files.rs` +(`buffered()`, `buffered_flags()`, `open_flags()`, `files_line()`, liczniki w `ReadFile`). Nasz +plik był identyczny z rodzicem tego commita, więc patch nałożony bez zmian. +Sprostowanie: nasz commit `6d39c94` ma w metadanych autora Kemerd. Prawdziwy autor to +D Everett Hinton . Historii nie przepisuję, bo commit jest już na GitHubie. Późniejszych poprawek w `rt-test-11` nie ma. Zależność od RT: brak. Co robi: `1` zdejmuje `FILE_FLAG_NO_BUFFERING` tylko z otwarć pliku z wirtualnego dysku gry, @@ -129,6 +131,53 @@ Pomiar: `files since the start (VICTORY_FILES_BUFFERED): ...` (otwarcia, ile prz `ReadFile`: wywołania, MB, ms) oraz czas od startu do menu i do świata. Zysk dopiero na drugim starcie po restarcie PC. Test: `files::tests::only_a_plain_read_of_the_package_reads_through_the_cache`. +## 3b. VICTORY_SEND_COPIED_FIND: IMPLEMENTED (ten PR) + +Commit `84d94c5`, autor D Everett Hinton, plus poprawka Kemerd `ef8f00c` (część `shadow.rs`). +U nas: `crates/victory-gpu/src/shadow.rs` `Carded`, `find_copied()`, `overlapping()`, +`send_copied()`, linia kopii w `host.rs`. Zależność od RT: brak. + +Co robi: kopia bufora tytułu (`send_copied`) zamiast przeglądać wszystkie kopie w pamięci +karty (autor: 4029 w klatce, z czego 1-2 trafiają w cel) szuka ich w `BTreeMap` po adresie +początku, w zakresie `[dst - longest, dst + len)`. Autor podaje 34 us na wywołanie przy pełnym +przeglądzie, czyli około 0,5 ms na klatkę przy 15 kopiach i 3 ms przy 100. Tyle czasu +wątku submitującego. + +Poprawność: `start` i `len` kopii to zwykłe pola `u64` ustawiane raz przy tworzeniu +(`Shadow`, za `Arc`). `longest` nigdy nie maleje, więc dolna granica wyszukiwania jest +bezpieczna. Sprzątanie `by_start` idzie razem z `list`. Build diagnostyczny porównuje +każde wyszukiwanie z pełnym przeglądem i ostrzega przy różnicy. Poprawka `ef8f00c` zwalnia +kopie dopiero po puszczeniu blokady `CARDED` i mierzy tylko samo wyszukiwanie. + +Pomiar: linia kopii karty w logu (`SEND_COPIED`: wywołania, ns, trafienia). +Test: `shadow::overlapping_tests::finds_every_copy_that_holds_a_byte`. + +## 3c. VICTORY_TEXTURE_LOOK_ONCE: IMPLEMENTED (ten PR) + +Commit `35cafeb`, autor D Everett Hinton, plus poprawka Kemerd `ef8f00c` (`note_looked`). +U nas: `crates/victory-gpu/src/texture.rs` `look_once()`, `LOOK_ONCE`, `looked_already()`, +`look_once_line()`, `note_looked()`, `Last::looked`, sprawdzenie w `Staging::refresh`. +Konflikt tylko w `host.rs` (miejsce wywołania linii logu). Zależność od RT: brak. + +Co robi: tekstura pilnowana przez strażnika zapisów, do której nic nie zapisało, jest +czytana i hashowana w całości najwyżej raz na klatkę zamiast przy każdej submisji (17-30 +na klatkę). Zapis widziany przez strażnika i dokładne odświeżenia (bake) idą jak dawniej. + +Ryzyko (opis autora): tekstura zapisana drogą, której strażnik nie widzi, między dwoma +próbkowaniami w jednej klatce pokaże późniejszemu starsze bajty, czyli najwyżej jedną +klatkę opóźnienia. Dlatego przełącznik jest domyślnie wyłączony. + +Pomiar: linia `guarded textures read with no write told, per frame: ...` jest wypisywana +także bez przełącznika i pokazuje, ile drugich odczytów jest do zaoszczędzenia. Jeśli +`again` jest bliskie zera, przełącznik nic nie da. + +## 3d. Poprawka Kemerd ef8f00c dla VICTORY_STAGING_NO_ZERO + +`PreludeUpload::record` działa pod blokadą stanów listy, a `zero_if_unwritten` bierze +blokadę `last`. Kemerd przeniósł zerowanie do `PreludeUpload::finish_refresh`, przed +nagraniem prelude. U nas zrobione tak samo. W `record` zostaje jako zabezpieczenie +(po wyzerowaniu to tylko odczyt flagi). + ## 4. VICTORY_PIPELINE_WAIT_ONCE: DISCOVERED Pomija czekanie, które nie zdąży w budżecie (`skip_wait`). Wymaga `asked_ms` w `Pending` i From 1d0e41817c73edecfcce4c1ec2b5c1708d979cc2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:44:29 +0000 Subject: [PATCH 15/19] docs: Kemerd audit, original commits and their authors Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- docs/KEMERD-AUDIT.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/KEMERD-AUDIT.md b/docs/KEMERD-AUDIT.md index 8fbe69a888..54980eb99d 100644 --- a/docs/KEMERD-AUDIT.md +++ b/docs/KEMERD-AUDIT.md @@ -4,6 +4,14 @@ = `0549d44c330bf0a1f808f8b012d8e22168dfad91`. Licencja: GPL-3.0, ta sama co nasza. Baza porównania: `ampere-sm86-perf-exp1` @ `49f164c66110351f18a22b7f16f694eba605e021`. +Repozytorium Kemerd ma kilku autorów. Oryginalne commity i ich autorzy: +- `VICTORY_STAGING_NO_ZERO`: `7a166c4`, D Everett Hinton. Nasz `970bcbc` to adaptacja. +- `VICTORY_PIPELINE_WAIT_BACKLOG`: `109f2c8`, Kemerd. Nasz `a376dd7` to adaptacja. +- `VICTORY_FILES_BUFFERED`: `1053639`, D Everett Hinton (nasz `6d39c94`, bez zmian). +- `VICTORY_SEND_COPIED_FIND`: `84d94c5`, D Everett Hinton (nasz `595b8cc`, bez zmian). +- `VICTORY_TEXTURE_LOOK_ONCE`: `35cafeb`, D Everett Hinton (nasz `8fff3e8`). +- Poprawki z przeglądu: `ef8f00c`, Kemerd (nasz `a5f964a`, wybrane części). + Każdy przenoszony mechanizm jest za własnym przełącznikiem, domyślnie wyłączony. Rollback: nie ustawiać przełącznika albo cofnąć commit (`git revert`). From b19e19bba317e7fd4f99e39e04c59fdec465ea20 Mon Sep 17 00:00:00 2001 From: D Everett Hinton Date: Fri, 27 Nov 2026 00:04:46 -0800 Subject: [PATCH 16/19] Textures: a buffer staged for one upload of the pass is read by threads of ours once the pass lets go of it (VICTORY_TEXTURE_READ_AHEAD, off by default) From Kemerd/VIctory-NVIDIA-RT 19f0de6 (in rt-test-11 0549d44c330bf0a1f808f8b012d8e22168dfad91), GPL-3.0, applied unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- crates/victory-gpu/src/draw.rs | 15 ++- crates/victory-gpu/src/host.rs | 1 + crates/victory-gpu/src/texture.rs | 28 +++++- crates/victory-gpu/src/texture/ahead.rs | 121 ++++++++++++++++++++++++ 4 files changed, 160 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 09d6d93546..068cb3b8d9 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3995,7 +3995,20 @@ impl State { let memory = if again.is_none() && heap_recheck() { crate::texture::staged_memory(resource) } else { None }; memory.map(|(at, len)| (at, len, crate::texture::fingerprint(at, len))) }); - rest(6, || crate::texture::unstage(resource)); + let staged = rest(6, || crate::texture::unstage(resource)); + // Read by threads of ours from here, after the fingerprint for + // the later look ([`crate::texture::ahead::read_ahead`]): not a + // bake's, not one taken ahead, not one looked at again by + // mapped bytes alone. + if let Some(staging) = staged + && crate::texture::ahead::read_ahead() + && ahead.is_none() + && sync.is_none() + && !baking + && memory.is_some() + { + crate::texture::ahead::read_soon(staging); + } SPENT.fetch_add(bytes, Ordering::Relaxed); since_asked += bytes; if first_upload || (room && since_asked >= 32 << 20) { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index dc07f7a0c6..082745ed44 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -10358,6 +10358,7 @@ impl Meter { ); } crate::texture::look_once_line(frames); + crate::texture::ahead::read_ahead_line(frames); let [through, left, filled, short] = [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); if through + left + filled > 0.0 { diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 3b72398473..95483b108b 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -1695,6 +1695,26 @@ impl Staging { preparing[3].fetch_add(read as u64, Relaxed); } + /// For the read-ahead threads ([`ahead::read_soon`]), on a thread of + /// theirs: the refresh the submission would do, only for a buffer read + /// once (no draw samples it through a table, which would ask the write + /// watch and guard its pages), not marked exact by a bake (that read + /// belongs to the submission) and not uploaded. None: held back by + /// those; Some(false): it was filled already, the submission (or another + /// list's) came first; Some(true): read here. + pub(crate) fn refresh_soon(&self) -> Option { + use std::sync::atomic::Ordering::Relaxed; + if !self.once.load(Relaxed) || self.exact.load(Relaxed) || self.uploaded.load(Relaxed) { + return None; + } + // (A refresh between this look and the next one returns at once.) + if self.last.lock().unwrap_or_else(|e| e.into_inner()).hash.is_some() { + return Some(false); + } + self.refresh(); + Some(true) + } + fn movie_plane(&self) -> bool { use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UNORM; let desc = &self.layout.desc; @@ -2242,11 +2262,11 @@ impl Drop for DetileTimed { /// Lets go of a title texture's staging buffer (lists that recorded an /// upload from it hold it until they have run); the next upload makes one /// anew. -pub(crate) fn unstage(resource: This) { +/// Returns the buffer let go of: no later upload finds it, so its flags +/// change no more but by its own refresh ([`ahead::read_soon`]). +pub(crate) fn unstage(resource: This) -> Option> { let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(map) = map.as_mut() { - map.remove(&(resource as usize)); - } + map.as_mut()?.remove(&(resource as usize)) } /// Where a staged title texture's memory is: address and bytes. diff --git a/crates/victory-gpu/src/texture/ahead.rs b/crates/victory-gpu/src/texture/ahead.rs index 0d741553aa..890f529535 100644 --- a/crates/victory-gpu/src/texture/ahead.rs +++ b/crates/victory-gpu/src/texture/ahead.rs @@ -355,6 +355,117 @@ pub(crate) fn there(resource: This) -> bool { crate::resource::made_copy(resource).is_some_and(|copy| copy.ahead.load(Relaxed) == DONE) } +/// Whether a buffer staged for one upload of the texture pass is read by +/// threads of ours as soon as the pass lets go of it, not at the list's +/// submission (`VICTORY_TEXTURE_READ_AHEAD=1`, off by default; with it unset +/// nothing is queued and every such buffer is read at its submission, on +/// the wide threads, as before). +/// +/// Where the bytes are: title memory -> the staging buffer (an upload +/// heap, detiled) -> the texture on the card. No hop is added or repeated: +/// the read into the staging buffer moves from the submission to here, and +/// the submission's refresh of a filled buffer returns at once. Only for a +/// buffer the pass took a fingerprint of for a later look (a write between +/// this read and the submission shows there), not one of a bake (exact) +/// nor one a table draw keeps watched. The saving is an upper bound of +/// 12-20 ms a frame of the wide threads' time in ray-traced streaming, +/// 1-5 ms without (bakes' uploads not counted), and it is the submit +/// thread's time, while that thread mostly stands waiting for translation: +/// not frame time. On the frame line "textures" rises by what moves here +/// (refreshes in front no longer subtract it); "copies" and the refreshes' +/// flushes fall; "a texture picked by index changed after its upload" and +/// "waiting for a texture another thread is refreshing" must not rise. +pub(crate) fn read_ahead() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_READ_AHEAD").is_some_and(|v| v == "1")) +} + +/// Bytes of staging buffers queued for reading at most: past it a buffer +/// is read at its submission, as before. +const READ_MOST: u64 = 64 << 20; + +/// The buffers to read and their bytes; the two threads wait on it. +static READS: (Mutex<(VecDeque>, u64)>, Condvar) = (Mutex::new((VecDeque::new(), 0)), Condvar::new()); +/// Since the last line: buffers queued, read here, their MB in bytes, filled +/// first by a submission, held back by the guards, turned away full. +static READ_STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + +/// Queues `staging` for a read ahead of its submission ([`read_ahead`]), +/// on the pass's thread; never waits. Not queued when full, or when the +/// threads could not be started. +pub(crate) fn read_soon(staging: Arc) { + static STARTED: OnceLock = OnceLock::new(); + let started = *STARTED.get_or_init(|| { + (0..2).fold(false, |any, n| { + let spawned = std::thread::Builder::new().name(format!("textures read ahead {n}")).spawn(read_worker).is_ok(); + any | spawned + }) + }); + if !started { + return; + } + let bytes = staging.read as u64; + { + let mut reads = READS.0.lock().unwrap_or_else(|e| e.into_inner()); + if !fits(reads.1, bytes) { + READ_STATS[5].fetch_add(1, Relaxed); + return; + } + reads.1 += bytes; + reads.0.push_back(staging); + } + READ_STATS[0].fetch_add(1, Relaxed); + READS.1.notify_one(); +} + +/// Whether `bytes` more fit beside `queued` ([`READ_MOST`]). +fn fits(queued: u64, bytes: u64) -> bool { + queued.saturating_add(bytes) <= READ_MOST +} + +/// A thread of [`read_soon`]'s: reads one buffer at a time, under the +/// buffer's own lock, as the submission would. +fn read_worker() { + loop { + let staging = { + let mut reads = READS.0.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(staging) = reads.0.pop_front() { + reads.1 = reads.1.saturating_sub(staging.read as u64); + break staging; + } + reads = READS.1.wait(reads).unwrap_or_else(|e| e.into_inner()); + } + }; + match staging.refresh_soon() { + Some(true) => { + READ_STATS[1].fetch_add(1, Relaxed); + READ_STATS[2].fetch_add(staging.read as u64, Relaxed); + } + Some(false) => { + READ_STATS[3].fetch_add(1, Relaxed); + } + None => { + READ_STATS[4].fetch_add(1, Relaxed); + } + } + } +} + +/// The read-ahead numbers since the last line, per frame, with the switch. +pub(crate) fn read_ahead_line(frames: f64) { + if !read_ahead() || frames <= 0.0 { + return; + } + let [queued, read, bytes, first, held, full] = [0, 1, 2, 3, 4, 5].map(|i| READ_STATS[i].swap(0, Relaxed) as f64 / frames); + tracing::info!( + "texture uploads of the lists read ahead of their submission (VICTORY_TEXTURE_READ_AHEAD=1), per frame: {queued:.1} queued, \ + {read:.1} read ahead ({:.1} MB), {first:.1} the submission filled first, {held:.1} held back (read once no more, exact \ + or uploaded), {full:.1} left to the submission with the queue full", + bytes / 1e6 + ); +} + /// The state of [`HostTexture::ahead`] of a new host copy. pub(crate) fn fresh() -> AtomicU8 { AtomicU8::new(NONE) @@ -364,6 +475,16 @@ pub(crate) fn fresh() -> AtomicU8 { mod tests { use super::*; + /// The queue for reads ahead holds at most its bytes; a buffer past + /// them is left to its submission. + #[test] + fn reads_ahead_fit_their_bound() { + assert!(fits(0, READ_MOST)); + assert!(fits(READ_MOST - 1, 1)); + assert!(!fits(READ_MOST, 1)); + assert!(!fits(1, u64::MAX)); + } + /// The texels of a placed texture arrive by the copy queue, all levels of /// them, and what waits for them is called then; a second asking finds the /// first on its way, and a later one is the list's. From 4162a3d6e2ac000e868e6dc0773303d102d233ea Mon Sep 17 00:00:00 2001 From: Kemerd <6404720+Kemerd@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:19:48 +0000 Subject: [PATCH 17/19] Streaming: the reviewers' findings for the read-ahead From Kemerd/VIctory-NVIDIA-RT ef8f00c (texture.rs, ahead.rs), GPL-3.0. A read-ahead decides and reads under one hold of the staging's last lock, and leaves a buffer a refresh already tried (its copy may be in flight); the read-ahead line says nothing in quiet frames. Plus a309f8e's quiet check in ahead.rs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- crates/victory-gpu/src/texture.rs | 39 ++++++++++++++++++++----- crates/victory-gpu/src/texture/ahead.rs | 4 +++ 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 95483b108b..41a1f44aab 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -218,6 +218,11 @@ struct Last { /// only where all of it was read: not for a partly mapped texture, a /// first filling from the pages there, or a kernel read that failed. looked: Option, + /// A refresh has run for this buffer, read or not. The read-ahead + /// threads ([`Staging::refresh_soon`]) leave a buffer that was tried: + /// the submission came first, and its copy may be in flight. (Kemerd + /// ef8f00c, GPL-3.0.) + tried: bool, } /// Frames a guarded texture is hashed at every check from its first check, @@ -1700,19 +1705,32 @@ impl Staging { /// once (no draw samples it through a table, which would ask the write /// watch and guard its pages), not marked exact by a bake (that read /// belongs to the submission) and not uploaded. None: held back by - /// those; Some(false): it was filled already, the submission (or another - /// list's) came first; Some(true): read here. + /// those, or by a refresh that was tried and read nothing (a submission's: + /// its copy may be in flight, nothing is written to the buffer after it); + /// Some(false): it was filled already, the submission (or another list's) + /// came first; Some(true): read here. Decided and read under one hold of + /// `last`, so a submission cannot come between the look and the read. pub(crate) fn refresh_soon(&self) -> Option { use std::sync::atomic::Ordering::Relaxed; if !self.once.load(Relaxed) || self.exact.load(Relaxed) || self.uploaded.load(Relaxed) { return None; } - // (A refresh between this look and the next one returns at once.) - if self.last.lock().unwrap_or_else(|e| e.into_inner()).hash.is_some() { + let started = std::time::Instant::now(); + let _texture = crate::timeline::span("a texture's refresh"); + let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); + if last.hash.is_some() { return Some(false); } - self.refresh(); - Some(true) + if last.tried { + return None; + } + let read = self.refresh_locked(&mut last); + let elapsed = started.elapsed().as_micros() as u64; + REFRESH_WAITS[3].fetch_add(elapsed, Relaxed); + let preparing = &crate::host::PREPARING; + preparing[2].fetch_add(elapsed, Relaxed); + preparing[3].fetch_add(read as u64, Relaxed); + Some(read > 0) } fn movie_plane(&self) -> bool { @@ -1778,10 +1796,15 @@ impl Staging { } fn refresh_timed(&self) -> usize { + let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); + self.refresh_locked(&mut last) + } + + /// The refresh, `last` (this buffer's) held by the caller. + fn refresh_locked(&self, last: &mut Last) -> usize { let size = self.read; let start = self.memory as usize; - let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); - let last = &mut *last; + last.tried = true; let exact = self.exact.swap(false, std::sync::atomic::Ordering::Relaxed); let alone = self.once.load(std::sync::atomic::Ordering::Relaxed); if alone && !exact && last.hash.is_some() { diff --git a/crates/victory-gpu/src/texture/ahead.rs b/crates/victory-gpu/src/texture/ahead.rs index 890f529535..3998b3f49c 100644 --- a/crates/victory-gpu/src/texture/ahead.rs +++ b/crates/victory-gpu/src/texture/ahead.rs @@ -458,6 +458,10 @@ pub(crate) fn read_ahead_line(frames: f64) { return; } let [queued, read, bytes, first, held, full] = [0, 1, 2, 3, 4, 5].map(|i| READ_STATS[i].swap(0, Relaxed) as f64 / frames); + // like the lines next to it, say nothing in menus and quiet frames + if queued + read + first + held + full == 0.0 { + return; + } tracing::info!( "texture uploads of the lists read ahead of their submission (VICTORY_TEXTURE_READ_AHEAD=1), per frame: {queued:.1} queued, \ {read:.1} read ahead ({:.1} MB), {first:.1} the submission filled first, {held:.1} held back (read once no more, exact \ From c0a72b4ebdb75d7307d3d2f160ffc1f9561c8b4b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 22:19:48 +0000 Subject: [PATCH 18/19] docs: Kemerd audit, texture read-ahead Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- docs/KEMERD-AUDIT.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/docs/KEMERD-AUDIT.md b/docs/KEMERD-AUDIT.md index 54980eb99d..1225ec4407 100644 --- a/docs/KEMERD-AUDIT.md +++ b/docs/KEMERD-AUDIT.md @@ -10,7 +10,8 @@ Repozytorium Kemerd ma kilku autorów. Oryginalne commity i ich autorzy: - `VICTORY_FILES_BUFFERED`: `1053639`, D Everett Hinton (nasz `6d39c94`, bez zmian). - `VICTORY_SEND_COPIED_FIND`: `84d94c5`, D Everett Hinton (nasz `595b8cc`, bez zmian). - `VICTORY_TEXTURE_LOOK_ONCE`: `35cafeb`, D Everett Hinton (nasz `8fff3e8`). -- Poprawki z przeglądu: `ef8f00c`, Kemerd (nasz `a5f964a`, wybrane części). +- `VICTORY_TEXTURE_READ_AHEAD`: `19f0de6`, D Everett Hinton. +- Poprawki z przeglądu: `ef8f00c`, Kemerd (nasze `a5f964a` i poprawka read-ahead, wybrane części). Każdy przenoszony mechanizm jest za własnym przełącznikiem, domyślnie wyłączony. Rollback: nie ustawiać przełącznika albo cofnąć commit (`git revert`). @@ -179,6 +180,31 @@ Pomiar: linia `guarded textures read with no write told, per frame: ...` jest wy także bez przełącznika i pokazuje, ile drugich odczytów jest do zaoszczędzenia. Jeśli `again` jest bliskie zera, przełącznik nic nie da. +## 3c2. VICTORY_TEXTURE_READ_AHEAD: IMPLEMENTED (ten PR) + +Commit `19f0de6`, autor D Everett Hinton, plus poprawka Kemerd `ef8f00c` (część read-ahead). +U nas: `crates/victory-gpu/src/texture/ahead.rs` `read_ahead()`, `read_soon()`, +`read_worker()`, `read_ahead_line()`; `texture.rs` `Staging::refresh_soon()`, +`refresh_locked()`, `Last::tried`, `unstage()` zwraca bufor; wywołanie w `draw.rs` przy +przejściu po teksturach. Zależność od RT: brak. + +Co robi: bufor staging, który przejście po teksturach puszcza po jednym uploadzie, czytają +dwa wątki `textures read ahead`, zamiast wątku submitującego przy submisji. Nie dodaje +żadnego kopiowania, tylko przenosi odczyt na inny wątek. Kolejka ma limit 64 MB, a po jego +przekroczeniu bufor czeka na submisję jak dawniej. Bez bake'ów (exact), bez buforów +pilnowanych przez draw z tablicy, tylko z odciskiem do późniejszego sprawdzenia. +Autor podaje 1-5 ms czasu wątku submitującego na klatkę bez RT (górna granica). To nie jest +czas klatki. + +Poprawność (`ef8f00c`): decyzja i odczyt pod jedną blokadą `last`, więc submisja nie wejdzie +między nie. Bufor, który submisja już próbowała odświeżyć (`tried`), jest pomijany, bo jego +kopia może lecieć na kartę. + +Pomiar: linia `texture uploads of the lists read ahead of their submission +(VICTORY_TEXTURE_READ_AHEAD=1), per frame` oraz linia FPS. Według autora nie mogą rosnąć: +„a texture picked by index changed after its upload” i „waiting for a texture another +thread is refreshing”. Test: `texture::ahead::tests::reads_ahead_fit_their_bound`. + ## 3d. Poprawka Kemerd ef8f00c dla VICTORY_STAGING_NO_ZERO `PreludeUpload::record` działa pod blokadą stanów listy, a `zero_if_unwritten` bierze From 84be0adf0b8b1dc1a7c044aab4849ddbd2bc987e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 22:20:07 +0000 Subject: [PATCH 19/19] docs: Kemerd audit, read-ahead source correction Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiiHe46xLWma3psWE1tgae --- docs/KEMERD-AUDIT.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/KEMERD-AUDIT.md b/docs/KEMERD-AUDIT.md index 1225ec4407..24ed34143b 100644 --- a/docs/KEMERD-AUDIT.md +++ b/docs/KEMERD-AUDIT.md @@ -205,6 +205,10 @@ Pomiar: linia `texture uploads of the lists read ahead of their submission „a texture picked by index changed after its upload” i „waiting for a texture another thread is refreshing”. Test: `texture::ahead::tests::reads_ahead_fit_their_bound`. +Sprostowanie: opis commitu `4162a3d` przypisuje sprawdzanie cichych klatek w `ahead.rs` +commitowi `a309f8e`. W rzeczywistości pochodzi ono z `ef8f00c`. `a309f8e` (licznik `in_flight` +dla `VICTORY_UPLOAD_AHEAD`) nie jest przeniesiony. + ## 3d. Poprawka Kemerd ef8f00c dla VICTORY_STAGING_NO_ZERO `PreludeUpload::record` działa pod blokadą stanów listy, a `zero_if_unwritten` bierze