diff --git a/HANDOFF.md b/HANDOFF.md index e6c6913..29fac66 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -653,7 +653,8 @@ The EXE (+ EOSSDK) imports 31 functions from console libraries: MFPlat `MFResetD name @0x40), RetrieveErrorRecord 0x290, Query 0x1C. A worker thread per queue runs the submitted requests in order: file reads through the VFS (as the title's own CreateFileW), memory copies, zlib (miniz_oxide); a status entry gets the first failure since the previous one, a signal sets the D3D12 fence from the CPU; a half-full queue submits by - itself. BCPack (and other console formats) are refused; the unlisted interface slots are logged E_NOTIMPL. The test + itself. BCPack is unpacked where `hle/bcpack` rebuilds the mode's blocks: BC1 and BC5 (2026-11-23); BC3, + BC4, BC6H and BC7 are refused (see "BCPack blocks" below). The unlisted interface slots are logged E_NOTIMPL. The test title reads the start of its own exe through it and waits on the fence. Not yet: cancelling submitted requests, multi-stage (intermediate-size) decompression, destinations that are not plain memory. - **Texture layout library (`xg_xs.dll`, `hle/xg.rs`)** – Fortnite imports `XGCreateTextureComputer`. XCL's own GFX10 @@ -1924,6 +1925,31 @@ three `graphics PSO rejected (0x8007000e)` just before are the driver's E_OUTOFM are on the adapter's device and the per-draw queues were not given back – the draw-heavy tests ended in E_OUTOFMEMORY at CreateCommandQueue with several test threads. +## BCPack blocks: BC1 and BC5 (2026-11-23) + +- **What decodes:** `hle/bcpack` has the entropy stage for every mode and block rebuilds for BC1 and + BC5. A BC5 stream is two symbols per lane per 16-byte block: lane 0 the distance (BC3's + bit-interleaved form), lanes 2/3 the endpoint residues of the two BC4 channels, lanes 4–7 and + 8–11 the 3-bit index pairs (64 possible pairs). Each channel is a plain BC4 block. +- **Tables:** neither mode's stream carries its constants. BC5 needs the 64-entry index-pair table + and a 255-slot endpoint history; XCL takes the estimates of the clean-room decoder + leonida-asset-pipeline (MIT, `bc5_tables.rs`), which fits 214 slots; the 42 it does not fit + (and slots 1–2) end a stream with `Error::History` instead of a guess. Only 3 slots (182, 183, + 222) are reported as confirmed. Its fits agree with SixNG's within a step on the shared slots. + So BC5 output is an approximation wherever one of those constants is off, as BC1's is. +- **BC7 is not done:** its block layout is documented (lanes, mode/partition/rotation/index + selection from lane 15, endpoint and index states), but the rebuild needs two 256-slot history + tables and 10 of the 285 lane-15 signature ranks that no stream carries. The only sources with + fitted values are GPL-3.0 (SixNG, rage-texture), which a GPL-2.0-only crate cannot take; the + MIT decoder ships them empty. A BC7 decoder without them would refuse nearly every chunk, so + it is left out rather than guessed. Same for BC3, BC4 and BC6H (their fitted selector/history + tables have the same problem). +- **Tests** (synthetic, no game files): `bc5_block_rebuild` (hand-built symbols for an in-stream + reference and a history slot), `bc5_blocks_round_trip_through_a_stream` (blocks → symbols → + fragment encoder → entropy decoder → blocks, 1–300 blocks), `bc5_fixture_decodes_to_blocks`, + `fitted_bc5_tables_are_well_formed` (pair table is a permutation, 214 slots fitted, unknown slot + ends the rebuild). + ## Next steps (priority) Little is left to do without the exe – the rest needs an actual run of the game. 1. Once the user has a legal game exe: `xcl inspect`, `xcl run`, analysis of `report.json` diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 5ea31ec..b29d7f5 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -12,7 +12,9 @@ carry a note in their header about its origin and the date of changes (GPL-2.0 | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | | [silicon-rans](https://github.com/microsoft/silicon-rans) (Microsoft) | MIT | BCPack entropy stage: the rANS lane in `crates/xcl/src/hle/bcpack/lanes.rs` (after the `decoder` module of `mdu_minirans.v`) and its model tables in `hle/bcpack/rans_tables.rs` (generated by `scripts/gen_bcpack_tables.py` from the same file) | port to Rust with annotation; tables | | [bcpack-decoder](https://github.com/Tim0219800/bcpack-decoder) (Tim0219800), [bcpack-rs](https://github.com/Ahmet-Dedeler/bcpack-rs) (Ahmet Dedeler) | MIT | no code; the BCPack stream layout, lane widths, byte feeder rule and BC1 block rule in `hle/bcpack/` follow their format notes (`docs/SPEC.md`, `docs/BCPACK_SPEC.md`) | specification | +| [leonida-asset-pipeline](https://github.com/wxrrry/leonida-asset-pipeline) (wxrrry) | MIT | no code; the BC5 block rule in `hle/bcpack/bc5.rs` follows its clean-room decoder (`tools/bcpack.py`) | specification | | bcpack-rs by Ahmet Dedeler (https://github.com/Ahmet-Dedeler/bcpack-rs) | MIT (notice in the file) | `crates/xcl/src/hle/bcpack/bc1_fitted.rs` (generated by `scripts/gen_bcpack_bc1_tables.py` from `data/bc1_window.json` and `data/bc1_quad_table.json`): the two tables of BC1 constants BCPack streams do not carry, as bcpack-rs estimated them from retail data | data tables (estimates; codec constants, not game content) | +| leonida-asset-pipeline by wxrrry (https://github.com/wxrrry/leonida-asset-pipeline) | MIT (notice in the file) | `crates/xcl/src/hle/bcpack/bc5_tables.rs` (generated by `scripts/gen_bcpack_bc5_tables.py` from `tools/bcpack_tables.py`): the two tables of BC5 constants BCPack streams do not carry, as leonida-asset-pipeline estimated them from retail data | data tables (estimates; codec constants, not game content) | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 44698db..f57747d 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -303,6 +303,25 @@ fn cmp_eflags(eflags: u32, lhs: u64, rhs: u64) -> u32 { f } +/// Overwrites the `len` code bytes at `rip` with `head` followed by NOPs, and flushes the +/// instruction cache; left as it is when the page cannot be made writable. +unsafe fn patch_code(rip: usize, len: usize, head: &[u8]) { + use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; + use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + if head.len() > len { + return; + } + let mut old = 0u32; + if VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 { + let code = std::slice::from_raw_parts_mut(rip as *mut u8, len); + code.fill(0x90); + code[..head.len()].copy_from_slice(head); + VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old); + FlushInstructionCache(GetCurrentProcess(), rip as *const std::ffi::c_void, len); + } +} + /// A title's STATUS_ILLEGAL_INSTRUCTION: an instruction the console's Zen 2 has and this CPU /// lacks (`insn`) is emulated and stepped over (EXCEPTION_CONTINUE_EXECUTION); anything else is /// logged with its code bytes and goes on to the title's handlers. @@ -341,8 +360,13 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) }; } } - ConsoleOnly::Monitorx => {} + // MONITORX / MWAITX sit in the title's spin-waits: emulating them costs an exception per + // loop iteration, a core's worth of exception dispatch on a CPU without them (any Intel). + // Rewritten in place on first use, as CLWB is: MONITORX becomes NOPs (it only arms the + // monitor) and MWAITX becomes PAUSE (F3 90) and NOPs, the spin hint the loop waits with. + ConsoleOnly::Monitorx => patch_code(rip, len, &[]), ConsoleOnly::Mwaitx => { + patch_code(rip, len, &[0xF3, 0x90]); std::hint::spin_loop(); } ConsoleOnly::Clzero => { @@ -1182,6 +1206,47 @@ mod tests { } } + /// MONITORX / MWAITX in a title image: on a CPU without them (any Intel) the first run + /// raises STATUS_ILLEGAL_INSTRUCTION, is emulated and rewritten in place (NOPs; PAUSE and a + /// NOP), so later runs raise nothing; on an AMD CPU they run natively and stay as they are. + #[test] + fn monitorx_and_mwaitx_are_rewritten_after_their_first_emulation() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE}; + // f(): xor eax, eax; xor ecx, ecx; xor edx, edx; monitorx; mwaitx; ret + let f_code: &[u8] = &[0x31, 0xC0, 0x31, 0xC9, 0x31, 0xD2, 0x0F, 0x01, 0xFA, 0x0F, 0x01, 0xFB, 0xC3]; + unsafe { + let page = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as *mut u8; + assert!(!page.is_null()); + std::ptr::write_bytes(page, 0xCC, 4096); + std::ptr::copy_nonoverlapping(f_code.as_ptr(), page, f_code.len()); + modules::register_mapped(std::sync::Arc::new(modules::MappedModule { + name: "mwaitx_test.exe".into(), + path: "mwaitx_test.exe".into(), + base: page as usize, + size: 4096, + entry_rva: 0, + is_dll: false, + exports: Default::default(), + tls_callbacks: Default::default(), + no_thread_calls: Default::default(), + initialized: Default::default(), + stack_reserve: 0, + })); + let veh = windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(1, Some(cpp_exception_logger)); + let f: extern "system" fn() = std::mem::transmute(page); + f(); + f(); + let code = std::slice::from_raw_parts(page.add(6), 6); + assert!( + code == [0x0F, 0x01, 0xFA, 0x0F, 0x01, 0xFB] || code == [0x90, 0x90, 0x90, 0xF3, 0x90, 0x90], + "left as it was (native) or rewritten (emulated): {code:02x?}" + ); + windows_sys::Win32::System::Diagnostics::Debug::RemoveVectoredExceptionHandler(veh); + modules::unregister_mapped(page as usize); + VirtualFree(page as _, 0, MEM_RELEASE); + } + } + static TITLE_FILTER_TEST_LOCK: Mutex<()> = Mutex::new(()); #[test] diff --git a/crates/xcl/src/hle/bcpack/bc5.rs b/crates/xcl/src/hle/bcpack/bc5.rs new file mode 100644 index 0000000..c44c94e --- /dev/null +++ b/crates/xcl/src/hle/bcpack/bc5.rs @@ -0,0 +1,122 @@ +//! BC5 blocks from the 12 lanes of a BCPack BC5 stream (two symbols per 16-byte block). +//! +//! Block `i` reads the symbol `2i` (E) and `2i + 1` (O) of every lane: +//! * lane 0 is a distance `d` back to the block whose endpoints predict this one's, bit +//! interleaved over E and O: `x` takes O's bits at positions 0, 2, 4, 6 and `E >> 1`'s at +//! 1, 3, 5, and `d` is `255 - x` when E's lowest bit is set, `x` otherwise. Symbol 0 is +//! "none" (predict 128 for every endpoint); `d <= i` names block `i - d`; a larger `d` names +//! slot `256 + i - d` of the built-in history ([`Tables::preset`]), +//! * lane 1 is unused; the format notes report it as 0 in every stream, and its symbols are +//! ignored here (the fixture generator fills it with noise), +//! * lanes 2 and 3 hold the residues of the endpoint pairs of channel 0 and channel 1, E for +//! the first endpoint and O for the second, 0, -1, 1, -2, 2 … for the symbols 0, 1, 2, 3, +//! 4 …, modulo 256, +//! * lanes 4–7 hold the index pairs of channel 0 and lanes 8–11 those of channel 1: lane +//! `4 + 4c + k` has E = the indices of pixels `4k` and `4k + 1`, O = pixels `4k + 2` and +//! `4k + 3`, each symbol the index of one of the 64 possible pairs in a fixed order +//! ([`Tables::pairs`]). +//! +//! Each channel is a BC4 block: endpoint 0, endpoint 1, then the 16 3-bit indices of the +//! 4 x 4 texels, low texels first, little-endian. The blocks are in the order of the +//! surface's memory, tiled as the console stores it. +//! +//! After the BC5 sections of the public format notes of the SixNG project and the clean-room +//! decoder of leonida-asset-pipeline (wxrrry, MIT), which agree on every symbol; written for +//! XCL on 2026-11-23. + +use super::{lane_widths, lanes, Error}; + +/// The constants of the BC5 rebuild that are not in a stream. +pub struct Tables { + /// The two 3-bit indices each index symbol codes, the first pixel then the second. + pub pairs: [(u8, u8); 64], + /// The endpoint pairs `[channel 0 e0, channel 0 e1, channel 1 e0, channel 1 e1]` of the + /// blocks before a stream's first: `preset[256 + i - d]` is the block `d - i` before block + /// 0 when `d > i` (slot 0 is never read). `None`: not known. + pub preset: [Option<[u8; 4]>; 256], +} + +/// The distance back to the block whose endpoints predict block `i`, from lane 0's symbols. +pub fn distance(e: u8, o: u8) -> usize { + let mut x = 0usize; + for k in 0..4 { + x |= ((o as usize >> k) & 1) << (2 * k); + } + for k in 0..3 { + x |= ((e as usize >> (k + 1)) & 1) << (2 * k + 1); + } + if e & 1 != 0 { + 255 - x + } else { + x + } +} + +/// The residue a symbol stands for: 0, -1, 1, -2, 2 … for 0, 1, 2, 3, 4 … +fn zigzag(v: u8) -> i32 { + if v & 1 == 0 { + (v >> 1) as i32 + } else { + -(((v >> 1) + 1) as i32) + } +} + +/// An endpoint from its prediction and residue, modulo 256. +fn endpoint(predicted: u8, symbol: u8) -> u8 { + (predicted as i32 + zigzag(symbol)) as u8 +} + +/// Unpack a BC5 stream to its `out_len` bytes of blocks. +pub fn decode(src: &[u8], out_len: usize, tables: &Tables) -> Result, Error> { + if out_len % 16 != 0 { + return Err(Error::OutputSize); + } + let widths = lane_widths(5).unwrap(); + let (symbols, consumed) = lanes::decode(src, widths, out_len / 8)?; + if src[consumed..].iter().any(|&b| b != 0) { + return Err(Error::Trailing { consumed }); + } + assemble(&symbols, tables) +} + +/// The blocks of `symbols` (24 per block, two units of 12, in [`super::decode_lanes`]'s order). +pub fn assemble(symbols: &[u8], tables: &Tables) -> Result, Error> { + let blocks = symbols.len() / 24; + let mut out = Vec::new(); + out.try_reserve_exact(blocks * 16).map_err(|_| Error::OutputSize)?; + out.resize(blocks * 16, 0u8); + for i in 0..blocks { + let s = &symbols[i * 24..i * 24 + 24]; + let d = distance(s[0], s[12]); + let base = if d == 0 { + [128; 4] + } else if d <= i { + let p = &out[(i - d) * 16..]; + [p[0], p[1], p[8], p[9]] + } else { + let slot = 256 + i - d; + tables.preset[slot].ok_or(Error::History { block: i, slot })? + }; + let e = [ + endpoint(base[0], s[2]), + endpoint(base[1], s[14]), + endpoint(base[2], s[3]), + endpoint(base[3], s[15]), + ]; + for ch in 0..2 { + let mut bits = 0u64; + for r in 0..4 { + let lane = 4 + 4 * ch + r; + let (a0, a1) = tables.pairs[s[lane] as usize]; + let (b0, b1) = tables.pairs[s[12 + lane] as usize]; + bits |= ((a0 as u64) | (a1 as u64) << 3 | (b0 as u64) << 6 | (b1 as u64) << 9) << (12 * r); + } + let b = &mut out[i * 16 + 8 * ch..i * 16 + 8 * ch + 8]; + b[0] = e[2 * ch]; + b[1] = e[2 * ch + 1]; + // the 16 indices, 3 bits each, low texels first + b[2..8].copy_from_slice(&bits.to_le_bytes()[..6]); + } + } + Ok(out) +} diff --git a/crates/xcl/src/hle/bcpack/bc5_tables.rs b/crates/xcl/src/hle/bcpack/bc5_tables.rs new file mode 100644 index 0000000..7fa7d06 --- /dev/null +++ b/crates/xcl/src/hle/bcpack/bc5_tables.rs @@ -0,0 +1,313 @@ +// Generated by scripts/gen_bcpack_bc5_tables.py from the BC5 tables of leonida-asset-pipeline +// by wxrrry (https://github.com/wxrrry/leonida-asset-pipeline, tools/bcpack_tables.py), used +// under its MIT license: +// +// MIT License +// +// Copyright (c) 2026 wxrrry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// The constants of BCPack's BC5 block rebuild that no stream carries. The history was fitted +// from retail data (decoded blocks against the next smaller mip level, which is stored +// unpacked); it is a constant of the codec, not game content. Only slots 182, 183 and 222 are +// reported as confirmed by the source; the other 214 are its estimates, and being estimates +// they make the BC5 output of XCL an approximation wherever one is off: +// * history: 214 of the 255 entries that can be read; the `None` ones (1, 2, 8, 10, 11, 12, 13, 17, 18, 21, 23, 25, 26, 35, 37, 45, 50, 53, 59, 62, 66, 76, 81, 89, 97, 113, 117, 118, 121, 122, 156, 158, 164, 168, 181, 207, 213, 220, 224, 230, 240) +// were never referred to in the data of the fit. +// A block rebuilt from a history entry carries its error, and so do the blocks that refer to it. + +use super::bc5::Tables; + +pub static TABLES: Tables = Tables { + pairs: PAIRS, + preset: PRESET, +}; + +/// Index symbol -> the two 3-bit indices it codes, the first pixel then the second. +static PAIRS: [(u8, u8); 64] = [ + (0, 0), (1, 1), (4, 4), (3, 3), (6, 6), (7, 7), (4, 0), (0, 4), + (0, 1), (2, 2), (1, 0), (3, 0), (0, 3), (5, 5), (2, 0), (0, 2), + (1, 6), (6, 1), (4, 3), (1, 7), (3, 4), (1, 4), (7, 1), (6, 0), + (0, 6), (6, 3), (6, 4), (3, 6), (3, 2), (4, 6), (1, 5), (1, 3), + (2, 3), (5, 4), (5, 3), (5, 0), (4, 1), (7, 6), (4, 5), (4, 2), + (3, 1), (3, 5), (5, 1), (6, 7), (2, 4), (7, 5), (7, 4), (0, 5), + (6, 5), (4, 7), (5, 7), (7, 0), (5, 6), (0, 7), (7, 3), (3, 7), + (5, 2), (2, 5), (1, 2), (6, 2), (2, 1), (2, 6), (7, 2), (2, 7), +]; + +/// Endpoint history: `[channel 0 e0, channel 0 e1, channel 1 e0, channel 1 e1]` per slot. +static PRESET: [Option<[u8; 4]>; 256] = [ + None, // 0 + None, // 1 + None, // 2 + Some([130, 218, 45, 192]), // 3 + Some([172, 109, 158, 94]), // 4 + Some([183, 136, 113, 69]), // 5 + Some([125, 129, 86, 34]), // 6 + Some([171, 196, 33, 82]), // 7 + None, // 8 + Some([142, 149, 102, 118]), // 9 + None, // 10 + None, // 11 + None, // 12 + None, // 13 + Some([82, 62, 26, 23]), // 14 + Some([100, 94, 32, 32]), // 15 + Some([97, 123, 61, 97]), // 16 + None, // 17 + None, // 18 + Some([133, 140, 118, 123]), // 19 + Some([206, 194, 128, 123]), // 20 + None, // 21 + Some([147, 145, 64, 66]), // 22 + None, // 23 + Some([76, 189, 55, 171]), // 24 + None, // 25 + None, // 26 + Some([94, 115, 86, 102]), // 27 + Some([163, 38, 152, 29]), // 28 + Some([143, 133, 89, 80]), // 29 + Some([197, 67, 172, 50]), // 30 + Some([164, 218, 130, 127]), // 31 + Some([141, 145, 111, 132]), // 32 + Some([177, 125, 131, 32]), // 33 + Some([49, 113, 26, 94]), // 34 + None, // 35 + Some([173, 169, 40, 28]), // 36 + None, // 37 + Some([117, 125, 43, 50]), // 38 + Some([139, 111, 99, 72]), // 39 + Some([123, 93, 83, 49]), // 40 + Some([189, 166, 135, 116]), // 41 + Some([198, 97, 178, 73]), // 42 + Some([205, 201, 76, 86]), // 43 + Some([172, 174, 73, 72]), // 44 + None, // 45 + Some([157, 210, 136, 188]), // 46 + Some([126, 149, 115, 129]), // 47 + Some([158, 67, 137, 41]), // 48 + Some([214, 120, 131, 80]), // 49 + None, // 50 + Some([147, 150, 119, 119]), // 51 + Some([169, 107, 135, 65]), // 52 + None, // 53 + Some([231, 168, 223, 154]), // 54 + Some([115, 144, 99, 120]), // 55 + Some([74, 104, 50, 83]), // 56 + Some([220, 132, 32, 123]), // 57 + Some([150, 136, 110, 96]), // 58 + None, // 59 + Some([139, 147, 124, 108]), // 60 + Some([121, 124, 78, 94]), // 61 + None, // 62 + Some([169, 151, 124, 103]), // 63 + Some([120, 106, 103, 88]), // 64 + Some([134, 147, 110, 109]), // 65 + None, // 66 + Some([133, 125, 103, 107]), // 67 + Some([160, 133, 118, 123]), // 68 + Some([175, 78, 163, 68]), // 69 + Some([229, 133, 166, 121]), // 70 + Some([233, 147, 224, 134]), // 71 + Some([127, 142, 104, 121]), // 72 + Some([134, 150, 99, 121]), // 73 + Some([110, 149, 83, 129]), // 74 + Some([175, 187, 129, 141]), // 75 + None, // 76 + Some([115, 124, 96, 104]), // 77 + Some([164, 128, 141, 109]), // 78 + Some([129, 85, 114, 22]), // 79 + Some([246, 131, 241, 125]), // 80 + None, // 81 + Some([168, 186, 145, 165]), // 82 + Some([192, 133, 158, 100]), // 83 + Some([107, 143, 105, 133]), // 84 + Some([201, 212, 172, 181]), // 85 + Some([124, 138, 116, 121]), // 86 + Some([92, 60, 71, 40]), // 87 + Some([203, 134, 149, 126]), // 88 + None, // 89 + Some([61, 123, 25, 114]), // 90 + Some([123, 160, 113, 145]), // 91 + Some([150, 169, 135, 150]), // 92 + Some([134, 139, 101, 109]), // 93 + Some([253, 94, 255, 63]), // 94 + Some([123, 87, 106, 67]), // 95 + Some([238, 133, 121, 121]), // 96 + None, // 97 + Some([24, 18, 15, 10]), // 98 + Some([117, 41, 97, 25]), // 99 + Some([123, 121, 70, 67]), // 100 + Some([64, 59, 51, 49]), // 101 + Some([11, 103, 12, 88]), // 102 + Some([144, 133, 111, 123]), // 103 + Some([189, 200, 65, 52]), // 104 + Some([219, 153, 195, 135]), // 105 + Some([150, 110, 138, 98]), // 106 + Some([118, 142, 60, 117]), // 107 + Some([139, 145, 114, 118]), // 108 + Some([216, 225, 191, 200]), // 109 + Some([46, 46, 38, 33]), // 110 + Some([91, 132, 85, 126]), // 111 + Some([154, 178, 115, 132]), // 112 + None, // 113 + Some([131, 127, 125, 17]), // 114 + Some([136, 134, 15, 123]), // 115 + Some([131, 129, 105, 123]), // 116 + None, // 117 + None, // 118 + Some([132, 215, 122, 149]), // 119 + Some([129, 138, 112, 111]), // 120 + None, // 121 + None, // 122 + Some([136, 145, 119, 131]), // 123 + Some([179, 196, 165, 183]), // 124 + Some([126, 125, 111, 92]), // 125 + Some([136, 150, 122, 123]), // 126 + Some([168, 158, 136, 126]), // 127 + Some([146, 153, 129, 134]), // 128 + Some([127, 130, 85, 124]), // 129 + Some([132, 241, 120, 126]), // 130 + Some([155, 124, 125, 85]), // 131 + Some([121, 115, 115, 108]), // 132 + Some([106, 72, 89, 51]), // 133 + Some([136, 155, 118, 137]), // 134 + Some([121, 145, 106, 133]), // 135 + Some([119, 220, 102, 209]), // 136 + Some([179, 136, 150, 122]), // 137 + Some([120, 133, 102, 113]), // 138 + Some([145, 142, 111, 112]), // 139 + Some([130, 108, 123, 62]), // 140 + Some([121, 132, 37, 122]), // 141 + Some([157, 142, 135, 119]), // 142 + Some([80, 201, 59, 191]), // 143 + Some([130, 133, 122, 104]), // 144 + Some([138, 136, 112, 120]), // 145 + Some([131, 107, 123, 37]), // 146 + Some([122, 120, 107, 119]), // 147 + Some([126, 181, 121, 146]), // 148 + Some([143, 141, 137, 135]), // 149 + Some([134, 178, 121, 161]), // 150 + Some([103, 135, 55, 126]), // 151 + Some([193, 132, 128, 123]), // 152 + Some([141, 129, 111, 114]), // 153 + Some([79, 77, 53, 51]), // 154 + Some([133, 72, 127, 64]), // 155 + None, // 156 + Some([102, 101, 83, 80]), // 157 + None, // 158 + Some([92, 137, 39, 125]), // 159 + Some([108, 136, 87, 122]), // 160 + Some([102, 97, 65, 57]), // 161 + Some([163, 149, 151, 134]), // 162 + Some([133, 17, 121, 15]), // 163 + None, // 164 + Some([179, 162, 153, 133]), // 165 + Some([119, 132, 98, 125]), // 166 + Some([175, 132, 130, 124]), // 167 + None, // 168 + Some([132, 92, 124, 81]), // 169 + Some([40, 31, 27, 19]), // 170 + Some([188, 211, 180, 202]), // 171 + Some([139, 121, 117, 101]), // 172 + Some([150, 125, 130, 106]), // 173 + Some([129, 184, 123, 131]), // 174 + Some([132, 158, 126, 148]), // 175 + Some([130, 155, 126, 129]), // 176 + Some([131, 167, 124, 127]), // 177 + Some([155, 131, 132, 125]), // 178 + Some([198, 139, 170, 124]), // 179 + Some([200, 196, 190, 186]), // 180 + None, // 181 + Some([133, 126, 124, 55]), // 182 + Some([128, 126, 116, 112]), // 183 + Some([173, 157, 163, 147]), // 184 + Some([197, 175, 158, 137]), // 185 + Some([102, 129, 98, 126]), // 186 + Some([131, 216, 121, 198]), // 187 + Some([127, 135, 115, 130]), // 188 + Some([139, 196, 94, 111]), // 189 + Some([132, 106, 123, 94]), // 190 + Some([219, 130, 193, 116]), // 191 + Some([212, 133, 127, 124]), // 192 + Some([196, 176, 173, 151]), // 193 + Some([56, 192, 15, 27]), // 194 + Some([129, 198, 124, 131]), // 195 + Some([131, 124, 125, 99]), // 196 + Some([176, 130, 169, 126]), // 197 + Some([137, 127, 121, 111]), // 198 + Some([144, 137, 131, 123]), // 199 + Some([132, 130, 114, 120]), // 200 + Some([182, 165, 169, 153]), // 201 + Some([138, 136, 113, 109]), // 202 + Some([185, 172, 179, 164]), // 203 + Some([131, 127, 123, 81]), // 204 + Some([124, 141, 121, 137]), // 205 + Some([173, 131, 136, 92]), // 206 + None, // 207 + Some([120, 133, 108, 123]), // 208 + Some([147, 134, 123, 110]), // 209 + Some([130, 142, 125, 129]), // 210 + Some([136, 137, 122, 131]), // 211 + Some([130, 119, 127, 114]), // 212 + None, // 213 + Some([117, 136, 111, 131]), // 214 + Some([199, 181, 187, 167]), // 215 + Some([132, 215, 124, 125]), // 216 + Some([135, 138, 120, 114]), // 217 + Some([131, 85, 123, 45]), // 218 + Some([197, 131, 193, 126]), // 219 + None, // 220 + Some([69, 206, 57, 195]), // 221 + Some([131, 128, 123, 37]), // 222 + Some([161, 156, 96, 92]), // 223 + None, // 224 + Some([130, 136, 123, 121]), // 225 + Some([126, 60, 118, 46]), // 226 + Some([139, 137, 120, 124]), // 227 + Some([140, 130, 124, 123]), // 228 + Some([122, 127, 118, 123]), // 229 + None, // 230 + Some([130, 141, 127, 138]), // 231 + Some([54, 205, 50, 185]), // 232 + Some([75, 74, 69, 68]), // 233 + Some([223, 130, 217, 125]), // 234 + Some([111, 129, 108, 127]), // 235 + Some([160, 129, 157, 126]), // 236 + Some([129, 217, 126, 217]), // 237 + Some([148, 128, 146, 126]), // 238 + Some([130, 129, 127, 118]), // 239 + None, // 240 + Some([60, 200, 50, 200]), // 241 + Some([131, 130, 120, 124]), // 242 + Some([123, 132, 116, 127]), // 243 + Some([132, 135, 130, 132]), // 244 + Some([129, 41, 126, 37]), // 245 + Some([122, 133, 120, 133]), // 246 + Some([118, 128, 116, 126]), // 247 + Some([136, 128, 133, 126]), // 248 + Some([128, 133, 123, 131]), // 249 + Some([82, 81, 78, 77]), // 250 + Some([124, 130, 122, 128]), // 251 + Some([130, 130, 125, 124]), // 252 + Some([128, 128, 127, 127]), // 253 + Some([127, 126, 126, 125]), // 254 + Some([129, 127, 128, 126]), // 255 +]; diff --git a/crates/xcl/src/hle/bcpack/mod.rs b/crates/xcl/src/hle/bcpack/mod.rs index 845acaa..7199930 100644 --- a/crates/xcl/src/hle/bcpack/mod.rs +++ b/crates/xcl/src/hle/bcpack/mod.rs @@ -10,19 +10,30 @@ //! is published for BC2, //! * the rebuild of BC1 blocks ([`bc1`]), which needs two tables of constants that are not in //! the stream ([`bc1::Tables`]). XCL has the estimates bcpack-rs made of them -//! (`bc1_fitted.rs`), so its BC1 blocks are an approximation wherever an estimate is off. +//! (`bc1_fitted.rs`), so its BC1 blocks are an approximation wherever an estimate is off, +//! * the rebuild of BC5 blocks ([`bc5`]), which also needs constants that are not in the +//! stream ([`bc5::Tables`]). XCL has the index-pair table and the estimates +//! leonida-asset-pipeline made of the history (`bc5_tables.rs`), so its BC5 blocks are an +//! approximation wherever an estimate is off. //! -//! What is not: the rebuild of the other formats. Their lanes decode, but how the symbols map -//! to block bits is not published in a form XCL can use, so those requests are still refused. +//! What is not: the rebuild of BC3, BC4, BC6H and BC7. Their lanes decode, but the block +//! rebuild needs tables of constants that no stream carries. For BC7 those are the 256-slot +//! endpoint history, the 256-slot index history and 10 of the 285 lane-15 mode signatures; +//! the only sources that fitted them are GPL-3.0, which this GPL-2.0-only crate cannot take, +//! and the clean-room decoder that XCL's BC5 tables come from ships them empty. Guessing them +//! would make the output wrong, so those requests are still refused. //! //! Nothing here was compared with what a console writes for the same input: the entropy stage -//! follows Microsoft's published decoder sample and the BC1 rules the public format notes of -//! bcpack-decoder (Tim0219800) and bcpack-rs (Ahmet Dedeler), both MIT, whose authors report -//! them as matching retail streams. The tests check against streams built independently from -//! those notes (`tests/data/bcpack`), not against hardware output. +//! follows Microsoft's published decoder sample and the block rules the public format notes of +//! bcpack-decoder (Tim0219800) and bcpack-rs (Ahmet Dedeler), the clean-room decoder of +//! leonida-asset-pipeline (wxrrry, MIT) and the format notes of SixNG, whose authors report them +//! as matching retail streams. The tests check against streams built independently from those +//! notes (`tests/data/bcpack`), not against hardware output. pub mod bc1; mod bc1_fitted; +pub mod bc5; +mod bc5_tables; mod lanes; mod rans_tables; @@ -128,15 +139,29 @@ fn bc1_tables() -> Option<&'static bc1::Tables> { } } +/// The BC5 tables, when XCL has them: the estimates of leonida-asset-pipeline, and in the +/// tests the made-up set their fixtures were built with. +fn bc5_tables() -> &'static bc5::Tables { + #[cfg(test)] + { + tests::bc5_tables() + } + #[cfg(not(test))] + { + &bc5_tables::TABLES + } +} + /// Whether [`decode`] has a block rebuild for `mode`. pub fn can_decode(mode: u8) -> bool { - mode == 1 && bc1_tables().is_some() + mode == 5 || (mode == 1 && bc1_tables().is_some()) } /// Unpack a stream of `mode` to its `out_len` bytes of BCn blocks. pub fn decode(mode: u8, src: &[u8], out_len: usize) -> Result, Error> { match (mode, bc1_tables()) { (1, Some(t)) => bc1::decode(src, out_len, t), + (5, _) => bc5::decode(src, out_len, bc5_tables()), _ => Err(Error::Unsupported), } } diff --git a/crates/xcl/src/hle/bcpack/tests.rs b/crates/xcl/src/hle/bcpack/tests.rs index a5ab53a..4b7d560 100644 --- a/crates/xcl/src/hle/bcpack/tests.rs +++ b/crates/xcl/src/hle/bcpack/tests.rs @@ -4,7 +4,7 @@ use super::lanes::{self, L}; use super::rans_tables::FREQ; -use super::{bc1, decode_lanes, lane_widths, Error}; +use super::{bc1, bc5, decode_lanes, lane_widths, Error}; /// The tables the fixtures' `.bc1` files were made with: history entry `slot` has the /// channels `(7 * slot + 13 * k) mod range`, and a quadrant symbol is its own selectors. @@ -23,6 +23,19 @@ pub(crate) fn data(name: &str) -> Option> { std::fs::read(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data/bcpack").join(name)).ok() } +/// The BC5 tables the tests use: the index pairs in an order of their own, and a history whose +/// slot `s` holds `(5s, 7s, 11s, 13s)` so a test can name the entry it expects. +pub(crate) fn bc5_tables() -> &'static bc5::Tables { + static T: std::sync::OnceLock = std::sync::OnceLock::new(); + T.get_or_init(|| bc5::Tables { + pairs: std::array::from_fn(|s| ((s & 7) as u8, (s >> 3) as u8)), + preset: std::array::from_fn(|slot| { + let v = slot as u8; + Some([v.wrapping_mul(5), v.wrapping_mul(7), v.wrapping_mul(11), v.wrapping_mul(13)]) + }), + }) +} + /// `bc--` → (mode, units) fn fixture(stem: &str) -> (u8, usize) { let mut p = stem.strip_prefix("bc").unwrap().split('-'); @@ -96,10 +109,11 @@ fn bc1_fixtures_decode_to_their_blocks() { assert_eq!(super::decode(1, &bin, units * 8).as_deref(), Ok(&blocks[..]), "{stem}"); } // the modes without a block rebuild - for mode in [0u8, 2, 3, 4, 5, 6, 7, 8, 15] { + for mode in [0u8, 2, 3, 4, 6, 7, 8, 15] { assert!(!super::can_decode(mode)); assert_eq!(super::decode(mode, &[], 16), Err(Error::Unsupported)); } + assert!(super::can_decode(5)); } /// One BC1 block by hand: every field of the rebuild, without the entropy stage. @@ -371,3 +385,222 @@ fn fitted_bc1_tables_are_well_formed() { assert_eq!(bc1::assemble(&s, t), Err(Error::History { block: 0, slot })); } } + +// --------------------------------------------------------------------------------------- +// BC5 +// --------------------------------------------------------------------------------------- + +/// A stream of one flush per lane, carrying `symbols` (unit-major) through the fragment +/// encoder of this file. The lanes' bytes are put in the order the decoder asks for them. +fn stream_from_symbols(widths: &[u8], symbols: &[u8]) -> Vec { + let n = widths.len(); + let units = symbols.len() / n; + let mut queues: Vec> = Vec::new(); + for (l, &w) in widths.iter().enumerate() { + let lane: Vec = (0..units).map(|u| symbols[u * n + l]).collect(); + queues.push(fragment(&lane, w as usize, 0, 0, true).into()); + } + let mut stream = Vec::new(); + lanes::run(widths, units, |lane| { + let b = queues[lane].pop_front(); + stream.extend(b); + b + }) + .expect("the encoder's own fragments decode"); + assert!(queues.iter().all(|q| q.is_empty()), "every fragment was read to its end"); + stream +} + +/// Lane 0's (E, O) symbols for the distance `d`: the inverse of [`bc5::distance`]. +fn bc5_distance_symbols(d: usize) -> (u8, u8) { + let (x, low) = if d <= 127 { (d, 0u8) } else { (255 - d, 1u8) }; + let mut e = low; + let mut o = 0u8; + for k in 0..4 { + o |= (((x >> (2 * k)) & 1) as u8) << k; + } + for k in 0..3 { + e |= (((x >> (2 * k + 1)) & 1) as u8) << (k + 1); + } + (e, o) +} + +/// The residue symbol for `want` from its prediction `base`, modulo 256. +fn bc5_residue(want: u8, base: u8) -> u8 { + let delta = (want as i32 - base as i32).rem_euclid(256); + let delta = if delta > 127 { delta - 256 } else { delta }; + if delta >= 0 { + (2 * delta) as u8 + } else { + (-2 * delta - 1) as u8 + } +} + +/// One BC5 block by hand: both channels, a reference inside the stream and one before it. +#[test] +fn bc5_block_rebuild() { + let t = bc5_tables(); + let mut s = vec![[0u8; 24]; 3]; + // block 0: no reference, so both channels predict 128; channel 0's endpoints grow by 1 + // and 2, channel 1's by 0 and 3; every index pair is symbol 0, which the test table maps + // to (0, 0) + s[0][2] = 2; + s[0][14] = 4; + s[0][15] = 6; + // block 1: one block back, the same endpoints; lane 4's E symbol 58 names (2, 7) + let (e1, o1) = bc5_distance_symbols(1); + assert_eq!((e1, o1), (0, 1)); + s[1][0] = e1; + s[1][12] = o1; + s[1][4] = 58; + // block 2: 255 back, before the stream: history slot 256 + 2 - 255 = 3 + let (e2, o2) = bc5_distance_symbols(255); + assert_eq!((e2, o2), (1, 0)); + s[2][0] = e2; + s[2][12] = o2; + let out = bc5::assemble(&s.concat(), t).unwrap(); + assert_eq!(out.len(), 48); + assert_eq!(out[..8], [129, 130, 0, 0, 0, 0, 0, 0]); + assert_eq!(out[8..16], [128, 131, 0, 0, 0, 0, 0, 0]); + assert_eq!(out[16..24], [129, 130, 58, 0, 0, 0, 0, 0]); + assert_eq!(out[24..32], [128, 131, 0, 0, 0, 0, 0, 0]); + let h = t.preset[3].unwrap(); + assert_eq!(out[32..34], h[..2]); + assert_eq!(out[40..42], h[2..]); + assert_eq!(out[34..40], [0; 6]); + assert_eq!(out[42..48], [0; 6]); + + // the distance mapping of the format notes, and its inverse over every value + assert_eq!(bc5::distance(0, 0), 0); + assert_eq!(bc5::distance(0, 1), 1); + assert_eq!(bc5::distance(2, 0), 2); + assert_eq!(bc5::distance(1, 0), 255); + for d in 0..256 { + let (e, o) = bc5_distance_symbols(d); + assert_eq!(bc5::distance(e, o), d); + } + + // an unknown history entry stops the stream instead of guessing + let mut holes = bc5::Tables { pairs: t.pairs, preset: t.preset }; + holes.preset[3] = None; + assert_eq!(bc5::assemble(&s.concat(), &holes), Err(Error::History { block: 2, slot: 3 })); +} + +/// Blocks built here, coded into lane symbols, encoded into a stream, decoded and compared. +#[test] +fn bc5_blocks_round_trip_through_a_stream() { + let t = bc5_tables(); + let widths = lane_widths(5).unwrap(); + let inverse: Vec> = { + let mut inv = vec![None; 64]; + for (sym, &(a, b)) in t.pairs.iter().enumerate() { + inv[(a * 8 + b) as usize] = Some(sym as u8); + } + inv + }; + let mut rng = Rng(0xB0C5); + for &blocks in &[1usize, 2, 9, 64, 300] { + let mut want = vec![[0u8; 16]; blocks]; + let mut idx = vec![[0u64; 2]; blocks]; + for i in 0..blocks { + want[i][0] = rng.next() as u8; + want[i][1] = rng.next() as u8; + want[i][8] = rng.next() as u8; + want[i][9] = rng.next() as u8; + for ch in 0..2 { + let mut w = 0u64; + for p in 0..16 { + w |= (rng.below(8) as u64) << (3 * p); + } + idx[i][ch] = w; + want[i][8 * ch + 2..8 * ch + 8].copy_from_slice(&w.to_le_bytes()[..6]); + } + } + let mut symbols = vec![0u8; blocks * 24]; + for i in 0..blocks { + // early blocks read the history, the others a block behind them + let d = if i == 0 { + 0 + } else if i % 11 == 0 && i < 250 { + 251 + i % 4 + } else { + 1 + (i % 7).min(i - 1) + }; + let base = if d == 0 { + [128u8; 4] + } else if d <= i { + let p = &want[i - d]; + [p[0], p[1], p[8], p[9]] + } else { + t.preset[256 + i - d].expect("the test tables fit every slot") + }; + let (e, o) = bc5_distance_symbols(d); + symbols[i * 24] = e; + symbols[i * 24 + 12] = o; + for ch in 0..2 { + symbols[i * 24 + 2 + ch] = bc5_residue(want[i][8 * ch], base[2 * ch]); + symbols[i * 24 + 12 + 2 + ch] = bc5_residue(want[i][8 * ch + 1], base[2 * ch + 1]); + let w = idx[i][ch]; + let px = |p: usize| ((w >> (3 * p)) & 7) as usize; + for r in 0..4 { + symbols[i * 24 + 4 + 4 * ch + r] = inverse[px(4 * r) * 8 + px(4 * r + 1)].unwrap(); + symbols[i * 24 + 12 + 4 + 4 * ch + r] = inverse[px(4 * r + 2) * 8 + px(4 * r + 3)].unwrap(); + } + } + } + assert_eq!(bc5::assemble(&symbols, t).unwrap(), want.concat(), "{blocks} blocks"); + let stream = stream_from_symbols(widths, &symbols); + assert_eq!(super::decode(5, &stream, blocks * 16).as_deref(), Ok(&want.concat()[..]), "{blocks} blocks"); + // every byte of the stream is needed, and the size must be a whole number of blocks + assert!(super::decode(5, &stream[..stream.len() - 1], blocks * 16).is_err(), "{blocks} blocks"); + assert_eq!(super::decode(5, &stream, blocks * 16 + 1), Err(Error::OutputSize)); + } +} + +/// The BC5 fixture of `tests/data/bcpack` (an independent encoder) goes through the entropy +/// stage and the rebuild. Its lane 1 holds noise, which the rebuild ignores. +#[test] +fn bc5_fixture_decodes_to_blocks() { + let bin = data("bc5-16-1.bin").unwrap(); + let blocks = super::decode(5, &bin, 8 * 16).expect("the fixture decodes"); + assert_eq!(blocks.len(), 8 * 16); +} + +/// The BC5 tables XCL ships (`bc5_tables.rs`) are whole and in the layout [`bc5::assemble`] +/// reads. +#[test] +fn fitted_bc5_tables_are_well_formed() { + let t = &super::bc5_tables::TABLES; + let mut seen = [false; 64]; + for &(a, b) in &t.pairs { + assert!(a < 8 && b < 8); + assert!(!std::mem::replace(&mut seen[(a * 8 + b) as usize], true), "pair ({a}, {b}) twice"); + } + // slot 0 is never read; 214 of the 255 readable slots were fitted, the three the source + // reports as confirmed among them + assert!(t.preset[0].is_none()); + assert_eq!(t.preset.iter().flatten().count(), 214); + for slot in [182, 183, 222] { + assert!(t.preset[slot].is_some()); + } + + // a first block that takes the endpoints of the block 253 before the stream (slot 3) as + // they are + let mut s = [0u8; 24]; + let (e, o) = bc5_distance_symbols(253); + s[0] = e; + s[12] = o; + let b = bc5::assemble(&s, t).unwrap(); + let h = t.preset[3].unwrap(); + assert_eq!(b[..2], h[..2]); + assert_eq!(b[8..10], h[2..]); + assert_eq!(b[2..8], [0; 6]); + assert_eq!(b[10..16], [0; 6]); + + // an entry the fit does not have ends the rebuild + let mut unknown = [0u8; 24]; + let (e, o) = bc5_distance_symbols(254); // slot 2 + unknown[0] = e; + unknown[12] = o; + assert_eq!(bc5::assemble(&unknown, t), Err(Error::History { block: 0, slot: 2 })); +} diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 199f724..65cad93 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -1,12 +1,14 @@ -//! Write32/64BitValueBottomOfPipeX into memory the GPU does not see: done by the CPU once the GPU -//! has finished the work before them. +//! Work on memory the GPU does not see, done by the CPU once the GPU has finished the work +//! before it: Write32/64BitValueBottomOfPipeX, and CopyMemoryToMemoryX with a side outside +//! unified memory. //! //! A console title marks its GPU progress with bottom-of-pipe writes into its own memory and //! waits on them (a retail game: plain `VirtualAlloc` memory, outside XCL's unified memory). //! The PC GPU cannot write there; dropped, the title waited for ever after its second frame. -//! Here each queue gets a fence of XCL's: after a submission whose lists carry such writes the -//! queue signals it, and a worker thread does the writes, in submission order, when the GPU is -//! there – what bottom of pipe means. +//! It also copies through its memory the GPU has no address for (command list #60 with a side +//! outside the windows). Here each queue gets a fence of XCL's: after a submission whose lists +//! carry such work the queue signals it, and a worker thread does the work, in submission +//! order, when the GPU is there – what bottom of pipe means. use std::collections::HashMap; use std::ffi::c_void; @@ -21,10 +23,20 @@ use windows_sys::Win32::System::Threading as th; /// (address, the dwords from there) pub(super) type Write = (usize, Vec); +/// A copy the CPU does after the queue's earlier work: (destination, source, bytes). +/// Its bytes are read from the source when it runs, so they are what the GPU has left there. +pub(super) type Copy = (usize, usize, usize); + +/// What a worker does for one submission, in this order. +pub(super) enum Work { + Words(Write), + Copy(Copy), +} + struct Job { fence: ID3D12Fence, value: u64, - writes: Vec, + work: Vec, } // SAFETY: the fence is a free-threaded COM object; the writes are plain data @@ -54,8 +66,11 @@ fn worker() -> &'static Mutex> { if job.fence.GetCompletedValue() < job.value && job.fence.SetEventOnCompletion(job.value, HANDLE(event as *mut c_void)).is_ok() { th::WaitForSingleObject(event, WAIT_MS); } - for (va, words) in &job.writes { - write_now(*va, words); + for w in &job.work { + match w { + Work::Words((va, words)) => write_now(*va, words), + Work::Copy((dst, src, bytes)) => copy_now(*dst, *src, *bytes), + } } } }); @@ -81,21 +96,50 @@ unsafe fn write_now(va: usize, words: &[u32]) { } } +/// `[va, va + bytes)` as the CPU sees it: committed, and writable when `write`. +unsafe fn commit_check(va: usize, bytes: usize, write: bool) -> bool { + use windows_sys::Win32::System::Memory::{ + VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READONLY, PAGE_READWRITE, + }; + if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { + // the coherent windows are committed read-write as a whole (no VirtualQuery walk) + return true; + } + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + let found = VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0; + let ok = if write { + m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 + } else { + m.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 + }; + found && m.State == MEM_COMMIT && ok && m.BaseAddress as usize + m.RegionSize >= va + bytes +} + /// Whether `[va, va + bytes)` is memory the CPU can write for the GPU later. pub(super) fn writable(va: usize, bytes: usize) -> bool { crate::hle::kernelx::lazy::ensure(va, bytes); - use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; - let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - let found = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0; - found - && m.State == MEM_COMMIT - && m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 - && m.BaseAddress as usize + m.RegionSize >= va + bytes + unsafe { commit_check(va, bytes, true) } } -/// `writes` of lists just submitted to `queue`: done when the GPU has finished them. -pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { - if writes.is_empty() || queue.is_null() { +/// Whether `[va, va + bytes)` is memory the CPU can read for a copy. +pub(super) fn readable(va: usize, bytes: usize) -> bool { + crate::hle::kernelx::lazy::ensure(va, bytes); + unsafe { commit_check(va, bytes, false) } +} + +/// `bytes` from `src` to `dst` on the CPU, when both are memory it can reach; a destination in +/// a sparse window then goes to that window's video memory for the GPU's later work. +pub(super) unsafe fn copy_now(dst: usize, src: usize, bytes: usize) { + if bytes == 0 || !writable(dst, bytes) || !readable(src, bytes) { + return; + } + std::ptr::copy(src as *const u8, dst as *mut u8, bytes); + super::sparse::flush_written(dst, bytes); +} + +/// `work` of lists just submitted to `queue`: done when the GPU has finished them. +pub(super) unsafe fn after(queue: *mut c_void, work: Vec) { + if work.is_empty() || queue.is_null() { return; } let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; @@ -118,10 +162,10 @@ pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { if q.Signal(&entry.fence, entry.value).is_err() { return; } - Job { fence: entry.fence.clone(), value: entry.value, writes } + Job { fence: entry.fence.clone(), value: entry.value, work } }; static FIRST: std::sync::Once = std::sync::Once::new(); - FIRST.call_once(|| crate::xlog_info!("D3D12.X: bottom-of-pipe writes outside unified memory are done by the CPU after the GPU ({} in the first submission)", job.writes.len())); + FIRST.call_once(|| crate::xlog_info!("D3D12.X: bottom-of-pipe writes outside unified memory are done by the CPU after the GPU ({} in the first submission)", job.work.len())); let _ = worker().lock().unwrap().send(job); } @@ -146,7 +190,7 @@ mod tests { let cell = Box::new([0u32; 2]); let va = cell.as_ptr() as usize; assert!(writable(va, 8)); - after(q.as_raw(), vec![(va, vec![7, 9])]); + after(q.as_raw(), vec![Work::Words((va, vec![7, 9]))]); let t = std::time::Instant::now(); while (*(va as *const AtomicU32)).load(Ordering::Acquire) != 7 { assert!(t.elapsed().as_secs() < 5, "never written"); @@ -155,4 +199,45 @@ mod tests { assert_eq!(*cell, [7, 9]); } } + + /// A copy of the title's memory outside unified memory lands too, after the queue has done + /// what came before it. + #[test] + fn copies_land_after_the_queue() { + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap(); + let warp: IDXGIAdapter = factory.EnumWarpAdapter().unwrap(); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.unwrap(); + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let src = Box::new([0xA5u8; 0x400]); + let dst = Box::new([0u8; 0x400]); + let (s, d) = (src.as_ptr() as usize, dst.as_ptr() as usize); + assert!(writable(d, 0x400) && readable(s, 0x400)); + after(q.as_raw(), vec![Work::Copy((d, s, 0x400))]); + let t = std::time::Instant::now(); + while *dst.first().unwrap() != 0xA5 { + assert!(t.elapsed().as_secs() < 5, "never copied"); + std::thread::yield_now(); + } + assert_eq!(*dst, *src, "the whole range"); + } + } + + /// A copy the CPU cannot make (a source that is no memory of the title's) changes nothing. + #[test] + fn a_copy_the_cpu_cannot_make_changes_nothing() { + unsafe { + let dst = Box::new([0u8; 0x100]); + let d = dst.as_ptr() as usize; + copy_now(d, 0x10, 0x100); + assert!(!readable(0x10, 0x100)); + assert_eq!(*dst, [0u8; 0x100]); + copy_now(d, d, 0); + assert_eq!(*dst, [0u8; 0x100]); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 270fdd1..de14814 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -559,6 +559,9 @@ struct ListState { pending_waits: Vec, /// bottom-of-pipe writes into memory the GPU does not see (`cpu_writes`) cpu_writes: Vec, + /// copies with a side outside the unified-memory windows, done by the CPU after the queue's + /// earlier work: `(destination, source, bytes)` + copies: Vec, /// Dedicated 256-byte buffer holding the current predicate value (created lazily in COMMON state). pred_buf: Option, /// True while `pred_buf` is in `D3D12_RESOURCE_STATE_PREDICATION` on this open recording. @@ -582,11 +585,20 @@ impl ListState { last.1 = last.1.max(end); } if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) { - if self.sparse_writes.is_empty() { - SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); - } - self.sparse_writes.push((va as usize, size as usize)); + self.note_sparse(va as usize, size as usize); + } + } + + /// A sparse-window range whose CPU view the GPU's writes must reach (before the CPU reads + /// it: a copy out of it, a wait on it). + fn note_sparse(&mut self, va: usize, size: usize) { + if size == 0 { + return; + } + if self.sparse_writes.is_empty() { + SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); } + self.sparse_writes.push((va, size)); } fn clear_sparse_writes(&mut self) -> Vec<(usize, usize)> { @@ -929,14 +941,26 @@ pub(super) unsafe fn readback_sparse_writes(queue: *mut c_void, lists: &[*mut c_ } } -/// After `lists` went to `queue`: their writes into memory the GPU does not see (`cpu_writes`). +/// After `lists` went to `queue`: their work on memory the GPU does not see (`cpu_writes`): +/// bottom-of-pipe writes, and copies with a side outside the unified-memory windows. pub(super) unsafe fn cpu_writes_after(queue: *mut c_void, lists: &[*mut c_void]) { - let writes: Vec = { + let (writes, copies): (Vec, Vec) = { let g = LISTS.lock().unwrap(); let Some(m) = g.as_ref() else { return }; - lists.iter().filter_map(|&l| m.get(&(l as usize))).flat_map(|s| s.cpu_writes.iter().cloned()).collect() + ( + lists.iter().filter_map(|&l| m.get(&(l as usize))).flat_map(|s| s.cpu_writes.iter().cloned()).collect(), + lists.iter().filter_map(|&l| m.get(&(l as usize))).flat_map(|s| s.copies.iter().copied()).collect(), + ) }; - super::cpu_writes::after(queue, writes); + super::cpu_writes::after(queue, deferred_work(writes, copies)); +} + +/// The work of a list's recorded bottom-of-pipe writes and CPU copies, in that order, for +/// `cpu_writes::after` (`KickoffX` submits its one list itself). +pub(super) fn deferred_work(writes: Vec, copies: Vec) -> Vec { + let mut work: Vec = writes.into_iter().map(super::cpu_writes::Work::Words).collect(); + work.extend(copies.into_iter().map(super::cpu_writes::Work::Copy)); + work } /// Submit `lists` through `submit`, splitting the batch before any list whose `Wait32/64BitValueX` @@ -979,17 +1003,26 @@ pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], mut submit: impl // --------------------------------------------------------------------------------------- /// command list #60 CopyMemoryToMemoryX(destination, source, size, flags) +/// +/// Both sides in unified-memory windows: a GPU copy (`CopyBufferRegion`). A side outside them +/// – the title's own memory, which the PC's GPU has no address for – the CPU copies, after the +/// queue's earlier work as `cpu_writes` does; a destination in a sparse window's video memory +/// gets the bytes then too (`sparse::flush_written`), a source there is read back first. pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, src: u64, size: u64, _flags: u32) { static N: AtomicU64 = AtomicU64::new(0); const W: &str = "CopyMemoryToMemoryX"; if size == 0 || !size.is_multiple_of(4) { return warn(&N, W, format_args!("size {size:#x} is not a non-zero multiple of 4")); } - let (Some((d, doff)), Some((s, soff))) = (real::uma_window_buffer(dst as usize, size as usize), real::uma_window_buffer(src as usize, size as usize)) else { - note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); - return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) is not in unified memory")); + note_gpu_write(W, dst as usize, size); + // in a window whose video memory reaches it: the GPU's copy + let window = |p: u64| { + real::uma_window_buffer(p as usize, size as usize) + .filter(|_| !crate::gpu::uma::get().is_some_and(|u| u.is_sparse(p as usize)) || super::sparse::has_video_memory(p as usize, size as usize)) + }; + let (Some((d, doff)), Some((s, soff))) = (window(dst), window(src)) else { + return cpu_copy(this, dst, src, size, W); }; - note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); if d == s && dst < src + size && src < dst + size { return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) overlap")); } @@ -1004,6 +1037,31 @@ pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, transition(this, s, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); } +/// `CopyMemoryToMemoryX` with a side outside the unified-memory windows: the CPU copies it once +/// the queue is past this list's earlier work (`cpu_writes::after`). +unsafe fn cpu_copy(this: *mut c_void, dst: u64, src: u64, size: u64, what: &str) { + static N: AtomicU64 = AtomicU64::new(0); + let (dp, sp) = (dst as usize, src as usize); + if !super::cpu_writes::writable(dp, size as usize) || !super::cpu_writes::readable(sp, size as usize) { + return warn(&N, what, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) is not in unified memory and the CPU cannot copy it")); + } + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) else { return }; + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(sp)) { + // the GPU's writes to the source reach its CPU view before the copy reads it + s.note_sparse(sp, size as usize); + } + s.copies.push((dp, sp, size as usize)); + drop(g); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 4 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: {what}: {src:#x} → {dst:#x} ({size:#x} bytes) outside unified memory is copied by the CPU after the queue's work (#{n}{})", + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(dp)) { ", into the destination window's video memory" } else { "" } + ); + } +} + unsafe fn device_of(list: *mut c_void) -> Option { let mut dev: Option = None; ID3D12GraphicsCommandList::from_raw_borrowed(&list)?.GetDevice(&mut dev).ok()?; @@ -1477,11 +1535,12 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let sparse_writes = s.clear_sparse_writes(); s.written_ranges.clear(); let cpu_writes = std::mem::take(&mut s.cpu_writes); + let copies = std::mem::take(&mut s.copies); let pred_in_state = std::mem::replace(&mut s.pred_in_state, false); let pred_buf = s.pred_buf.as_ref().map(|r| r.as_raw() as usize); - (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, waits, (sparse_writes, cpu_writes)) + (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, waits, (sparse_writes, cpu_writes, copies)) }; - let (sparse_writes, cpu_writes) = sparse_writes; + let (sparse_writes, cpu_writes, copies) = sparse_writes; // End any active occlusion query before Close (PC forbids closing with an open query). if let Some(((h, i), qty)) = active_query { @@ -1518,7 +1577,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { super::sparse::readback_after_execute(q, &sparse_writes); } } - super::cpu_writes::after(q_raw, cpu_writes); + super::cpu_writes::after(q_raw, deferred_work(cpu_writes, copies)); let ext_closed = *(this as *const usize); let init_pso = super::pso_async::resolve_for_bind(bound_pso); @@ -2104,6 +2163,7 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz s.clear_sparse_writes(); s.clear_waits(); s.cpu_writes.clear(); + s.copies.clear(); s.predication = None; s.pred_in_state = false; s.bindings = Bindings::default(); @@ -2719,6 +2779,30 @@ mod tests { assert!(!s.has_prior_write(0x0FF8, 8)); } + /// CopyMemoryToMemoryX with a side outside the unified-memory windows (two buffers of the + /// CPU's own) is recorded for the CPU to do once the queue is past the list's earlier work. + #[test] + fn copy_outside_unified_memory_goes_to_the_cpu() { + let src = Box::new([0x5Au8; 0x100]); + let dst = Box::new([0u8; 0x100]); + let (s, d) = (src.as_ptr() as u64, dst.as_ptr() as u64); + let l = 0x7100_0002usize as *mut c_void; + unsafe { + on_create(l, 0x100, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + copy_memory_x(l, d, s, 0x100, 0); + } + let copies = { + let g = LISTS.lock().unwrap(); + g.as_ref().unwrap().get(&(l as usize)).unwrap().copies.clone() + }; + assert_eq!(copies, vec![(d as usize, s as usize, 0x100usize)], "one CPU copy, in the list's record"); + assert!(*dst == [0u8; 0x100], "nothing copied at the record"); + // the CPU's copy does it + unsafe { super::super::cpu_writes::copy_now(copies[0].0, copies[0].1, copies[0].2) }; + assert!(*dst == [0x5Au8; 0x100]); + LISTS.lock().unwrap().as_mut().unwrap().remove(&(l as usize)); + } + #[test] fn execute_with_waits_splits_batches_before_unsatisfied_list() { // Use synthetic non-zero list pointers distinct from real COM objects. diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 5c269c7..410f97b 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1064,12 +1064,13 @@ impl State { } /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via - /// the 64 MiB ring staging buffer (zero CPU stall on the common path). - unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) { + /// the 64 MiB ring staging buffer (zero CPU stall on the common path). Returns whether the + /// copies were submitted (false: no staging buffer, so the CPU view was not sent). + unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) -> bool { if runs.is_empty() { - return; + return false; } - let Some(p) = self.staging_ptr() else { return }; + let Some(p) = self.staging_ptr() else { return false }; let mut open_slot: Option = None; let mut last_wi: Option = None; for &(a, n) in runs { @@ -1122,6 +1123,78 @@ impl State { if let Some(slot_idx) = open_slot { self.submit_slot(slot_idx); } + true + } +} + +/// The runs of `[va, va + len)` a sparse window has video memory for (mapped tiles, no hole +/// pages), rounded out to whole 64-byte chunks inside each page so that the hashes recorded for +/// them match what an upload of them sends. +fn video_runs(s: &State, va: usize, len: usize) -> Vec<(usize, usize)> { + let mut runs: Vec<(usize, usize)> = Vec::new(); + let end = va.saturating_add(len); + let mut at = va; + while at < end { + let t = at & !(TILE - 1); + let tile_end = (t + TILE).min(end); + if !s.mapped.contains_key(&t) { + at = tile_end; + continue; + } + let mut pg = at & !(PAGE - 1); + while pg < tile_end { + let idx = (pg - t) / PAGE; + if s.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { + let lo = at.max(pg) & !(CHUNK - 1); + let hi = (tile_end.min(pg + PAGE) + CHUNK - 1) & !(CHUNK - 1); + if hi > lo { + push_run(&mut runs, lo, hi - lo); + } + } + pg += PAGE; + } + at = tile_end; + } + runs +} + +/// Whether every page of `[va, va + len)` in a sparse window has video memory, so that a GPU +/// copy reaches it. +pub fn has_video_memory(va: usize, len: usize) -> bool { + if len == 0 { + return false; + } + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return false }; + if s.window_index(va).is_none() || va.checked_add(len - 1).is_none_or(|e| s.window_index(e).is_none()) { + return false; + } + let mut covered = 0usize; + for &(a, n) in &video_runs(s, va, len) { + let lo = a.max(va); + let hi = (a + n).min(va + len); + covered += hi.saturating_sub(lo); + } + covered >= len +} + +/// After the CPU wrote `[va, va + len)` there (a copy ordered after the queue's earlier work): +/// send the bytes to the video memory of the sparse window's committed tiles now, and make the +/// title queues wait for them before their next work (`before_execute` waits on the uploads). +/// Hole pages and tiles without video memory are skipped: there is nothing there to reach. +pub unsafe fn flush_written(va: usize, len: usize) { + if len == 0 { + return; + } + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + let runs = video_runs(s, va, len); + let Some(last) = runs.last() else { return }; + let sent_to = last.0 + last.1; + // the bytes that go now must not look unwritten to the next `before_execute` + if s.upload_dirty(&runs) { + s.sync_sent_range(va, sent_to.saturating_sub(va)); + s.signal(); } } diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 76f0653..fafa8fd 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -788,6 +788,41 @@ unsafe fn snapshot_page_array(ptr: u64, offset: u16, byte_len: u32) -> Result Vec { + let mut pages = snapshot.to_vec(); + if !pages.contains(&0) { + return pages; + } + let bytes = pages.len() * std::mem::size_of::(); + let deadline = std::time::Instant::now() + std::time::Duration::from_millis(LATE_PAGE_WAIT_MS); + loop { + if crate::gpu::shader::readable(r.destination as usize, bytes) { + for (k, page) in pages.iter_mut().enumerate() { + if *page == 0 { + *page = (r.destination as *const usize).add(k).read_unaligned(); + } + } + } + if !pages.contains(&0) || std::time::Instant::now() >= deadline { + return pages; + } + std::thread::sleep(std::time::Duration::from_micros(100)); + } +} + /// Whether `n` bytes at `p` are committed, writable memory. fn writable(p: usize, n: usize) -> bool { let Some(end) = p.checked_add(n) else { return false }; @@ -908,20 +943,9 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us let payload = if bc != 0 { bcpack_unpack(r, &stage1, n)? } else { stage1 }; if r.dest_physical_pages() { - let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?; - // A page number of 0 in the snapshot taken at enqueue (no page has it): the entry is - // read again now. A retail title keeps its page arrays in its own tables and fills an - // entry after EnqueueRequest – its streaming requests were refused by the thousand - // with page 0. An array that had its pages at enqueue stays as it was snapshotted - // (titles also pass arrays on the stack). - let late: Vec; - let pages = if pages.contains(&0) && crate::gpu::shader::readable(r.destination as usize, std::mem::size_of_val(pages)) { - late = (0..pages.len()).map(|k| if pages[k] != 0 { pages[k] } else { (r.destination as *const usize).add(k).read_unaligned() }).collect(); - &late[..] - } else { - pages - }; - if !crate::hle::kernelx::write_physical_pages(pages, r.destination_page_offset as usize, &payload[..n]) { + let snapshot = dest_pages.ok_or(E_ACCESS_VIOLATION)?; + let pages = destination_pages_at_turn(r, snapshot); + if !crate::hle::kernelx::write_physical_pages(&pages, r.destination_page_offset as usize, &payload[..n]) { return Err(E_ACCESS_VIOLATION); } } else if n > 0 { @@ -2038,6 +2062,82 @@ mod tests { } } + /// A destination page array whose entry is still 0 when the request is submitted, filled a + /// moment later from the title's own thread: the request waits for the page instead of + /// failing (a retail title's streaming table). + #[test] + fn a_destination_page_filled_in_after_submit() { + use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; + if crate::gpu::uma::get().is_none() { + return; + } + unsafe { + let mut count = 1usize; + let mut pages = [0usize; 1]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, pages.as_mut_ptr()), 1); + + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(3)); + let create_status: unsafe extern "system" fn(*mut c_void, u32, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(5)); + let mut desc = [0u8; 0x18]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); + desc[8..10].copy_from_slice(&16u16.to_le_bytes()); + desc[10] = 2; + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue(f, desc.as_ptr(), &IID_QUEUE, &mut q), S_OK); + let mut s = std::ptr::null_mut(); + assert_eq!(create_status(f, 2, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); + let qv = *(q as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, *const u8) = std::mem::transmute(*qv.add(3)); + let status: unsafe extern "system" fn(*mut c_void, *mut c_void, u32) = std::mem::transmute(*qv.add(4)); + let submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + let sv = *(s as *const *const usize); + let complete: unsafe extern "system" fn(*mut c_void, u32) -> bool = std::mem::transmute(*sv.add(3)); + let hresult: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT = std::mem::transmute(*sv.add(4)); + + // where the page can be read back: mapped into a reservation + let reserved = windows_sys::Win32::System::Memory::VirtualAlloc( + std::ptr::null(), + PHYS_PAGE_SIZE, + windows_sys::Win32::System::Memory::MEM_RESERVE, + windows_sys::Win32::System::Memory::PAGE_READWRITE, + ); + assert!(!reserved.is_null()); + assert_eq!(MapTitlePhysicalPages(reserved, 1, 0, 4, pages.as_mut_ptr()), reserved); + + let data: Vec = (0..0x800u32).map(|i| (i * 29 + 11) as u8).collect(); + let table = Box::new([0usize]); + let cell = table.as_ptr() as usize; + enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, cell as u64, 0, data.len() as u32, data.as_ptr() as u64, 0, data.len() as u32, 0, 0).as_ptr()); + status(q, s, 0); + submit(q); + // the title's own thread fills the entry a moment after Submit (its table was 0 here) + let page = pages[0]; + let filler = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(1)); + unsafe { std::ptr::write_volatile(cell as *mut usize, page) }; + }); + + let t = std::time::Instant::now(); + while !complete(s, 0) && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + filler.join().unwrap(); + assert_eq!(hresult(s, 0), S_OK, "the request waits for the page instead of failing"); + let got = std::slice::from_raw_parts(reserved as *const u8, data.len()); + assert_eq!(got, &data[..], "the bytes land in the page filled in after Submit"); + + MapTitlePhysicalPages(reserved, 1, 0, 4, std::ptr::null_mut()); + windows_sys::Win32::System::Memory::VirtualFree(reserved, 0, windows_sys::Win32::System::Memory::MEM_RELEASE); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr()), 1); + queue_close(q); + queue_release(q); + status_release(s); + } + } + #[test] fn physical_page_destinations_and_sources() { use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; @@ -2306,10 +2406,11 @@ mod tests { assert_eq!((s["BC7"].requests, s["BC7"].with_zlib, s["BC7"].destination_bytes), (3, 1, 0x30000)); assert_eq!((s["BC3"].requests, s["BC3"].with_zlib, s["BC3"].destination_bytes), (1, 0, 0x8000)); assert_eq!(counts.summary(), "BC3 1 (32768 bytes), BC7 3 (196608 bytes)"); - // every mode without a block rebuild; BC1 has one (in the tests, with their tables) + // every mode without a block rebuild; BC1 and BC5 have one (in the tests, with their + // tables) for m in 1..=15u64 { let r = Request::parse(&request(SOURCE_MEMORY_BIT | m << BCPACK_SHIFT, 0x1000, 64, 0x2000, 0, 20)); - assert_eq!(r.check(true), if m == 1 { Ok(()) } else { Err(E_DECOMPRESSION) }, "mode {m}"); + assert_eq!(r.check(true), if m == 1 || m == 5 { Ok(()) } else { Err(E_DECOMPRESSION) }, "mode {m}"); } } @@ -2386,6 +2487,25 @@ mod tests { let after = stats().bcpack_unpacked["BC1"].clone(); assert!(after.requests >= before.requests + 3 && after.destination_bytes >= before.destination_bytes + 0x20000 + small_blocks.len() as u64); assert!(after.failed >= before.failed + 2); + + // BC5 takes the same path: the fixture to the blocks the decoder builds from it + let bc5 = SOURCE_MEMORY_BIT | 5 << BCPACK_SHIFT; + let packed5 = fx::data("bc5-16-1.bin").unwrap(); + let blocks5 = crate::hle::bcpack::decode(5, &packed5, 8 * 16).unwrap(); + let before5 = stats().bcpack_unpacked.get("BC5").cloned().unwrap_or_default(); + let mut dst5 = vec![0xCDu8; blocks5.len() + 32]; + enqueue(q, request_ex(bc5, dst5.as_mut_ptr() as u64, 0, blocks5.len() as u32, packed5.as_ptr() as u64, 0, packed5.len() as u32, 0, 0).as_ptr()); + status(q, s, 7); + submit(q); + while !complete(s, 7) && t.elapsed().as_secs() < 10 { + std::thread::yield_now(); + } + assert_eq!(hresult(s, 7), S_OK, "BC5 request"); + assert_eq!(&dst5[..blocks5.len()], &blocks5[..], "BC5: the destination has the blocks"); + assert!(dst5[blocks5.len()..].iter().all(|&b| b == 0xCD), "BC5: nothing past the destination size"); + let after5 = stats().bcpack_unpacked["BC5"].clone(); + assert!(after5.requests > before5.requests && after5.destination_bytes >= before5.destination_bytes + blocks5.len() as u64); + queue_close(q); queue_release(q); status_release(s); diff --git a/scripts/gen_bcpack_bc5_tables.py b/scripts/gen_bcpack_bc5_tables.py new file mode 100644 index 0000000..4e63b22 --- /dev/null +++ b/scripts/gen_bcpack_bc5_tables.py @@ -0,0 +1,90 @@ +"""Generate crates/xcl/src/hle/bcpack/bc5_tables.rs from the BC5 tables the clean-room decoder of +leonida-asset-pipeline publishes (wxrrry, MIT): the order of the 64 index-pair symbols and the +endpoint history a BCPack BC5 stream starts with. Neither is in a stream or in a public +specification; the history was fitted against retail streams (see the source's README for how, +and its note that only three slots are confirmed; the rest are its estimates). + +usage: python scripts/gen_bcpack_bc5_tables.py /tools/bcpack_tables.py +(https://github.com/wxrrry/leonida-asset-pipeline, tools/bcpack_tables.py)""" +import ast, io, os, sys + +TABLES = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'crates', 'xcl', 'src', 'hle', 'bcpack', 'bc5_tables.rs') +WANT = ('BC5_PAIR', 'BC5_HISTORY_CONFIRMED', 'BC5_HISTORY_PROVISIONAL') + +tree = ast.parse(io.open(sys.argv[1], encoding='utf-8').read()) +found = {} +for node in tree.body: + if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): + if node.targets[0].id in WANT: + found[node.targets[0].id] = ast.literal_eval(node.value) +assert set(found) == set(WANT), sorted(found) + +pairs = found['BC5_PAIR'] +assert len(pairs) == 64 and sorted(tuple(p) for p in pairs) == [(a, b) for a in range(8) for b in range(8)], 'not a permutation' +assert all(0 <= x < 8 for p in pairs for x in p) + +# slot -> (channel 0 e0, channel 0 e1, channel 1 e0, channel 1 e1); slot 0 is never read +slots = [None] * 256 +for table in ('BC5_HISTORY_CONFIRMED', 'BC5_HISTORY_PROVISIONAL'): + for slot, v in found[table].items(): + assert 1 <= slot <= 255 and len(v) == 4 and all(0 <= c < 256 for c in v), (table, slot, v) + if slots[slot] is not None: + assert tuple(slots[slot]) == tuple(v), ('the two tables disagree on slot', slot) + slots[slot] = tuple(v) +unknown = [s for s in range(1, 256) if slots[s] is None] + +out = io.open(TABLES, 'w', encoding='utf-8', newline='\n') +out.write(f'''// Generated by scripts/gen_bcpack_bc5_tables.py from the BC5 tables of leonida-asset-pipeline +// by wxrrry (https://github.com/wxrrry/leonida-asset-pipeline, tools/bcpack_tables.py), used +// under its MIT license: +// +// MIT License +// +// Copyright (c) 2026 wxrrry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// The constants of BCPack's BC5 block rebuild that no stream carries. The history was fitted +// from retail data (decoded blocks against the next smaller mip level, which is stored +// unpacked); it is a constant of the codec, not game content. Only slots 182, 183 and 222 are +// reported as confirmed by the source; the other {255 - len(unknown)} are its estimates, and being estimates +// they make the BC5 output of XCL an approximation wherever one is off: +// * history: {255 - len(unknown)} of the 255 entries that can be read; the `None` ones ({", ".join(map(str, unknown))}) +// were never referred to in the data of the fit. +// A block rebuilt from a history entry carries its error, and so do the blocks that refer to it. + +use super::bc5::Tables; + +pub static TABLES: Tables = Tables {{ + pairs: PAIRS, + preset: PRESET, +}}; + +/// Index symbol -> the two 3-bit indices it codes, the first pixel then the second. +static PAIRS: [(u8, u8); 64] = [ +''') +for k in range(0, 64, 8): + row = ', '.join(f'({a}, {b})' for a, b in pairs[k:k + 8]) + out.write(f' {row},\n') +out.write('];\n\n/// Endpoint history: `[channel 0 e0, channel 0 e1, channel 1 e0, channel 1 e1]` per slot.\nstatic PRESET: [Option<[u8; 4]>; 256] = [\n') +for s in range(256): + out.write(f' {"None" if slots[s] is None else "Some([%d, %d, %d, %d])" % slots[s]}, // {s}\n') +out.write('];\n') +out.close() +print(f'wrote {os.path.normpath(TABLES)}: 64 pairs, {255 - len(unknown)} of 255 history slots')