diff --git a/HANDOFF.md b/HANDOFF.md index d0a01a7..118948d 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1820,7 +1820,9 @@ right after its first `CreateShaderResourceView` (the first descriptor written i the Zen 2 instructions such a CPU lacks – `clwb` (Intel: Ice Lake+), `clzero`, `rdpru`, `monitorx` / `mwaitx` (AMD only), `rdpid` – and the vectored handler (`eh::emulate_console_only`) emulates them and steps over (`clwb` / `monitorx` / `mwaitx`: nothing, the PC's memory is coherent; `clzero`: 64 zero bytes at rAX; `rdpru`: -QueryPerformanceCounter; `rdpid`: the processor number). Logged once per instruction. Any other illegal instruction +QueryPerformanceCounter; `rdpid`: the processor number). SSE4a (AMD only): `extrq` / `insertq` on the exception's +XMM registers, `movntss` / `movntsd` as a plain store of the low dword / quadword (fs / gs-relative ones are not +emulated). Logged once per instruction. Any other illegal instruction (and `ud2`, a title's own trap) is logged with its 16 code bytes, in the first-chance handler and in the crash line. SHA-NI is not emulated (also missing on those CPUs): add it if a title's code bytes show `0F 38 C8..CD`. diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 4afc9f2..fd42e6a 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -10,6 +10,9 @@ carry a note in their header about its origin and the date of changes (GPL-2.0 | [FFmpeg](https://ffmpeg.org/) | LGPL-2.1+ | XMA1/XMA2 decoder and tables (`crates/xcl/src/hle/xma2/`) – after `libavcodec/wmaprodec.c`, `wmaprodata.h`, `wma.c`, `sinewin_tablegen.h`, `libavutil/float_dsp.c`, `tx_template.c` | port to safe Rust with annotation | | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [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 | +| 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) | | [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/config.rs b/crates/xcl/src/config.rs index 1503e55..be453ec 100644 --- a/crates/xcl/src/config.rs +++ b/crates/xcl/src/config.rs @@ -87,7 +87,7 @@ impl Config { if let Some(m) = &m { from.push(format!("title memory {m}")); } - self.title_memory = m.unwrap_or_else(|| "standard".into()).to_ascii_lowercase(); + self.title_memory = m.unwrap_or_else(|| "standard".into()).trim().to_ascii_lowercase(); } // the standard budgets; "advanced" adds memory the console docs do not give publicly – // the standard figure stays (xcl.toml can raise it) @@ -220,8 +220,7 @@ impl Config { } // only a missing file gets the defaults written: an unreadable one (locked, not UTF-8) // must not be replaced by them (issue #106) - Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(format!("{}: {e}", path.display())), - Err(_) => { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { let c = Config::default(); let body = toml::to_string_pretty(&c).map_err(|e| e.to_string())?; if let Some(d) = path.parent() { @@ -230,6 +229,7 @@ impl Config { let _ = std::fs::write(path, format!("{HEADER}{body}")); Ok(c) } + Err(e) => Err(format!("{}: {e}", path.display())), } } @@ -355,14 +355,65 @@ mod tests { #[test] fn title_memory_is_read_in_any_case() { - let manifest = crate::manifest::Manifest { anaconda_memory: Some("Advanced".into()), ..Default::default() }; - for (setting, m) in [("Auto", Some(&manifest)), ("ADVANCED", None)] { + let manifest_adv = crate::manifest::Manifest { anaconda_memory: Some("Advanced".into()), ..Default::default() }; + let manifest_std = crate::manifest::Manifest { anaconda_memory: Some("Standard".into()), ..Default::default() }; + for (setting, m, expected_mode, expected_uma) in [ + ("auto", Some(&manifest_adv), "advanced", 4095), + ("Auto", Some(&manifest_adv), "advanced", 4095), + ("AUTO", Some(&manifest_adv), "advanced", 4095), + (" aUtO ", Some(&manifest_adv), "advanced", 4095), + ("auto", Some(&manifest_std), "standard", 2048), + ("Auto", None, "standard", 2048), + ("advanced", None, "advanced", 4095), + ("Advanced", None, "advanced", 4095), + ("ADVANCED", None, "advanced", 4095), + (" AdVaNcEd ", None, "advanced", 4095), + ("standard", None, "standard", 2048), + ("Standard", None, "standard", 2048), + ] { let mut c = Config { title_memory: setting.into(), ..Config::default() }; c.resolve(m); - assert_eq!((c.title_memory.as_str(), c.uma_mb), ("advanced", 4095), "{setting}"); + assert_eq!( + (c.title_memory.as_str(), c.uma_mb), + (expected_mode, expected_uma), + "failed for setting {setting:?}" + ); } } + #[test] + fn load_or_create_only_creates_on_not_found_and_preserves_on_errors() { + let dir = std::env::temp_dir().join(format!("xcl_cfg_robustness_{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("xcl.toml"); + + // 1. Missing file: creates default xcl.toml + if path.exists() { + let _ = std::fs::remove_file(&path); + } + let created = Config::load_or_create(&path).expect("creates when missing"); + assert_eq!(created.device_type, "anaconda"); + assert!(path.exists()); + let original_content = std::fs::read_to_string(&path).unwrap(); + assert!(original_content.starts_with("# XCL")); + + // 2. Corrupted TOML (syntax error): fails and does NOT overwrite file + let corrupted_toml = "device_type = [invalid toml syntax"; + std::fs::write(&path, corrupted_toml).unwrap(); + let res = Config::load_or_create(&path); + assert!(res.is_err()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), corrupted_toml); + + // 3. Unreadable / Invalid UTF-8 data: fails and does NOT overwrite file + let invalid_utf8 = [0xFF, 0xFE, 0xFD, 0xFC]; + std::fs::write(&path, &invalid_utf8).unwrap(); + let res = Config::load_or_create(&path); + assert!(res.is_err()); + assert_eq!(std::fs::read(&path).unwrap(), invalid_utf8); + + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn raytracing_tier_parsing() { assert_eq!(parse_raytracing_tier("auto"), None); diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index fca2999..f065bc1 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -370,6 +370,22 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics d.Low = crate::insn::insertq(d.Low, s.Low, len, idx); d.High = 0; } + ConsoleOnly::Movnts { bytes, src, mem } => { + let regs = [ + ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, + ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15, + ]; + let at = crate::insn::address(&mem, ®s, ctx.Rip + len as u64) as usize; + if !crate::gpu::shader::readable(at, bytes as usize) { + return 0; // the real store faults there too + } + let v = ctx.Anonymous.FltSave.XmmRegisters[src as usize & 15].Low; + if bytes == 8 { + (at as *mut u64).write_unaligned(v); + } else { + (at as *mut u32).write_unaligned(v as u32); + } + } } ctx.Rip += len as u64; -1 // EXCEPTION_CONTINUE_EXECUTION @@ -556,14 +572,46 @@ unsafe fn name_thread(tid: u32, name: &[u16]) { } } +/// Bytes of a thread's stack (from RSP up) a thread dump keeps +const DUMP_STACK: usize = 0x4_0000; + +/// The stack from `rsp` up (to the end of its region, at most `buf.len()` bytes) copied to +/// `buf`: its length. Only system calls – no lock a suspended thread may hold. +unsafe fn copy_stack(rsp: u64, buf: &mut [u8]) -> Option { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let mut mbi: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(rsp as *const c_void, &mut mbi, std::mem::size_of::()) == 0 || mbi.State != MEM_COMMIT { + return None; + } + let n = (mbi.BaseAddress as usize + mbi.RegionSize).saturating_sub(rsp as usize).min(buf.len()); + let mut read = 0usize; + let cur = windows_sys::Win32::System::Threading::GetCurrentProcess(); + (n >= 8 && ReadProcessMemory(cur, rsp as *const c_void, buf.as_mut_ptr() as *mut c_void, n, &mut read) != 0 && read == n).then_some(n) +} + /// The return addresses of the frames from `ctx` on (its RIP first), unwound with the -/// functions' unwind data (registered for the title's images too); up to `n`. -unsafe fn unwind(ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, n: usize) -> Vec { +/// functions' unwind data (registered for the title's images too); up to `n`. `stack` is the +/// thread's stack from `ctx.Rsp` on, copied while it was stopped: the thread has gone on (or +/// ended) since, so the unwinding reads the copy – addresses into the stack are moved to it – +/// and ends where a frame would leave it. +unsafe fn unwind(ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, n: usize, stack: &[u8]) -> Vec { use windows_sys::Win32::System::Diagnostics::Debug::{RtlLookupFunctionEntry, RtlVirtualUnwind, UNW_FLAG_NHANDLER}; + let (orig, copy, len) = (ctx.Rsp, stack.as_ptr() as u64, stack.len() as u64); + let in_copy = |v: u64| v >= copy && v < copy + len; + let to_copy = |ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT| { + for r in [&mut ctx.Rax, &mut ctx.Rcx, &mut ctx.Rdx, &mut ctx.Rbx, &mut ctx.Rsp, &mut ctx.Rbp, &mut ctx.Rsi, &mut ctx.Rdi, + &mut ctx.R8, &mut ctx.R9, &mut ctx.R10, &mut ctx.R11, &mut ctx.R12, &mut ctx.R13, &mut ctx.R14, &mut ctx.R15] { + if *r >= orig && *r < orig + len { + *r = *r - orig + copy; + } + } + }; + to_copy(ctx); let mut out = Vec::new(); for _ in 0..n { let rip = ctx.Rip; - if rip == 0 { + if rip == 0 || !in_copy(ctx.Rsp) || ctx.Rsp + 8 > copy + len { break; } out.push(rip as usize); @@ -571,16 +619,22 @@ unsafe fn unwind(ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTE let f = RtlLookupFunctionEntry(rip, &mut base, std::ptr::null_mut()); if f.is_null() { // a leaf function: the return address is at RSP - if !crate::gpu::shader::readable(ctx.Rsp as usize, 8) { - break; - } ctx.Rip = (ctx.Rsp as *const u64).read_unaligned(); ctx.Rsp += 8; } else { + // a frame register (UNWIND_INFO byte 3, low nibble) has to point into the copy too + let info = (base + (*f).Anonymous.UnwindData as u64) as *const u8; + let fp = (*info.add(3) & 0xF) as usize; + let regs = [ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15]; + if fp != 0 && !in_copy(regs[fp]) { + break; + } let mut data = std::ptr::null_mut(); let mut frame = 0u64; RtlVirtualUnwind(UNW_FLAG_NHANDLER, base, rip, f, ctx, &mut data, &mut frame, std::ptr::null_mut()); } + // registers restored from the copy hold addresses into the stack + to_copy(ctx); } out } @@ -599,6 +653,9 @@ pub fn dump_threads() { return; } let mut lines = Vec::new(); + // allocated before any thread is stopped: it may hold the heap's lock. (The slack past + // the copy: a frame's unwinding may read a little beyond where the copy ends.) + let mut stack = vec![0u8; DUMP_STACK + 0x1_0000]; let mut te: THREADENTRY32 = std::mem::zeroed(); te.dwSize = std::mem::size_of::() as u32; let mut ok = Thread32First(snap, &mut te) != 0; @@ -611,16 +668,18 @@ pub fn dump_threads() { struct Aligned(CONTEXT); let mut c: Aligned = std::mem::zeroed(); c.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64; - // only the context is taken while the thread is suspended: the unwinding - // (RtlLookupFunctionEntry), the module lookup (loader lock), the name and the - // formatting (heap) take locks the suspended thread may hold (#106) + // only the context and a copy of the stack are taken while the thread is + // suspended: the unwinding (RtlLookupFunctionEntry), the module lookup (loader + // lock), the name and the formatting (heap) take locks the suspended thread + // may hold (#106). The unwinding reads the copy: the thread goes on, or ends. + let mut len = 0; let got = SuspendThread(h) != u32::MAX && { - let ok = GetThreadContext(h, &mut c.0) != 0; + let ok = GetThreadContext(h, &mut c.0) != 0 && copy_stack(c.0.Rsp, &mut stack[..DUMP_STACK]).inspect(|&n| len = n).is_some(); ResumeThread(h); ok }; if got { - let frames: Vec = unwind(&mut c.0, 14).into_iter().map(modules::describe_address).collect(); + let frames: Vec = unwind(&mut c.0, 14, &stack[..len]).into_iter().map(modules::describe_address).collect(); lines.push(format!("thread {} '{}': {}", te.th32ThreadID, thread_name(h), frames.join(" < "))); } CloseHandle(h); @@ -912,6 +971,47 @@ pub fn start_probes() { mod tests { use super::*; + /// recursion whose frames hold return addresses and saved registers that change as it runs + #[inline(never)] + fn churn_stack(depth: u32, seed: u64) -> u64 { + let local = std::hint::black_box([seed; 8]); + if depth == 0 { + return local.iter().fold(0u64, |a, &x| a.wrapping_add(x)); + } + churn_stack(depth - 1, seed.wrapping_mul(6364136223846793005).wrapping_add(depth as u64)) ^ local[depth as usize % 8] + } + + /// Thread dumps while threads run, start and end around them (#106: a dump read a near-null + /// address inside RtlVirtualUnwind). + #[test] + fn thread_dumps_while_threads_run_and_exit() { + use std::sync::atomic::AtomicBool; + static STOP: AtomicBool = AtomicBool::new(false); + let busy: Vec<_> = (0..4u64) + .map(|i| std::thread::spawn(move || { + let mut n = 0u64; + while !STOP.load(Ordering::Relaxed) { + n = n.wrapping_add(churn_stack((n % 40) as u32 + 1, n ^ i)); + } + n + })) + .collect(); + let churn: Vec<_> = (0..4u64) + .map(|i| std::thread::spawn(move || { + let mut n = 0u64; + while !STOP.load(Ordering::Relaxed) { + n = std::thread::spawn(move || churn_stack((n % 24) as u32 + 1, n ^ i)).join().unwrap(); + } + })) + .collect(); + for _ in 0..40 { + dump_threads(); + } + STOP.store(true, Ordering::Relaxed); + churn.into_iter().for_each(|t| t.join().unwrap()); + busy.into_iter().for_each(|t| { t.join().unwrap(); }); + } + #[test] fn bounded_cstr_stops_at_nul_limit_and_unreadable_memory() { unsafe { @@ -971,4 +1071,58 @@ mod tests { } modules::unregister_mapped(code); } + + /// MOVNTSS / MOVNTSD in a title image: on a CPU without SSE4a (any Intel) they raise + /// STATUS_ILLEGAL_INSTRUCTION and the handler does the store; on an AMD CPU they run + /// natively. Either way the memory holds the same values. + #[test] + fn sse4a_streaming_stores_run_in_a_title_image() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE}; + // s(p, v): movq xmm0, rdx; movntsd [rcx], xmm0; ret + // t(p, v): movq xmm1, rdx; movntss [rcx+4], xmm1 (a SIB without an index); ret + // u(p, v): movq xmm2, rdx; movntsd [rip+disp32], xmm2 (into the page's last 8 bytes); ret + let s_code: &[u8] = &[0x66, 0x48, 0x0F, 0x6E, 0xC2, 0xF2, 0x0F, 0x2B, 0x01, 0xC3]; + let t_code: &[u8] = &[0x66, 0x48, 0x0F, 0x6E, 0xCA, 0xF3, 0x0F, 0x2B, 0x4C, 0x21, 0x04, 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(s_code.as_ptr(), page, s_code.len()); + std::ptr::copy_nonoverlapping(t_code.as_ptr(), page.add(32), t_code.len()); + // u at 64: the store's disp32 is relative to the end of the movntsd (64 + 5 + 8) + let disp = (4096 - 8 - (64 + 5 + 8)) as u32; + let mut u_code = vec![0x66, 0x48, 0x0F, 0x6E, 0xD2, 0xF2, 0x0F, 0x2B, 0x15]; + u_code.extend_from_slice(&disp.to_le_bytes()); + u_code.push(0xC3); + std::ptr::copy_nonoverlapping(u_code.as_ptr(), page.add(64), u_code.len()); + modules::register_mapped(std::sync::Arc::new(modules::MappedModule { + name: "sse4a_test.exe".into(), + path: "sse4a_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 s: extern "system" fn(*mut u64, u64) = std::mem::transmute(page); + let t: extern "system" fn(*mut u32, u64) = std::mem::transmute(page.add(32)); + let u: extern "system" fn(*mut u64, u64) = std::mem::transmute(page.add(64)); + let mut out = [0u64; 2]; + s(out.as_mut_ptr(), 0x0123_4567_89AB_CDEF); + assert_eq!(out[0], 0x0123_4567_89AB_CDEF, "movntsd stores the low quadword"); + let mut words = [0u32; 3]; + t(words.as_mut_ptr(), 0xFFFF_FFFF_DEAD_BEEF); + assert_eq!(words, [0, 0xDEAD_BEEF, 0], "movntss stores the low dword at [rcx+4] and nothing else"); + u(std::ptr::null_mut(), 0x1122_3344_5566_7788); + assert_eq!((page.add(4096 - 8) as *const u64).read_unaligned(), 0x1122_3344_5566_7788, "rip-relative movntsd"); + windows_sys::Win32::System::Diagnostics::Debug::RemoveVectoredExceptionHandler(veh); + modules::unregister_mapped(page as usize); + VirtualFree(page as _, 0, MEM_RELEASE); + } + } } diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 5a63c3c..0d6baa0 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -43,6 +43,9 @@ pub(super) struct Em { /// split wave64: pc → SGPRs whose whole value may be read after that instruction /// (`x64_masks`); a mask written to none of them stays in its half (no exchange) pub x64_whole_live: BTreeMap, + /// compute mode: the group is padded to whole console waves (`partial_waves`), the + /// padding lanes inactive at the start + pub cs_pad: bool, /// wave64 VS / PS on a GPU with 32-lane waves only: what the console's lanes 32..63 hold /// where the program reads them (`upper_lanes`), used when the wave has 32 lanes pub upper: Option, @@ -477,6 +480,7 @@ impl Em { uses_scratch: false, x64_words: 1, x64_whole_live: BTreeMap::new(), + cs_pad: false, upper: None, cur_pc: 0, static_ss: BTreeMap::new(), @@ -2175,11 +2179,33 @@ impl Em { let sampler = self.sampler_ref(d.pc, has_c, &s3); self.line(&format!("{samp} {t}_S = {sampler};")); if let Some(o) = &offset { - let level = match (&lod, has_lz || base.starts_with("gather4"), ps && grads.is_none() && !has_c) { - (_, true, _) => "0u".to_string(), - (Some(l), _, _) => format!("(uint)max(round({l}), 0.0f)"), - (None, _, true) => format!("(uint)max(round({t}_T.CalculateLevelOfDetail({t}_S, {coord0})), 0.0f)"), - _ => "0u".to_string(), + // the mip the console reads: the given LOD, else that of the given gradients or the + // pixel's own (none outside PS), plus the bias + let level = if has_lz || base.starts_with("gather4") { + "0u".to_string() + } else if let Some(l) = &lod { + format!("(uint)max(round({l}), 0.0f)") + } else if grads.is_none() && bias.is_none() && !(ps && has_c) { + if ps { format!("(uint)max(round({t}_T.CalculateLevelOfDetail({t}_S, {coord0})), 0.0f)") } else { "0u".to_string() } + } else { + // mip 0's size for the gradients' LOD, and the view's levels: a bias can pass the last + self.texel_offset(&t, dim, o, "0u", "0"); + let size = [format!("{t}_w0"), format!("{t}_h0"), format!("{t}_d0")]; + let len = |x: &[String]| format!("length(float{}({}))", x.len(), x.iter().zip(&size).map(|(a, w)| format!("{a} * (float){w}")).collect::>().join(", ")); + let grad_lod = |dx: &[String], dy: &[String]| format!("log2(max(max({}, {}), 1e-8f))", len(dx), len(dy)); + // CalculateLevelOfDetail takes no comparison sampler: the screen derivatives + let screen = |op: &str| (0..[1, 2, 3, 3, 1, 2][dim as usize]).map(|k| format!("{op}({})", coords_unmoved[k])).collect::>(); + let l = match &grads { + Some((dx, dy)) => grad_lod(dx, dy), + None if ps && has_c => grad_lod(&screen("ddx"), &screen("ddy")), + None if ps => format!("{t}_T.CalculateLevelOfDetail({t}_S, {coord0})"), + None => "0.0f".to_string(), + }; + let l = match &bias { + Some(b) => format!("{l} + {b}"), + None => l, + }; + format!("min((uint)max(round({l}), 0.0f), max({t}_n0, 1u) - 1u)") }; self.texel_offset(&t, dim, o, &level, ""); } @@ -2682,10 +2708,11 @@ impl Em { // integer clamp saturates each half "v_pk_add_u16" if clamp => format!("min({a} + {b}, 0xFFFFu)"), "v_pk_sub_u16" if clamp => format!("select({a} < {b}, 0u, {a} - {b})"), - "v_pk_add_i16" if clamp => format!("((uint)clamp({} + {}, -32768, 32767) & 0xFFFFu)", si(0, hi), si(1, hi)), - "v_pk_sub_i16" if clamp => format!("((uint)clamp({} - {}, -32768, 32767) & 0xFFFFu)", si(0, hi), si(1, hi)), + "v_pk_add_i16" if clamp => format!("sat_i16({} + {})", si(0, hi), si(1, hi)), + "v_pk_sub_i16" if clamp => format!("sat_i16({} - {})", si(0, hi), si(1, hi)), + "v_pk_mul_lo_u16" if clamp => format!("min({a} * {b}, 0xFFFFu)"), "v_pk_mad_u16" if clamp => format!("min({a} * {b} + {c}, 0xFFFFu)"), - "v_pk_mad_i16" if clamp => format!("((uint)clamp({} * {} + {}, -32768, 32767) & 0xFFFFu)", si(0, hi), si(1, hi), si(2, hi)), + "v_pk_mad_i16" if clamp => format!("sat_i16({} * {} + {})", si(0, hi), si(1, hi), si(2, hi)), "v_pk_add_u16" => format!("(({a} + {b}) & 0xFFFFu)"), "v_pk_sub_u16" => format!("(({a} - {b}) & 0xFFFFu)"), "v_pk_add_i16" => format!("((uint)({} + {}) & 0xFFFFu)", si(0, hi), si(1, hi)), @@ -2903,15 +2930,21 @@ impl Em { "v_cvt_f16_u16" => fr(format!("(float){a}")), "v_cvt_f16_i16" => fr(format!("(float){}", si(0))), "v_cvt_u16_f16" => format!("(cvt_u32({}) > 0xFFFFu ? 0xFFFFu : cvt_u32({}))", fh(0), fh(0)), - "v_cvt_i16_f16" => format!("((uint)clamp(cvt_i32({}), -32768, 32767) & 0xFFFFu)", fh(0)), + "v_cvt_i16_f16" => format!("sat_i16(cvt_i32({}))", fh(0)), // f16 → unorm16 / snorm16: exact RNE on raw binary16 bits (avoids fp32 double-rounding & clamp(NaN)) "v_cvt_norm_u16_f16" => format!("cvt_norm_u16_f16({})", hb(0)), "v_cvt_norm_i16_f16" => format!("cvt_norm_i16_f16({})", hb(0)), + "v_add_nc_u16" | "v_add_u16" if m.clamp => format!("min({a} + {b}, 0xFFFFu)"), + "v_sub_nc_u16" | "v_sub_u16" if m.clamp => format!("select({a} < {b}, 0u, {a} - {b})"), + "v_subrev_nc_u16" | "v_subrev_u16" if m.clamp => format!("select({b} < {a}, 0u, {b} - {a})"), + "v_add_nc_i16" if m.clamp => format!("sat_i16({} + {})", si(0), si(1)), + "v_sub_nc_i16" if m.clamp => format!("sat_i16({} - {})", si(0), si(1)), "v_add_nc_u16" | "v_add_u16" => format!("(({a} + {b}) & 0xFFFFu)"), "v_sub_nc_u16" | "v_sub_u16" => format!("(({a} - {b}) & 0xFFFFu)"), "v_subrev_nc_u16" | "v_subrev_u16" => format!("(({b} - {a}) & 0xFFFFu)"), "v_add_nc_i16" => format!("((uint)({} + {}) & 0xFFFFu)", si(0), si(1)), "v_sub_nc_i16" => format!("((uint)({} - {}) & 0xFFFFu)", si(0), si(1)), + "v_mul_lo_u16" if m.clamp => format!("min({a} * {b}, 0xFFFFu)"), "v_mul_lo_u16" => format!("(({a} * {b}) & 0xFFFFu)"), "v_lshlrev_b16" => format!("(({b} << ({a} & 15u)) & 0xFFFFu)"), "v_lshrrev_b16" => format!("({b} >> ({a} & 15u))"), @@ -2920,6 +2953,8 @@ impl Em { "v_min_u16" => format!("min({a}, {b})"), "v_max_i16" => format!("((uint)max({}, {}) & 0xFFFFu)", si(0), si(1)), "v_min_i16" => format!("((uint)min({}, {}) & 0xFFFFu)", si(0), si(1)), + "v_mad_u16" if m.clamp => format!("min({a} * {b} + {c}, 0xFFFFu)"), + "v_mad_i16" if m.clamp => format!("sat_i16({} * {} + {})", si(0), si(1), si(2)), "v_mad_u16" => format!("(({a} * {b} + {c}) & 0xFFFFu)"), "v_mad_i16" => format!("((uint)({} * {} + {}) & 0xFFFFu)", si(0), si(1), si(2)), _ => return Err("VALU 16-bit"), @@ -3005,16 +3040,42 @@ impl Em { "v_lshrrev_b64" => format!("({} >> ({} & 63u))", u64v(1), lo_hi[0].0), "v_ashrrev_i64" => format!("(uint64_t)((int64_t){} >> ({} & 63u))", u64v(1), lo_hi[0].0), "v_mad_u64_u32" | "v_mad_i64_i32" => { - let p = if name == "v_mad_u64_u32" { - format!("((uint64_t){} * (uint64_t){})", lo_hi[0].0, lo_hi[1].0) - } else { + let signed = name == "v_mad_i64_i32"; + let p = if signed { format!("(uint64_t)((int64_t)(int){} * (int64_t)(int){})", lo_hi[0].0, lo_hi[1].0) + } else { + format!("((uint64_t){} * (uint64_t){})", lo_hi[0].0, lo_hi[1].0) }; self.line(&format!("uint64_t {t}_p = {p}; uint64_t {t}_c = {};", u64v(2))); - self.line(&format!("uint64_t {t}_w = {t}_p + {t}_c;")); + self.line(&format!("uint64_t {t}_w = {t}_p + {t}_c; bool {t}_ov = {t}_w < {t}_c;")); let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::Null); - self.write_mask(&sdst, &format!("{t}_w < {t}_c")); - self.write64(&dst, &format!("(uint){t}_w"), &format!("(uint)({t}_w >> 32)")); + if signed { + // RDNA2 ISA: { D1.i1, D0.i64 } = 65'I(S0.i32) * 65'I(S1.i32) + 65'I(S2.i64). + // Since p fits in signed 64 bits ([-2^62 + 2^31, 2^62]), bit 64 of the 65-bit + // signed sum is sign(p) ^ sign(c) ^ carry_out, and signed overflow occurs iff + // bit 64 differs from bit 63. + self.line(&format!("bool {t}_s64 = ((({t}_p ^ {t}_c) >> 63) ^ select({t}_ov, 1ull, 0ull)) != 0ull;")); + self.write_mask(&sdst, &format!("{t}_s64")); + } else { + self.write_mask(&sdst, &format!("{t}_ov")); + } + if !m.clamp { + self.write64(&dst, &format!("(uint){t}_w"), &format!("(uint)({t}_w >> 32)")); + } else if !signed { + self.write64( + &dst, + &format!("select({t}_ov, 0xFFFFFFFFu, (uint){t}_w)"), + &format!("select({t}_ov, 0xFFFFFFFFu, (uint)({t}_w >> 32))"), + ); + } else { + self.line(&format!("bool {t}_w63 = ({t}_w >> 63) != 0ull;")); + self.line(&format!("bool {t}_pos = and(!{t}_s64, {t}_w63); bool {t}_neg = and({t}_s64, !{t}_w63);")); + self.write64( + &dst, + &format!("select({t}_pos, 0xFFFFFFFFu, select({t}_neg, 0u, (uint){t}_w))"), + &format!("select({t}_pos, 0x7FFFFFFFu, select({t}_neg, 0x80000000u, (uint)({t}_w >> 32)))"), + ); + } return Ok(()); } _ => { @@ -3063,7 +3124,7 @@ impl Em { } _ => return Err("VALU 64-bit"), }; - // omod, then clamp (DXIL has a double saturate) + // omod, then clamp (clamp to [0.0, 1.0] since HLSL SM 6.6 has no double saturate overload) let mut e = match m.omod { 1 => format!("(({e}) * 2.0)"), 2 => format!("(({e}) * 4.0)"), @@ -3071,7 +3132,7 @@ impl Em { _ => e, }; if m.clamp { - e = format!("saturate({e})"); + e = format!("clamp({e}, 0.0, 1.0)"); } self.line(&format!("double {t}_d = {e}; uint {t}_l, {t}_h; asuint({t}_d, {t}_l, {t}_h);")); self.write64(&dst, &format!("{t}_l"), &format!("{t}_h")); @@ -3181,6 +3242,7 @@ impl Em { format!("({cur} & 0xFFFF0000u) | {h}") } } + // OMOD and VOP3 CLAMP are not applied to the packed f16x2 result on RDNA2 (Mesa ACO b63aa2bb8e) "v_cvt_pkrtz_f16_f32" => format!("f16_rtz({}) | (f16_rtz({}) << 16)", fs(0), fs(1)), "v_pack_b32_f16" => { let lo = if m.opsel & 1 == 1 { format!("({a} >> 16)") } else { format!("({a} & 0xFFFFu)") }; @@ -3269,6 +3331,10 @@ impl Em { "v_mul_lo_u32" => format!("{a} * {b}"), "v_mul_hi_u32" => format!("mul_hi_u32({a}, {b})"), "v_mul_hi_i32" => format!("(uint)(((int64_t)(int){a} * (int64_t)(int){b}) >> 32)"), + "v_mul_u32_u24" if m.clamp => format!("sat_u32((uint64_t)({a} & 0xFFFFFFu) * (uint64_t)({b} & 0xFFFFFFu))"), + "v_mul_i32_i24" if m.clamp => format!("sat_i32((int64_t)i24({a}) * (int64_t)i24({b}))"), + "v_mad_u32_u24" if m.clamp => format!("sat_u32((uint64_t)({a} & 0xFFFFFFu) * (uint64_t)({b} & 0xFFFFFFu) + (uint64_t){c})"), + "v_mad_i32_i24" if m.clamp => format!("sat_i32((int64_t)i24({a}) * (int64_t)i24({b}) + (int64_t)(int){c})"), "v_mul_u32_u24" => format!("({a} & 0xFFFFFFu) * ({b} & 0xFFFFFFu)"), "v_mul_hi_u32_u24" => format!("(uint)(((uint64_t)({a} & 0xFFFFFFu) * (uint64_t)({b} & 0xFFFFFFu)) >> 32)"), "v_mul_i32_i24" => format!("(uint)(i24({a}) * i24({b}))"), @@ -3308,6 +3374,11 @@ impl Em { "v_min3_i32" => format!("(uint)min(min((int){a}, (int){b}), (int){c})"), "v_max3_i32" => format!("(uint)max(max((int){a}, (int){b}), (int){c})"), "v_med3_i32" => format!("(uint)med3i((int){a}, (int){b}, (int){c})"), + "v_sad_u32" if m.clamp => format!("sat_u32((uint64_t)(max({a}, {b}) - min({a}, {b})) + (uint64_t){c})"), + "v_sad_u8" if m.clamp => format!("sat_u32((uint64_t)sad_u8({a}, {b}) + (uint64_t){c})"), + "v_sad_hi_u8" if m.clamp => format!("sat_u32((uint64_t)(sad_u8({a}, {b}) << 16) + (uint64_t){c})"), + "v_sad_u16" if m.clamp => format!("sat_u32((uint64_t)(absd16({a}, {b}, 0u) + absd16({a}, {b}, 16u)) + (uint64_t){c})"), + "v_msad_u8" if m.clamp => format!("sat_u32((uint64_t)msad_u8({a}, {b}) + (uint64_t){c})"), "v_sad_u32" => format!("(max({a}, {b}) - min({a}, {b})) + {c}"), "v_sad_u8" => format!("sad_u8({a}, {b}) + {c}"), "v_sad_hi_u8" => format!("(sad_u8({a}, {b}) << 16) + {c}"), @@ -3318,6 +3389,16 @@ impl Em { "v_sub_nc_i32" if m.clamp => format!("sat_i32((int64_t)(int){a} - (int64_t)(int){b})"), "v_add_nc_i32" => format!("{a} + {b}"), "v_sub_nc_i32" => format!("{a} - {b}"), + "v_mad_u32_u16" if m.clamp => format!( + "sat_u32((uint64_t)((({a} >> {}u) & 0xFFFFu) * (({b} >> {}u) & 0xFFFFu)) + (uint64_t){c})", + 16 * (m.opsel & 1), + 8 * (m.opsel & 2) + ), + "v_mad_i32_i16" if m.clamp => format!( + "sat_i32((int64_t)((((int)(({a} >> {}u) << 16)) >> 16) * (((int)(({b} >> {}u) << 16)) >> 16)) + (int64_t)(int){c})", + 16 * (m.opsel & 1), + 8 * (m.opsel & 2) + ), "v_mad_u32_u16" => format!("(({a} >> {}u) & 0xFFFFu) * (({b} >> {}u) & 0xFFFFu) + {c}", 16 * (m.opsel & 1), 8 * (m.opsel & 2)), "v_mad_i32_i16" => format!( "(uint)((((int)(({a} >> {}u) << 16)) >> 16) * (((int)(({b} >> {}u) << 16)) >> 16) + (int){c})", @@ -3325,7 +3406,7 @@ impl Em { 8 * (m.opsel & 2) ), "v_cvt_pk_u16_u32" => format!("min({a}, 0xFFFFu) | (min({b}, 0xFFFFu) << 16)"), - "v_cvt_pk_i16_i32" => format!("((uint)clamp((int){a}, -32768, 32767) & 0xFFFFu) | (((uint)clamp((int){b}, -32768, 32767) & 0xFFFFu) << 16)"), + "v_cvt_pk_i16_i32" => format!("sat_i16((int){a}) | (sat_i16((int){b}) << 16)"), "v_cvt_pknorm_i16_f32" => format!("(cvt_norm_i16_f32({}) | (cvt_norm_i16_f32({}) << 16))", fs(0), fs(1)), "v_cvt_pknorm_u16_f32" => format!("(uint)round(saturate({}) * 65535.0f) | ((uint)round(saturate({}) * 65535.0f) << 16)", fs(0), fs(1)), // packed f16 sources: op_sel[0]/[1] pick each source's half; result fills all 32 bits @@ -3437,16 +3518,21 @@ impl Em { "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" => { let (x, y) = if name == "v_subrev_co_u32" { (b.clone(), a.clone()) } else { (a.clone(), b.clone()) }; let t = self.t(); - let carry = if name == "v_add_co_u32" { - self.line(&format!("uint {t} = {x} + {y};")); - format!("{t} < {x}") + let is_add = name == "v_add_co_u32"; + if is_add { + self.line(&format!("uint {t} = {x} + {y}; bool {t}_c = {t} < {x};")); } else { - self.line(&format!("uint {t} = {x} - {y};")); - format!("{y} > {x}") - }; + self.line(&format!("uint {t} = {x} - {y}; bool {t}_c = {y} > {x};")); + } let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106)); - self.write_mask(&sdst, &carry); - self.vwrite(d, &dst, &t); + self.write_mask(&sdst, &format!("{t}_c")); + let out = if m.clamp { + let sat = if is_add { "0xFFFFFFFFu" } else { "0u" }; + format!("select({t}_c, {sat}, {t})") + } else { + t + }; + self.vwrite(d, &dst, &out); return Ok(()); } "v_add_co_ci_u32" | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => { @@ -3454,15 +3540,22 @@ impl Em { let cin = format!("(uint)({})", self.lane_of(l, h)); let (x, y) = if name == "v_subrev_co_ci_u32" { (b.clone(), a.clone()) } else { (a.clone(), b.clone()) }; let t = self.t(); - if name == "v_add_co_ci_u32" { + let is_add = name == "v_add_co_ci_u32"; + if is_add { self.line(&format!("uint64_t {t}w = (uint64_t){x} + (uint64_t){y} + (uint64_t){cin};")); } else { self.line(&format!("uint64_t {t}w = (uint64_t){x} - (uint64_t){y} - (uint64_t){cin};")); } - self.line(&format!("uint {t} = (uint){t}w;")); + self.line(&format!("uint {t} = (uint){t}w; bool {t}_c = ({t}w >> 32) != 0ull;")); let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106)); - self.write_mask(&sdst, &format!("({t}w >> 32) != 0ull")); - self.vwrite(d, &dst, &t); + self.write_mask(&sdst, &format!("{t}_c")); + let out = if m.clamp { + let sat = if is_add { "0xFFFFFFFFu" } else { "0u" }; + format!("select({t}_c, {sat}, {t})") + } else { + t + }; + self.vwrite(d, &dst, &out); return Ok(()); } _ => return Err("VALU"), @@ -4024,10 +4117,21 @@ impl Em { // ---------------------------------------------------------------- whole shader - /// Split wave64: threads of the console's thread group. + /// Compute mode: the threads of the PC group – the console's, or whole console waves of + /// them (`cs_pad`). + fn cs_threads(&self, cs: &super::CsInterface) -> u32 { + let threads: u32 = cs.threads.iter().product(); + if self.cs_pad { + threads.next_multiple_of(if self.opt.wave64 { 64 } else { 32 }) + } else { + threads + } + } + + /// Split wave64: threads of the thread group. fn x64_threads(&self) -> u32 { match &self.opt.mode { - Mode::Compute(cs) => cs.threads.iter().product(), + Mode::Compute(cs) => self.cs_threads(cs), Mode::Mesh(ms) => ms.threads, _ => 64, } @@ -4227,7 +4331,10 @@ impl Em { // thread indices (AMD RDNA4 lays them out in 2 x 2 quads: lanes 0, 1, 4, 5, 8 … // of an 8 x 8 group; NVIDIA differs too), the console does – a hardware wave // takes the next `lanes` console threads as it arrives, lane l the l-th of them - let reorder = !self.x64() && y * z > 1; + // a padded group (`cs_pad`) is declared 1-D and takes its threads the same + // way, so the lanes of its last wave that the console launches are its first + let padded = self.cs_pad.then(|| self.cs_threads(cs)); + let reorder = !self.x64() && (y * z > 1 || padded.is_some()); if reorder { // console threads handed to waves so far: the program's top LDS word while // the waves take their threads (the console's LDS starts undefined; D3D12's @@ -4238,16 +4345,17 @@ impl Em { h.push_str("groupshared uint xcl_wt;\n#define XCL_WT xcl_wt\n"); } } + let [nx, ny, nz] = padded.map_or([x, y, z], |t| [t, 1, 1]); let _ = writeln!( h, - "[WaveSize({hw_lanes})]\n[numthreads({x}, {y}, {z})]\nvoid main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID, uint gi : SV_GroupIndex)\n{{" + "[WaveSize({hw_lanes})]\n[numthreads({nx}, {ny}, {nz})]\nvoid main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID, uint gi : SV_GroupIndex)\n{{" ); if self.x64() { // the console thread's ids (`xcl_x_thread`), not this hardware thread's self.x64_entry(&mut h); let _ = writeln!(h, " gtid = uint3(xcl_tid % {x}u, (xcl_tid / {x}u) % {y}u, xcl_tid / {}u);\n gi = xcl_tid;", x * y); } else if reorder { - let t = x * y * z; + let t = padded.unwrap_or(x * y * z); let _ = writeln!( h, " if (gi == 0u) XCL_WT = 0u;\n GroupMemoryBarrierWithGroupSync();\n lane_id = WaveGetLaneIndex();\n {{\n bool full = WaveActiveCountBits(true) == {lanes}u;\n uint base = {}u;\n if (WaveIsFirstLane() && full) InterlockedAdd(XCL_WT, {lanes}u, base);\n uint xcl_tid = WaveReadLaneFirst(base) + lane_id;\n gtid = uint3(xcl_tid % {x}u, (xcl_tid / {x}u) % {y}u, xcl_tid / {}u);\n gi = xcl_tid;\n }}\n GroupMemoryBarrierWithGroupSync(); // all waves have their threads before the program writes LDS", @@ -4272,7 +4380,10 @@ impl Em { // waves in the group: a last, partial wave counts (96 threads: 2 of 64) let _ = writeln!(h, " {} = {}u | ((gi / {lanes}u) << 6);", sname(next).unwrap(), (x * y * z).div_ceil(lanes)); } - let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0 = {}(true); exec_lo = e0.x; exec_hi = e0.y; }}", self.ballot_fn()); + // a padded group: the lanes past the console's threads start inactive (`gi` is + // the console thread's index here) + let launched = if padded.is_some() { format!("gi < {}u", x * y * z) } else { "true".into() }; + let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0 = {}({launched}); exec_lo = e0.x; exec_hi = e0.y; }}", self.ballot_fn()); for &v in &self.vgprs { let init = match v { 0 => "gtid.x", @@ -5362,8 +5473,13 @@ uint sad_u8(uint a, uint b) { return absd8(a, b, 0u) + absd8(a, b, 8u) + absd8(a uint msad_u8(uint a, uint b) { return select((b & 0xFFu) != 0u, absd8(a, b, 0u), 0u) + select(((b >> 8) & 0xFFu) != 0u, absd8(a, b, 8u), 0u) + select(((b >> 16) & 0xFFu) != 0u, absd8(a, b, 16u), 0u) + select((b >> 24) != 0u, absd8(a, b, 24u), 0u); } uint lerp8(uint a, uint b, uint c, uint k) { return ((((a >> k) & 0xFFu) + ((b >> k) & 0xFFu) + ((c >> k) & 1u)) >> 1) << k; } uint lerp_u8(uint a, uint b, uint c) { return lerp8(a, b, c, 0u) | lerp8(a, b, c, 8u) | lerp8(a, b, c, 16u) | lerp8(a, b, c, 24u); } -uint sat_u32(uint64_t r) { return select(r > (uint64_t)0xFFFFFFFFu, 0xFFFFFFFFu, (uint)r); } +// branchless saturate: Windows SDK DXC 1.7-1.9.2602 turns `select(r > 0xFFFFFFFFu, ...)` +// on a 64-bit product into forbidden `llvm.umul.with.overflow.i32` (DXIL validation fails) +uint sat_u32(uint64_t r) { return (uint)r | (0u - min((uint)(r >> 32), 1u)); } uint sat_i32(int64_t r) { return select(r > (int64_t)0x7FFFFFFF, 0x7FFFFFFFu, select(r < -(int64_t)0x80000000u, 0x80000000u, (uint)r)); } +// select instead of `clamp(r, -32768, 32767) & 0xFFFFu`: NVIDIA's SPIR-V backend drops the +// `& 0xFFFFu` mask after `SMin(SMax(r, -32768), 32767)`, leaking sign bits into the upper half +uint sat_i16(int r) { return select(r > 32767, 0x7FFFu, select(r < -32768, 0x8000u, (uint)r & 0xFFFFu)); } float div_fixup(float q, float d, float n) { return select(or(or(isnan(d), isnan(n)), or(d == 0.0f, or(isinf(d), isinf(n)))), n / d, q); } float fma_legacy(float a, float b, float c) { return (a == 0.0f || b == 0.0f) ? c : mad(a, b, c); } float mad_nf(float a, float b, float c) { precise float p = a * b; precise float r = p + c; return r; } diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 34ac919..75c9595 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -55,6 +55,7 @@ pub mod dxc; pub(crate) mod emit; pub mod mesh_dispatch; pub mod mesh_wave; +pub mod partial_waves; pub mod x64_masks; pub mod pso; pub use emit::mesh_passthrough; @@ -493,11 +494,29 @@ pub struct Options { /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) pub structured: bool, + /// compute groups that are not whole console waves + pub pad_waves: PadWaves, +} + +/// A compute group that is not a whole number of console waves (40 threads: one wave64 with +/// lanes 0..39 launched) as a PC group of whole waves, its extra lanes inactive at the start +/// as the console's are: for a program that can tell them (`partial_waves`: it turns them on +/// in EXEC, or writes them with `v_writelane`). Every other program keeps its group. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum PadWaves { + /// where the program can tell; `XCL_CS_PAD_ALL=1` / `XCL_NO_CS_PAD=1` make it `Always` / + /// `Never` (for comparison) + #[default] + WhereSeen, + /// every group that is not whole waves + Always, + /// never: the group as the console declares it + Never, } impl Default for Options { fn default() -> Self { - Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, structured: true } + Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, structured: true, pad_waves: PadWaves::WhereSeen } } } @@ -1339,6 +1358,24 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { if opt.wave64 && opt.split_wave64 && matches!(opt.mode, Mode::Kernel | Mode::Compute(_) | Mode::Mesh(_)) && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { em.x64_whole_live = x64_masks::by_pc(&insts, matches!(opt.mode, Mode::Kernel)); } + // a compute group that is not whole console waves: padded to whole waves where the + // program can tell the lanes its last wave does not launch + if let Mode::Compute(cs) = &opt.mode { + let lanes = if opt.wave64 { 64 } else { 32 }; + let threads: u32 = cs.threads.iter().product(); + let pad = match opt.pad_waves { + PadWaves::WhereSeen if std::env::var_os("XCL_NO_CS_PAD").is_some() => PadWaves::Never, + PadWaves::WhereSeen if std::env::var_os("XCL_CS_PAD_ALL").is_some() => PadWaves::Always, + p => p, + }; + em.cs_pad = !threads.is_multiple_of(lanes) + && threads.next_multiple_of(lanes) <= 1024 + && match pad { + PadWaves::Always => true, + PadWaves::Never => false, + PadWaves::WhereSeen => partial_waves::sees_lanes_not_launched(&insts, opt.wave64, threads % lanes).is_some(), + }; + } // a wave64 VS / PS on a GPU that can run 32-lane waves: what lanes 32..63 hold where the // program reads them (the driver may still pick 64 lanes: decided at run time); only a // program with a read to change gets the form diff --git a/crates/xcl/src/gpu/recomp/partial_waves.rs b/crates/xcl/src/gpu/recomp/partial_waves.rs new file mode 100644 index 0000000..1a06e04 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/partial_waves.rs @@ -0,0 +1,359 @@ +//! Compute groups that are not whole console waves: can the program tell the lanes its last +//! wave does not launch? +//! +//! A group of 40 threads is one wave64 with lanes 0..39 launched. On the console lanes 40..63 +//! exist all the same: inactive, but `v_writelane` (which ignores EXEC) writes them, and code +//! that turns them on in EXEC – whole-wave code (`s_or_saveexec_b64 s, -1`), `s_not_b64 exec`, +//! `s_wqm_b64 exec` – runs in them: its compares see them, its writes reach them, a later +//! `v_readlane` or DPP step reads them back. A PC thread group of 40 threads has no such +//! lanes. A program that can tell gets them (`Em::cs_pad`: the group padded to whole waves, +//! the padding lanes inactive at the start, as on the console); any other program keeps its +//! group, and its translation, as they are. +//! +//! A program can tell when it has a `v_writelane` to a lane the last wave may not launch, or +//! when EXEC may get a bit outside the launched lanes. The second is a forward data-flow pass +//! over the SGPRs as 32-bit words that are known subsets of the last wave's launched lanes, +//! as a low word (lanes 0..31) and as a high word (lanes 32..63): EXEC is one at the start; a +//! VALU mask (`v_cmp*`, carries) is a subset of EXEC; AND with a subset, OR / XOR of two, the +//! saveexec forms, moves and selects keep the property; every other value is taken to have +//! any bit. Conservative: where it cannot follow (an indirect jump, a value from memory) the +//! program is padded, which is exact, only more threads. + +use std::collections::{BTreeMap, BTreeSet}; + +use super::upper_lanes::{is_valu, sgpr_outputs, slot, successors}; +use crate::gpu::rdna2::{self, Decoded}; + +/// What is known of a 32-bit word: `LO` – its bits are launched lanes when it is a low word, +/// `HI` – when it is a high word. +type Sub = u8; +const LO: Sub = 1; +const HI: Sub = 2; + +#[derive(Clone, PartialEq)] +struct State { + s: [Sub; 128], + /// launched lanes of the last wave as (low, high) words + launched: (u32, u32), +} + +impl State { + fn of(&self, v: u32) -> Sub { + (if v & !self.launched.0 == 0 { LO } else { 0 }) | (if v & !self.launched.1 == 0 { HI } else { 0 }) + } + + /// What any value is. + fn any(&self) -> Sub { + self.of(!0) + } + + fn entry(wave64: bool, launched: u32) -> State { + let mask = if launched >= 64 { !0u64 } else { (1u64 << launched) - 1 }; + let mut st = State { s: [0; 128], launched: (mask as u32, (mask >> 32) as u32) }; + st.s = [st.any(); 128]; + st.s[125] = LO | HI; // NULL + st.s[126] |= LO; + if wave64 { + st.s[127] |= HI; + } + st + } + + fn join(&self, o: &State) -> State { + let mut s = self.s; + for (a, b) in s.iter_mut().zip(o.s) { + *a &= b; + } + State { s, launched: self.launched } + } + + fn set(&mut self, r: u64, w: Sub) { + if r < 128 && r != 125 { + self.s[r as usize] = w; + } + } + + /// A 32-bit scalar source (operand code). + fn src32(&self, d: &Decoded, code: u64) -> Sub { + match code { + 0..=127 => self.s[code as usize], + 128..=192 => self.of((code - 128) as u32), + 193..=208 => self.of((-((code - 192) as i32)) as u32), + 255 => d.literal.map_or(self.any(), |l| self.of(l)), + _ => self.any(), + } + } + + /// A 64-bit scalar source (operand code) as (low, high) words; a 32-bit literal is the + /// low word of an integer operand, inline integers are sign-extended (as `Em::code64`). + fn src64(&self, d: &Decoded, code: u64) -> (Sub, Sub) { + match code { + 0..=123 | 126 => (self.s[code as usize], self.s[code as usize + 1]), + 125 => (LO | HI, LO | HI), + 128..=192 => (self.of((code - 128) as u32), self.of(0)), + 193..=208 => (self.of((-((code - 192) as i32)) as u32), self.of(!0)), + 255 => (d.literal.map_or(self.any(), |l| self.of(l)), self.of(0)), + _ => (self.any(), self.any()), + } + } + + /// A bitwise SALU operation by its name's second part (`S_ANDN2_SAVEEXEC_B64` → "ANDN2"): + /// a AND b is a subset of either, a OR / XOR b of what both are subsets of, a AND NOT b + /// of a; the forms that invert their result or an OR operand may set any bit. + fn bitop(&self, op: &str, a: Sub, b: Sub) -> Option { + Some(match op { + "AND" => a | b, + "OR" | "XOR" => a & b, + "ANDN2" => a, + "ANDN1" => b, + "ORN2" | "NAND" | "NOR" | "XNOR" | "ORN1" => self.any(), + _ => return None, + }) + } +} + +/// One instruction's effect. +fn step(d: &Decoded, st: &mut State, wave64: bool) { + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let any = st.any(); + if name.starts_with("S_MOVREL") { + // s_movreld / s_movrelsd_2 write s[dst + m0]: any SGPR up to VCC (`x64_masks::uses`) + for r in 0..124 { + st.set(r, any); + } + return; + } + let op = name.split('_').nth(1).unwrap_or(""); + let b64 = name.ends_with("_B64"); + if name.contains("SAVEEXEC") || name.contains("WREXEC") { + let s0 = if b64 { st.src64(d, fv("SSRC0")) } else { (st.src32(d, fv("SSRC0")), any) }; + let (el, eh) = (st.s[126], st.s[127]); + let nl = st.bitop(op, s0.0, el).unwrap_or(any); + let nh = st.bitop(op, s0.1, eh).unwrap_or(any); + let dst = fv("SDST"); + let wr = name.contains("WREXEC"); + st.s[126] = nl; + st.set(dst, if wr { nl } else { el }); + if b64 { + st.s[127] = nh; + st.set(dst + 1, if wr { nh } else { eh }); + } + return; + } + if d.enc.name == "ENC_SOP1" || d.enc.name == "ENC_SOP2" { + let dst = fv("SDST"); + let a = |st: &State| if b64 { st.src64(d, fv("SSRC0")) } else { (st.src32(d, fv("SSRC0")), any) }; + let b = |st: &State| if b64 { st.src64(d, fv("SSRC1")) } else { (st.src32(d, fv("SSRC1")), any) }; + let both = |x: (Sub, Sub), y: (Sub, Sub)| (x.0 & y.0, x.1 & y.1); + let r: Option<(Sub, Sub)> = match op { + "MOV" if d.enc.name == "ENC_SOP1" && (name == "S_MOV_B32" || name == "S_MOV_B64") => Some(a(st)), + "CMOV" if d.enc.name == "ENC_SOP1" => Some(both(a(st), (st.s[dst.min(127) as usize], st.s[(dst + 1).min(127) as usize]))), + "CSELECT" => Some(both(a(st), b(st))), + _ if d.enc.name == "ENC_SOP2" && (name.ends_with("_B32") || b64) => { + let (x, y) = (a(st), b(st)); + st.bitop(op, x.0, y.0).zip(st.bitop(op, x.1, y.1)) + } + _ => None, + }; + if let Some((lo, hi)) = r { + st.set(dst, lo); + if b64 { + st.set(dst + 1, hi); + } + return; + } + } + let valu = is_valu(d); + let (el, eh) = (st.s[126], st.s[127]); + for (r, n) in sgpr_outputs(d) { + if valu && n == 2 { + // a lane mask (v_cmpx: EXEC itself): the bits of inactive lanes are 0. A wave32 + // program's mask is its low word only + st.set(r, el); + if wave64 { + st.set(r + 1, eh); + } + } else { + for k in r..r + n { + st.set(k, any); + } + } + } +} + +/// Why the program can tell the lanes the last wave of its group does not launch (None: it +/// cannot). `insts`: the program in address order, far jumps resolved; `launched`: the lanes +/// that wave does launch (1 .. wave size - 1). +pub fn sees_lanes_not_launched(insts: &[Decoded], wave64: bool, launched: u32) -> Option<&'static str> { + let lanes = if wave64 { 64 } else { 32 }; + if insts.is_empty() || launched == 0 || launched >= lanes { + return None; + } + // `v_writelane` ignores EXEC: a lane that was not launched is written on the console + if insts.iter().any(|d| d.inst.name == "V_WRITELANE_B32" && !slot(d).is_some_and(|(_, l)| l & (lanes - 1) < launched)) { + return Some("v_writelane to a lane the last wave may not launch"); + } + let pcs: BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); + let succ = successors(insts, &pcs); + let mut at: Vec> = vec![None; insts.len()]; + at[0] = Some(State::entry(wave64, launched)); + let mut work = BTreeSet::from([0usize]); + while let Some(i) = work.pop_first() { + let mut st = at[i].clone().expect("queued with a state"); + step(&insts[i], &mut st, wave64); + if st.s[126] & LO == 0 || (wave64 && st.s[127] & HI == 0) { + return Some("EXEC may turn on lanes the last wave does not launch"); + } + let Some(s) = &succ[i] else { + return Some("an indirect jump: EXEC is not followed"); + }; + for &j in s { + let new = match &at[j] { + None => st.clone(), + Some(old) => old.join(&st), + }; + if at[j].as_ref() != Some(&new) { + at[j] = Some(new); + work.insert(j); + } + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::rdna2::encode; + + const V: u64 = 256; + type I = (&'static str, &'static str, &'static [(&'static str, u64)]); + const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); + const CMP: I = ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]); + + fn program(lines: &[I]) -> Vec { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| encode(n, e, f, None).unwrap()).collect(); + let mut out = Vec::new(); + let mut off = 0usize; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + out.push(d); + } + rdna2::resolve_far_jumps(&mut out); + out + } + + fn sees(lines: &[I], launched: u32) -> bool { + sees_lanes_not_launched(&program(lines), true, launched).is_some() + } + + #[test] + fn if_else_and_loop_masks_stay_in_the_launched_lanes() { + // if (vcc) … else … end, as the console compiler writes it + let if_else: &[I] = &[ + CMP, + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_XOR_B64", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 129)]), + ("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 0)]), + ("S_XOR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 130)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + // a loop that lanes leave one by one: s[4:5] collects them, EXEC loses them + let a_loop: &[I] = &[ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 128)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 126)]), + CMP, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 2), ("SSRC1", 4)]), + ("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 4)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFB)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 6)]), + ENDPGM, + ]; + for launched in [1, 10, 20, 32, 40, 63] { + assert!(!sees(if_else, launched), "if / else, {launched} lanes"); + assert!(!sees(a_loop, launched), "loop, {launched} lanes"); + assert!(!sees(&[("V_CMPX_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]), ENDPGM], launched), "v_cmpx, {launched} lanes"); + } + } + + #[test] + fn exec_turning_on_other_lanes_is_seen() { + let widen: [&[I]; 7] = [ + &[("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 193)])], + &[("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])], + &[("S_NOT_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)])], + &[("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)])], + &[("S_ORN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)])], + // a mask from the program's arguments, and one from a scalar load + &[("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 8)])], + &[("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 12), ("SBASE", 4), ("OFFSET", 0), ("SOFFSET", 125)]), ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 12)])], + ]; + for w in widen { + let mut l = vec![CMP]; + l.extend_from_slice(w); + l.push(ENDPGM); + for launched in [10, 40] { + assert!(sees(&l, launched), "{} with {launched} lanes", w.last().unwrap().0); + } + } + } + + #[test] + fn constants_count_by_their_bits() { + // exec = 15 (lanes 0..3): inside 10 or 4 launched lanes, not inside 3 + let low8: &[I] = &[("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128 + 15)]), ENDPGM]; + assert!(!sees(low8, 10) && !sees(low8, 4) && sees(low8, 3)); + // the high word alone: 1 = lane 32, launched from 33 lanes on + let hi: &[I] = &[("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 129)]), ENDPGM]; + assert!(sees(hi, 32) && !sees(hi, 33)); + // the low word of a wave of 40 lanes is whole: any value is inside it + let lo: &[I] = &[("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 8)]), ENDPGM]; + assert!(!sees(lo, 40) && sees(lo, 31)); + } + + #[test] + fn a_wider_exec_on_one_path_is_seen() { + // s_cbranch_scc0 → skip; s_mov_b64 s[2:3], -1; skip: s_and_b64 exec, exec, s[2:3] is + // fine either way, s_or_b64 is not + let with = |last: I| -> Vec { + vec![ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 128)]), + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 1)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 193)]), + last, + ENDPGM, + ] + }; + assert!(!sees(&with(("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 2)])), 40)); + assert!(sees(&with(("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 2)])), 40)); + } + + #[test] + fn v_writelane_to_a_lane_that_may_be_missing_is_seen() { + let lane5: &[I] = &[("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 4), ("SRC1", 128 + 5)]), ENDPGM]; + let lane20: &[I] = &[("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 4), ("SRC1", 128 + 20)]), ENDPGM]; + let lane37: &[I] = &[("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 4), ("SRC1", 128 + 37)]), ENDPGM]; + assert!(!sees(lane5, 20) && sees(lane20, 20) && sees(lane37, 20)); + // a wave32 program's lane 37 is lane 5 + assert!(sees_lanes_not_launched(&program(lane37), false, 20).is_none()); + // a lane from an SGPR: any lane + assert!(sees(&[("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 4), ("SRC1", 6)]), ENDPGM], 20)); + } + + #[test] + fn whole_waves_and_wave32_programs() { + let whole_wave: &[I] = &[("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 193)]), ENDPGM]; + assert!(sees_lanes_not_launched(&program(whole_wave), true, 0).is_none(), "no partial wave"); + // a wave32 program: EXEC is s126 alone, s127 is data + let w32: &[I] = &[("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 193)]), CMP, ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), ENDPGM]; + assert!(sees_lanes_not_launched(&program(w32), false, 20).is_none()); + let w32_wide: &[I] = &[("S_OR_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 193)]), ENDPGM]; + assert!(sees_lanes_not_launched(&program(w32_wide), false, 20).is_some()); + } +} diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 68c7b09..9d02109 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -5,9 +5,9 @@ //! directly indexed descriptor heaps (images / samplers). Mapping the title's root arguments //! onto that ABI at draw time is the next step (needs the console runtime's user-data layout). -use std::collections::VecDeque; +use std::collections::HashMap; use std::path::PathBuf; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock, Weak}; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; @@ -15,13 +15,31 @@ use windows::Win32::Graphics::Direct3D12::*; use super::{dxc, interface, translate, Mode, Options}; use crate::gpu::xbox; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Stage { Vertex, Pixel, Compute, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum CacheStage { + Vertex, + Pixel, + Compute, + Mesh, +} + +impl From for CacheStage { + fn from(stage: Stage) -> Self { + match stage { + Stage::Vertex => Self::Vertex, + Stage::Pixel => Self::Pixel, + Stage::Compute => Self::Compute, + } + } +} + /// A console (xbox-native) shader container? pub fn is_console(blob: &[u8]) -> bool { xbox::is_xbox(blob) || fspx(blob).is_some() @@ -103,27 +121,43 @@ pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_w console_to_dxil_in(blob, stage, sampler_base, split_wave64, mem_windows()) } -/// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile` -/// fills the caches without a title: the same keys as at its run). -pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { - let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); - if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { - return compile_one(); - } +fn shader_mem_cache() -> &'static Mutex { static CACHE: OnceLock> = OnceLock::new(); - let cache = CACHE.get_or_init(|| Mutex::new(ShaderCache::new(64 << 20))); + CACHE.get_or_init(|| Mutex::new(ShaderCache::with_max_entries(64 << 20, 4096))) +} + +fn cached_console_stage( + blob: &[u8], + stage: CacheStage, + sampler_base: u32, + windows: u32, + split_wave64: bool, + compile_one: impl FnOnce() -> Result, +) -> Result { + let cache = shader_mem_cache(); + let cache_dir = dxc::cache_dir(); let key = ShaderKey { hash: crate::gpu::shader::fnv64(blob), stage, sampler_base, windows, split_wave64, - cache_dir: dxc::cache_dir(), + cache_dir: cache_dir.clone(), }; - let from_disk = || translated::cached(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, compile_one); + let from_disk = || translated::cached(&cache_dir, blob, stage, sampler_base, windows, split_wave64, compile_one); cached_shader(cache, key, blob, from_disk).map(|shader| shader.as_ref().clone()) } +/// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile` +/// fills the caches without a title: the same keys as at its run). +pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { + let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); + if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { + return compile_one(); + } + cached_console_stage(blob, stage.into(), sampler_base, windows, split_wave64, compile_one) +} + /// Translations on disk: a console program's (DXIL, static samplers) by its bytes, so a run /// does not translate again what an earlier run of the same XCL build translated. The DXIL /// cache is keyed by the generated HLSL, so it needs the translation first: a retail game's @@ -132,7 +166,7 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa /// translation parameters; the XCL binary's hash is in each file (another build: a miss). /// `XCL_TRANSLATED_CACHE=0` turns it off. mod translated { - use super::{Compiled, Stage}; + use super::{CacheStage, Compiled}; use std::path::{Path, PathBuf}; use std::sync::OnceLock; @@ -154,7 +188,7 @@ mod translated { b.iter().fold(0x9E37_79B9_7F4A_7C15u64, |h, &x| (h ^ x as u64).wrapping_mul(0xFF51_AFD7_ED55_8CCD).rotate_left(29)) } - fn file(dir: &Path, blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split: bool) -> PathBuf { + pub(super) fn file(dir: &Path, blob: &[u8], stage: CacheStage, sampler_base: u32, windows: u32, split: bool) -> PathBuf { dir.join("translated").join(format!("{:016x}_{stage:?}_{sampler_base}_{windows}_{}.bin", crate::gpu::shader::fnv64(blob), split as u8)) } @@ -208,7 +242,7 @@ mod translated { pub(super) fn cached( dir: &Path, blob: &[u8], - stage: Stage, + stage: CacheStage, sampler_base: u32, windows: u32, split: bool, @@ -322,10 +356,10 @@ pub fn console_to_hlsl(blob: &[u8], stage: Stage) -> Result<(String, &'static st console_translation(blob, stage, 0, mem_windows(), false).map(|(t, p)| (t.hlsl, p)) } -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq, Hash)] struct ShaderKey { hash: u64, - stage: Stage, + stage: CacheStage, sampler_base: u32, windows: u32, split_wave64: bool, @@ -333,67 +367,131 @@ struct ShaderKey { } struct ShaderEntry { - key: ShaderKey, blob: Vec, shader: Arc, + bytes: usize, + last_used: u64, } -impl ShaderEntry { - fn bytes(&self) -> usize { - self.blob.len() - + self.key.cache_dir.capacity() - + self.shader.dxil.capacity() - + self.shader.samplers.capacity() * std::mem::size_of::() - } +fn entry_bytes(key: &ShaderKey, blob: &[u8], shader: &Compiled) -> usize { + blob.len() + + key.cache_dir.capacity() + + shader.dxil.capacity() + + shader.samplers.capacity() * std::mem::size_of::() } struct ShaderCache { - entries: VecDeque, + entries: HashMap>, bytes: usize, limit: usize, + entry_count: usize, + max_entries: usize, + clock: u64, } impl ShaderCache { + #[cfg(test)] fn new(limit: usize) -> Self { + Self::with_max_entries(limit, 128) + } + + fn with_max_entries(limit: usize, max_entries: usize) -> Self { Self { - entries: VecDeque::new(), + entries: HashMap::new(), bytes: 0, limit, + entry_count: 0, + max_entries: max_entries.max(1), + clock: 0, } } + #[cfg(test)] + fn len(&self) -> usize { + self.entry_count + } + + #[cfg(test)] + fn is_empty(&self) -> bool { + self.entry_count == 0 + } + fn get(&mut self, key: &ShaderKey, blob: &[u8]) -> Option> { - let at = self + let bucket = self.entries.get_mut(key)?; + let entry = bucket.iter_mut().find(|e| e.blob == blob)?; + self.clock += 1; + entry.last_used = self.clock; + Some(entry.shader.clone()) + } + + fn evict_oldest(&mut self) -> bool { + let Some((key, idx)) = self .entries .iter() - .rposition(|e| &e.key == key && e.blob == blob)?; - let entry = self.entries.remove(at)?; - let shader = entry.shader.clone(); - self.entries.push_back(entry); - Some(shader) + .flat_map(|(k, bucket)| bucket.iter().enumerate().map(move |(i, e)| (e.last_used, k, i))) + .min_by_key(|&(tick, _, _)| tick) + .map(|(_, k, i)| (k.clone(), i)) + else { + return false; + }; + let empty = { + let bucket = self.entries.get_mut(&key).unwrap(); + let removed = bucket.swap_remove(idx); + self.bytes -= removed.bytes; + self.entry_count -= 1; + bucket.is_empty() + }; + if empty { + self.entries.remove(&key); + } + true } fn insert(&mut self, key: ShaderKey, blob: &[u8], shader: Arc) { - let bytes = blob.len() - + key.cache_dir.capacity() - + shader.dxil.capacity() - + shader.samplers.capacity() * std::mem::size_of::(); + let bytes = entry_bytes(&key, blob, &shader); if bytes > self.limit { return; } - while self.bytes + bytes > self.limit || self.entries.len() >= 128 { - let Some(old) = self.entries.pop_front() else { + if let Some(bucket) = self.entries.get_mut(&key) { + if let Some(pos) = bucket.iter().position(|e| e.blob == blob) { + let removed = bucket.swap_remove(pos); + self.bytes -= removed.bytes; + self.entry_count -= 1; + if bucket.is_empty() { + self.entries.remove(&key); + } + } + } + while self.bytes + bytes > self.limit || self.entry_count >= self.max_entries { + if !self.evict_oldest() { break; - }; - self.bytes -= old.bytes(); + } } - self.entries.push_back(ShaderEntry { - key, + self.clock += 1; + let last_used = self.clock; + self.entries.entry(key).or_default().push(ShaderEntry { blob: blob.to_vec(), shader, + bytes, + last_used, }); self.bytes += bytes; + self.entry_count += 1; + } +} + +fn shader_flight(cache_id: usize, key: ShaderKey) -> Arc> { + type FlightMap = Mutex>>>; + static FLIGHTS: OnceLock = OnceLock::new(); + let mut flights = FLIGHTS.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap(); + flights.retain(|_, v| v.strong_count() != 0); + let fk = (cache_id, key); + if let Some(flight) = flights.get(&fk).and_then(Weak::upgrade) { + return flight; } + let flight = Arc::new(Mutex::new(())); + flights.insert(fk, Arc::downgrade(&flight)); + flight } fn cached_shader( @@ -402,22 +500,40 @@ fn cached_shader( blob: &[u8], compile_one: impl FnOnce() -> Result, ) -> Result, String> { + cached_shader_status(cache, key, blob, compile_one).map(|(shader, _)| shader) +} + +fn cached_shader_status( + cache: &Mutex, + key: ShaderKey, + blob: &[u8], + compile_one: impl FnOnce() -> Result, +) -> Result<(Arc, bool), String> { if let Some(shader) = cache.lock().unwrap().get(&key, blob) { dxc::note_memory_hit(); - return Ok(shader); + return Ok((shader, true)); + } + // Cached-only probes must never block waiting on another thread's in-flight build. + let flight = (!dxc::in_cached_only()).then(|| shader_flight(cache as *const Mutex as usize, key.clone())); + let _flight_guard = flight.as_ref().map(|f| f.lock().unwrap_or_else(|e| e.into_inner())); + if _flight_guard.is_some() { + if let Some(shader) = cache.lock().unwrap().get(&key, blob) { + dxc::note_memory_hit(); + return Ok((shader, true)); + } } // Keep compilation outside the cache lock, including cached-only probes. let shader = Arc::new(compile_one()?); let mut cache = cache.lock().unwrap(); if let Some(existing) = cache.get(&key, blob) { - return Ok(existing); + return Ok((existing, true)); } cache.insert(key, blob, shader.clone()); - Ok(shader) + Ok((shader, false)) } fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { - !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY"] + !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_CS_PAD_ALL", "XCL_NO_CS_PAD"] .iter() .any(|name| present(name)) && (stage != Stage::Pixel @@ -504,29 +620,57 @@ pub struct TwoPass { pub samplers: Vec, } +fn finish_two_pass_compiled(cs: Compiled, record: super::MsInterface, ps: Option<&[u8]>) -> Result { + let ps_inputs = ps.map(|p| crate::gpu::dxbc::signatures(p).0); + let ms = dxc::compile_cached(&super::emit::mesh_passthrough_for(&record, ps_inputs.as_deref()), "main", "ms_6_6")?.0; + let mesh_groups_per_record = super::emit::passthrough_split(&record, super::emit::passthrough_elements(&record, ps_inputs.as_deref())); + Ok(TwoPass { cs: cs.dxil, ms, record, mesh_groups_per_record, samplers: cs.samplers }) +} + fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option<&[u8]>) -> Result { if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); } let cs = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - let ps_inputs = ps.map(|p| crate::gpu::dxbc::signatures(p).0); - let ms = dxc::compile_cached(&super::emit::mesh_passthrough_for(&record, ps_inputs.as_deref()), "main", "ms_6_6")?.0; - let mesh_groups_per_record = super::emit::passthrough_split(&record, super::emit::passthrough_elements(&record, ps_inputs.as_deref())); - Ok(TwoPass { cs, ms, record, mesh_groups_per_record, samplers: t.static_samplers }) + finish_two_pass_compiled(Compiled { dxil: cs, samplers: t.static_samplers }, record, ps) } -/// The mesh-shader (NGG) program of a console MS container; the pass-through carries what -/// the pixel shader `ps` (its container: console or PC) reads. -pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result { +fn mesh_interface(blob: &[u8]) -> Result { let sh = xbox::parse(blob).ok_or("not a console shader container")?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 7)).ok_or("no NGG hardware variant")?; let mode = interface(blob, &sh, f).ok_or("unknown MS interface (e.g. lines / points)")?; - let Mode::Mesh(ms) = &mode else { return Err("the container is not an MS".into()) }; - let record = ms.clone(); + let Mode::Mesh(ms) = mode else { return Err("the container is not an MS".into()) }; + Ok(ms) +} + +fn compile_console_mesh(blob: &[u8], ms: &super::MsInterface, windows: u32, split_wave64: bool) -> Result { + let sh = xbox::parse(blob).ok_or("not a console shader container")?; + let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 7)).ok_or("no NGG hardware variant")?; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - finish_two_pass(super::translate_mesh(code, ms.clone(), super::detect_wave64(code), split_wave64, mem_windows())?, record, ps) + let t = super::translate_mesh(code, ms.clone(), super::detect_wave64(code), split_wave64, windows)?; + if !t.complete() { + let missing: Vec<&String> = t.unsupported.keys().collect(); + return Err(format!("incomplete translation, missing: {missing:?}")); + } + let dxil = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; + Ok(Compiled { dxil, samplers: t.static_samplers }) +} + +/// The mesh-shader (NGG) program of a console MS container; the pass-through carries what +/// the pixel shader `ps` (its container: console or PC) reads. Its compute pass is cached per +/// MS container so multiple PS pairings share one translation and DXIL build. +pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result { + let record = mesh_interface(blob)?; + let windows = mem_windows(); + let compile_one = || compile_console_mesh(blob, &record, windows, split_wave64); + let cs = if !cache_allowed(Stage::Compute, |name| std::env::var_os(name).is_some()) { + compile_one()? + } else { + cached_console_stage(blob, CacheStage::Mesh, 0, windows, split_wave64, compile_one)? + }; + finish_two_pass_compiled(cs, record, ps) } /// Whether the adapter runs only 32-lane waves (its wave range lacks 64): wave64 compute, @@ -714,7 +858,7 @@ mod shader_cache_tests { fn key(hash: u64) -> ShaderKey { ShaderKey { hash, - stage: Stage::Compute, + stage: CacheStage::Compute, sampler_base: 0, windows: 1, split_wave64: false, @@ -762,7 +906,7 @@ mod shader_cache_tests { let a = cached_shader(&cache, original.clone(), b"a", || Ok(compiled(1))).unwrap(); for changed in [ ShaderKey { - stage: Stage::Vertex, + stage: CacheStage::Vertex, ..original.clone() }, ShaderKey { @@ -805,7 +949,7 @@ mod shader_cache_tests { }) }); assert!(result.is_err() && missed); - assert!(cache.lock().unwrap().entries.is_empty()); + assert!(cache.lock().unwrap().is_empty()); let t = cached_shader(&cache, key(1), b"a", || Ok(compiled(9))).unwrap(); assert_eq!(t.dxil[0], 9); } @@ -813,12 +957,7 @@ mod shader_cache_tests { #[test] fn shader_cache_evicts_old_entries_and_skips_oversized_shaders() { let t = Arc::new(compiled(1)); - let limit = 2 * ShaderEntry { - key: key(1), - blob: b"a".to_vec(), - shader: t.clone(), - } - .bytes(); + let limit = 2 * entry_bytes(&key(1), b"a", &t); let mut cache = ShaderCache::new(limit); cache.insert(key(1), b"a", t.clone()); cache.insert(key(2), b"b", t.clone()); @@ -837,18 +976,18 @@ mod shader_cache_tests { ); assert!(cache.get(&key(4), b"d").is_none()); assert_eq!(cache.bytes, limit); - assert_eq!(cache.entries.len(), 2); + assert_eq!(cache.len(), 2); let mut cache = ShaderCache::new(1 << 20); for i in 0..129 { cache.insert(key(i), b"a", t.clone()); } - assert_eq!(cache.entries.len(), 128); + assert_eq!(cache.len(), 128); assert!(cache.get(&key(0), b"a").is_none()); } #[test] fn shader_cache_bypasses_debug_overrides() { - for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY"] { + for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_CS_PAD_ALL", "XCL_NO_CS_PAD"] { assert!(!cache_allowed(Stage::Compute, |v| v == name)); assert!(!cache_allowed(Stage::Vertex, |v| v == name)); assert!(!cache_allowed(Stage::Pixel, |v| v == name)); @@ -929,6 +1068,119 @@ mod shader_cache_tests { } }); } + + #[test] + fn shader_cache_with_max_entries_keeps_more_and_evicts_lru() { + let t = Arc::new(compiled(1)); + let mut cache = ShaderCache::with_max_entries(1 << 20, 300); + for i in 0..300u64 { + cache.insert(key(i), b"a", t.clone()); + } + assert_eq!(cache.len(), 300); + assert!(cache.get(&key(0), b"a").is_some()); + cache.insert(key(300), b"a", t); + assert_eq!(cache.len(), 300); + assert!(cache.get(&key(0), b"a").is_some()); + assert!(cache.get(&key(1), b"a").is_none()); + } + + #[test] + fn shader_cache_overwrite_updates_byte_accounting() { + let small = Arc::new(Compiled { + dxil: Vec::from(&[1u8; 16][..]), + samplers: Vec::new(), + }); + let other = Arc::new(Compiled { + dxil: Vec::from(&[2u8; 32][..]), + samplers: Vec::new(), + }); + let large = Arc::new(Compiled { + dxil: Vec::from(&[3u8; 100][..]), + samplers: Vec::new(), + }); + let small_bytes = entry_bytes(&key(1), b"a", &small); + let other_bytes = entry_bytes(&key(2), b"b", &other); + let large_bytes = entry_bytes(&key(1), b"a", &large); + let limit = (small_bytes + other_bytes).max(large_bytes) + 8; + assert!(large_bytes + other_bytes > limit); + + let mut cache = ShaderCache::new(limit); + cache.insert(key(1), b"a", small); + cache.insert(key(2), b"b", other); + assert_eq!(cache.bytes, small_bytes + other_bytes); + assert_eq!(cache.len(), 2); + + // Overwriting key(1) with a larger compiled shader must subtract the old size + // and evict key(2) so cache.bytes accurately reflects the new size within limit. + cache.insert(key(1), b"a", large); + assert_eq!(cache.len(), 1); + assert_eq!(cache.bytes, large_bytes); + assert!(cache.bytes <= limit); + assert!(cache.get(&key(2), b"b").is_none()); + assert_eq!(cache.get(&key(1), b"a").unwrap().dxil.len(), 100); + } + + #[test] + fn shader_cache_coalesces_concurrent_same_key_compiles() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let cache = Mutex::new(ShaderCache::new(1 << 20)); + let calls = AtomicUsize::new(0); + let hits = AtomicUsize::new(0); + let barrier = std::sync::Barrier::new(4); + std::thread::scope(|scope| { + let mut threads = Vec::new(); + for _ in 0..4 { + threads.push(scope.spawn(|| { + barrier.wait(); + let (shader, hit) = cached_shader_status(&cache, key(42), b"same", || { + calls.fetch_add(1, Ordering::SeqCst); + std::thread::sleep(std::time::Duration::from_millis(30)); + Ok(compiled(5)) + }) + .unwrap(); + assert_eq!(shader.dxil[0], 5); + hits.fetch_add(hit as usize, Ordering::SeqCst); + shader + })); + } + let first = threads.pop().unwrap().join().unwrap(); + for thread in threads { + assert!(Arc::ptr_eq(&first, &thread.join().unwrap())); + } + }); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(hits.load(Ordering::SeqCst), 3); + } + + #[test] + fn translated_disk_cache_isolates_mesh_stage_from_compute() { + let dir = std::env::temp_dir().join(format!("xcl-translated-mesh-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mesh_path = translated::file(&dir, b"blob", CacheStage::Mesh, 0, 1, false); + let cs_path = translated::file(&dir, b"blob", CacheStage::Compute, 0, 1, false); + assert_ne!(mesh_path, cs_path); + + let c_mesh = compiled(11); + let c_cs = compiled(22); + translated::store_in(&mesh_path, 99, b"blob", &c_mesh); + translated::store_in(&cs_path, 99, b"blob", &c_cs); + assert_eq!(translated::load_in(&mesh_path, 99, b"blob").unwrap().dxil, c_mesh.dxil); + assert_eq!(translated::load_in(&cs_path, 99, b"blob").unwrap().dxil, c_cs.dxil); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn console_mesh_rejects_non_mesh_blob_before_caching() { + use crate::gpu::xbox::tests::{fssm, sample, CODE}; + assert!(console_mesh(b"not a container", None, false).is_err()); + + let mut f = fssm(&CODE, &[(6, 0)]); + for offset in [0x13C, 0x140, 0x144] { + f[offset..offset + 4].copy_from_slice(&1u32.to_le_bytes()); + } + let compute_blob = sample(5, &[f]); + assert!(console_mesh(&compute_blob, None, false).is_err()); + } } #[cfg(test)] diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 33c45e8..81128e4 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -72,24 +72,58 @@ unsafe impl Send for Gpu {} static GPU: Mutex>> = Mutex::new(None); -fn e(x: windows::core::Error) -> String { +fn werr(x: windows::core::Error) -> String { format!("{x}") } +/// Signal + wait. On failure (timeout, device lost) the GPU may still be using the +/// resources the caller is about to drop on `?`: the device is then removed explicitly +/// (WARP has no TDR, a hung kernel would never stop), which makes freeing them safe; +/// `with_gpu` then recreates the device for the next run. unsafe fn wait_for_submission( dev: &ID3D12Device, queue: &ID3D12CommandQueue, fence: &ID3D12Fence, value: u64, stage: &str, ) -> Result<(), String> { - queue.Signal(fence, value).map_err(|e| format!("{stage}: {}", fence::api_error(dev, "Signal", e)))?; - fence::wait(fence, value, dev, None, 10_000).map_err(|e| format!("{stage}: {e}")) + let r = queue + .Signal(fence, value) + .map_err(|x| format!("{stage}: {}", fence::api_error(dev, "Signal", x))) + .and_then(|()| fence::wait(fence, value, dev, None, 10_000).map_err(|x| format!("{stage}: {x}"))); + if r.is_err() { + if let Ok(d5) = dev.cast::() { + d5.RemoveDevice(); + } + } + r +} + +/// The GPU lock; a test that panicked while holding it does not poison the following ones. +fn lock_gpu() -> std::sync::MutexGuard<'static, Option>> { + GPU.lock().unwrap_or_else(|p| p.into_inner()) +} + +/// Run `f` on the shared GPU (created on first use). If `f` fails and the device was +/// removed (TDR, timeout), the cached device is dropped so the next call creates a new one. +fn with_gpu(f: impl FnOnce(&mut Gpu) -> Result) -> Result { + let mut g = lock_gpu(); + let r = match g.get_or_insert_with(init) { + Ok(gpu) => f(gpu), + Err(x) => return Err(x.clone()), + }; + if r.is_err() { + let removed = matches!((*g).as_ref(), Some(Ok(gpu)) if unsafe { gpu.dev.GetDeviceRemovedReason() }.is_err()); + if removed { + *g = None; + } + } + r } fn init() -> Result { unsafe { - let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(e)?; + let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(werr)?; // `XCL_ADAPTER` picks the adapter (default: the first in high-performance order) let sel = crate::gpu::adapter::Selector::from_env_or("auto"); let (adapter, name): (IDXGIAdapter1, String) = if sel == crate::gpu::adapter::Selector::Warp { - (factory.EnumWarpAdapter().map_err(e)?, "WARP (software renderer)".into()) + (factory.EnumWarpAdapter().map_err(werr)?, "WARP (software renderer)".into()) } else { let (a, desc) = crate::gpu::adapter::candidates(&factory, &sel) .into_iter() @@ -97,7 +131,7 @@ fn init() -> Result { .ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; (a, crate::gpu::adapter::name(&desc)) }; - let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(e)?; + let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(werr)?; let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { HighestShaderModel: D3D_SHADER_MODEL_6_6 }; dev.CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &mut sm as *mut _ as _, std::mem::size_of_val(&sm) as u32) .map_err(|x| format!("SM 6.6: {x}"))?; @@ -105,7 +139,7 @@ fn init() -> Result { return Err(crate::gpu::agility::format_no_sm66_message(&name, crate::gpu::agility::state())); } let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); - dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &mut o1 as *mut _ as _, std::mem::size_of_val(&o1) as u32).map_err(e)?; + dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &mut o1 as *mut _ as _, std::mem::size_of_val(&o1) as u32).map_err(werr)?; if !o1.WaveOps.as_bool() || !o1.Int64ShaderOps.as_bool() { return Err(format!("{name}: no wave operations/int64")); } @@ -115,9 +149,9 @@ fn init() -> Result { let mesh = dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &mut o7 as *mut _ as _, std::mem::size_of_val(&o7) as u32).is_ok() && o7.MeshShaderTier.0 >= D3D12_MESH_SHADER_TIER_1.0; let queue: ID3D12CommandQueue = - dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?; + dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(werr)?; let rs = root_signature(&dev, false)?; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(werr)?; Ok(Gpu { dev, queue, rs, fence, value: 0, adapter: name, wave64, wave32, mesh }) } } @@ -166,6 +200,16 @@ struct Bound { /// Create the descriptor heaps (always, so the directly indexed root signature is valid), /// the test textures and samplers; record the uploads into `list`. unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, textures: &[TestTexture], samplers: &[TestSampler]) -> Result { + // an Err rather than a slice panic below (with the GPU lock held) + for (i, t) in textures.iter().enumerate() { + let need = t.width as usize * t.height as usize * t.depth as usize * t.texel_bytes as usize; + if t.data.len() < need { + return Err(format!("test texture {i}: {} bytes of data, {need} needed ({}×{}×{} × {} bytes)", t.data.len(), t.width, t.height, t.depth, t.texel_bytes)); + } + if t.dim == TexDim::Cube && t.depth % 6 != 0 { + return Err(format!("test texture {i}: cube with depth {} (a multiple of 6 needed)", t.depth)); + } + } let n = (2 * textures.len()).max(2) as u32; let heap: ID3D12DescriptorHeap = dev .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { @@ -174,7 +218,7 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }) - .map_err(e)?; + .map_err(werr)?; let sheap: ID3D12DescriptorHeap = dev .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, @@ -182,7 +226,7 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }) - .map_err(e)?; + .map_err(werr)?; let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; let sinc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; let at = |h: &ID3D12DescriptorHeap, k: usize, step: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h.GetCPUDescriptorHandleForHeapStart().ptr + k * step }; @@ -234,7 +278,7 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t let mut out = Vec::new(); if let Some(up) = &upload { let mut p = std::ptr::null_mut(); - up.Map(0, None, Some(&mut p)).map_err(e)?; + up.Map(0, None, Some(&mut p)).map_err(werr)?; for (t, fps) in textures.iter().zip(&plans) { let row = (t.width * t.texel_bytes) as usize; let slices = t.depth as usize; @@ -254,7 +298,7 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t for (i, ((t, rd), fps)) in textures.iter().zip(&descs).zip(&plans).enumerate() { let mut r: Option = None; dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, rd, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut r) - .map_err(e)?; + .map_err(werr)?; let r = r.ok_or("texture")?; for (k, fp) in fps.iter().enumerate() { let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 } }; @@ -326,7 +370,7 @@ fn buffer(dev: &ID3D12Device, size: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RES let mut r: Option = None; unsafe { dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r) - .map_err(e)?; + .map_err(werr)?; } r.ok_or_else(|| "buffer".into()) } @@ -348,15 +392,11 @@ fn transition(r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RE /// Name of the GPU the kernels run on (None: no usable GPU). pub fn adapter() -> Result { - let mut g = GPU.lock().unwrap(); - let gpu = g.get_or_insert_with(init); - gpu.as_ref().map(|x| x.adapter.clone()).map_err(|x| x.clone()) + with_gpu(|g| Ok(g.adapter.clone())) } pub fn wave64_supported() -> Result { - let mut g = GPU.lock().unwrap(); - let gpu = g.get_or_insert_with(init); - gpu.as_ref().map(|x| x.wave64).map_err(|x| x.clone()) + with_gpu(|g| Ok(g.wave64)) } /// Whether wave64 programs need the split form here (`Options::split_wave64`): the @@ -367,9 +407,7 @@ pub fn split_wave64() -> bool { /// Whether wave64 programs run on this adapter at all: natively (64-lane waves) or split (32). pub fn wave64_programs_supported() -> Result { - let mut g = GPU.lock().unwrap(); - let gpu = g.get_or_insert_with(init); - gpu.as_ref().map(|x| x.wave64 || x.wave32).map_err(|x| x.clone()) + with_gpu(|g| Ok(g.wave64 || g.wave32)) } /// Whether a wave64 VS / PS may run in 32-lane waves here (`pso::graphics_wave32`): the @@ -378,8 +416,7 @@ pub fn graphics_wave32() -> bool { if split_wave64() { return true; } - let mut g = GPU.lock().unwrap(); - g.get_or_insert_with(init).as_ref().is_ok_and(|x| x.wave32) + with_gpu(|g| Ok(g.wave32)).unwrap_or(false) } /// The split flag for a program of `mode` on this adapter: `graphics_wave32` for a VS / PS, @@ -415,9 +452,7 @@ fn split_halves_agree(raw: &[u32]) -> Result<(), String> { /// Whether the adapter runs mesh shaders (`mesh_draw`); an integrated RDNA2 GPU, for one, /// reports wave64 but no mesh shader tier. pub fn mesh_shaders_supported() -> Result { - let mut g = GPU.lock().unwrap(); - let gpu = g.get_or_insert_with(init); - gpu.as_ref().map(|x| x.mesh).map_err(|x| x.clone()) + with_gpu(|g| Ok(g.mesh)) } /// A GPU test (or a part of one) that cannot run here, `reason` one of "no GPU", "no DXC", @@ -441,6 +476,19 @@ pub fn skip_test(reason: &str) { let _ = writeln!(std::io::stderr(), "SKIPPED {test}: {reason}"); } +/// u0 of a kernel run: SGPRs (SCC in its slot), then every lane's VGPRs. +fn pack_io(state: &KernelState) -> Vec { + let mut io: Vec = state.sgpr.clone(); + io.resize(KERNEL_SGPRS, 0); + io[KERNEL_SCC_SLOT] = state.scc; + for lane in 0..KERNEL_LANES { + let mut regs = state.vgpr.get(lane).cloned().unwrap_or_default(); + regs.resize(KERNEL_VGPRS, 0); + io.extend_from_slice(®s); + } + io +} + /// Run a compiled kernel (DXIL) with `state` and flat memory `mem`. pub fn run(dxil: &[u8], state: &KernelState, mem: &[u32]) -> Result { run_with(dxil, state, mem, &[], &[]) @@ -460,118 +508,108 @@ pub fn run_with_statics( samplers: &[TestSampler], statics: &[super::pso::StaticSampler], ) -> Result { - let mut g = GPU.lock().unwrap(); - let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?; - let rs: ID3D12RootSignature = if statics.is_empty() { gpu.rs.clone() } else { super::pso::abi_root_signature_with(&gpu.dev, false, statics)? }; - let mut io: Vec = state.sgpr.clone(); - io.resize(KERNEL_SGPRS, 0); - io[KERNEL_SCC_SLOT] = state.scc; - for lane in 0..KERNEL_LANES { - let mut regs = state.vgpr.get(lane).cloned().unwrap_or_default(); - regs.resize(KERNEL_VGPRS, 0); - io.extend_from_slice(®s); - } - let mem_len = mem.len().max(64); - unsafe { - let dev = &gpu.dev; - let pso: ID3D12PipelineState = dev - .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: transmute_copy(&rs), - CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, - ..Default::default() - }) - .map_err(|x| format!("CreateComputePipelineState: {x}"))?; - let io_bytes = (io.len() * 4) as u64; - let res_bytes = (KERNEL_RES_DWORDS * 4) as u64; - let mem_bytes = (mem_len * 4) as u64; - let upload = buffer(dev, io_bytes + mem_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; - let io_buf = buffer(dev, io_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; - let mem_buf = buffer(dev, mem_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; - let res_buf = buffer(dev, res_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; - let readback = buffer(dev, res_bytes + mem_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; - let mut p = std::ptr::null_mut(); - upload.Map(0, None, Some(&mut p)).map_err(e)?; - std::ptr::copy_nonoverlapping(io.as_ptr(), p as *mut u32, io.len()); - let mut m = mem.to_vec(); - m.resize(mem_len, 0); - std::ptr::copy_nonoverlapping(m.as_ptr(), (p as *mut u32).add(io.len()), m.len()); - upload.Unmap(0, None); - - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).map_err(e)?; - list.CopyBufferRegion(&io_buf, 0, &upload, 0, io_bytes); - list.CopyBufferRegion(&mem_buf, 0, &upload, io_bytes, mem_bytes); - list.ResourceBarrier(&[ - transition(&io_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - transition(&mem_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - ]); - let bound = bind_resources(dev, &list, textures, samplers)?; - list.SetComputeRootSignature(&rs); - list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); - list.Dispatch(1, 1, 1); - list.ResourceBarrier(&[ - transition(&res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition(&mem_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), - ]); - list.CopyBufferRegion(&readback, 0, &res_buf, 0, res_bytes); - list.CopyBufferRegion(&readback, res_bytes, &mem_buf, 0, mem_bytes); - // UAV textures back for checks - let mut tex_back = Vec::new(); - for (i, t) in textures.iter().enumerate() { - if !t.uav { - continue; - } - let (r, fps, size) = &bound.textures[i]; - let rb = buffer(dev, *size, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; - list.ResourceBarrier(&[transition(r, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); - for (k, fp) in fps.iter().enumerate() { - let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } }; - let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 } }; - list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + with_gpu(|gpu| { + let rs: ID3D12RootSignature = if statics.is_empty() { gpu.rs.clone() } else { super::pso::abi_root_signature_with(&gpu.dev, false, statics)? }; + let io = pack_io(state); + let mem_len = mem.len().max(64); + unsafe { + let dev = &gpu.dev; + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }) + .map_err(|x| format!("CreateComputePipelineState: {x}"))?; + let io_bytes = (io.len() * 4) as u64; + let res_bytes = (KERNEL_RES_DWORDS * 4) as u64; + let mem_bytes = (mem_len * 4) as u64; + let upload = buffer(dev, io_bytes + mem_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; + let io_buf = buffer(dev, io_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; + let mem_buf = buffer(dev, mem_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; + let res_buf = buffer(dev, res_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; + let readback = buffer(dev, res_bytes + mem_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).map_err(werr)?; + std::ptr::copy_nonoverlapping(io.as_ptr(), p as *mut u32, io.len()); + let mut m = mem.to_vec(); + m.resize(mem_len, 0); + std::ptr::copy_nonoverlapping(m.as_ptr(), (p as *mut u32).add(io.len()), m.len()); + upload.Unmap(0, None); + + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(werr)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).map_err(werr)?; + list.CopyBufferRegion(&io_buf, 0, &upload, 0, io_bytes); + list.CopyBufferRegion(&mem_buf, 0, &upload, io_bytes, mem_bytes); + list.ResourceBarrier(&[ + transition(&io_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + transition(&mem_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]); + let bound = bind_resources(dev, &list, textures, samplers)?; + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[ + transition(&res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(&mem_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + ]); + list.CopyBufferRegion(&readback, 0, &res_buf, 0, res_bytes); + list.CopyBufferRegion(&readback, res_bytes, &mem_buf, 0, mem_bytes); + // UAV textures back for checks + let mut tex_back = Vec::new(); + for (i, t) in textures.iter().enumerate() { + if !t.uav { + continue; + } + let (r, fps, size) = &bound.textures[i]; + let rb = buffer(dev, *size, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; + list.ResourceBarrier(&[transition(r, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + for (k, fp) in fps.iter().enumerate() { + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + tex_back.push((i, rb)); } - tex_back.push((i, rb)); - } - list.Close().map_err(e)?; - gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); - gpu.value += 1; - wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "kernel dispatch")?; - let mut p = std::ptr::null_mut(); - readback.Map(0, None, Some(&mut p)).map_err(e)?; - let raw = std::slice::from_raw_parts(p as *const u32, KERNEL_RES_DWORDS).to_vec(); - let mem_out = std::slice::from_raw_parts((p as *const u32).add(KERNEL_RES_DWORDS), mem_len).to_vec(); - readback.Unmap(0, None); - let mut tex_out = Vec::new(); - for (i, rb) in &tex_back { - let t = &textures[*i]; - let (_, fps, _) = &bound.textures[*i]; - let mut q = std::ptr::null_mut(); - rb.Map(0, None, Some(&mut q)).map_err(e)?; - let row = (t.width * t.texel_bytes) as usize; - let mut v = Vec::new(); - for z in 0..t.depth as usize { - let fp = if t.dim == TexDim::D3 { &fps[0] } else { &fps[z] }; - let zoff = if t.dim == TexDim::D3 { z * fp.Footprint.RowPitch as usize * t.height as usize } else { 0 }; - for y in 0..t.height as usize { - let s = std::slice::from_raw_parts((q as *const u8).add(fp.Offset as usize + zoff + y * fp.Footprint.RowPitch as usize), row); - v.extend_from_slice(s); + list.Close().map_err(werr)?; + gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(werr)?)]); + gpu.value += 1; + wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "kernel dispatch")?; + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).map_err(werr)?; + let raw = std::slice::from_raw_parts(p as *const u32, KERNEL_RES_DWORDS).to_vec(); + let mem_out = std::slice::from_raw_parts((p as *const u32).add(KERNEL_RES_DWORDS), mem_len).to_vec(); + readback.Unmap(0, None); + let mut tex_out = Vec::new(); + for (i, rb) in &tex_back { + let t = &textures[*i]; + let (_, fps, _) = &bound.textures[*i]; + let mut q = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut q)).map_err(werr)?; + let row = (t.width * t.texel_bytes) as usize; + let mut v = Vec::new(); + for z in 0..t.depth as usize { + let fp = if t.dim == TexDim::D3 { &fps[0] } else { &fps[z] }; + let zoff = if t.dim == TexDim::D3 { z * fp.Footprint.RowPitch as usize * t.height as usize } else { 0 }; + for y in 0..t.height as usize { + let s = std::slice::from_raw_parts((q as *const u8).add(fp.Offset as usize + zoff + y * fp.Footprint.RowPitch as usize), row); + v.extend_from_slice(s); + } } + rb.Unmap(0, None); + tex_out.push(v); } - rb.Unmap(0, None); - tex_out.push(v); + let vgpr = (0..KERNEL_LANES) + .map(|l| raw[KERNEL_SGPRS + l * KERNEL_VGPRS..KERNEL_SGPRS + (l + 1) * KERNEL_VGPRS].to_vec()) + .collect(); + drop(bound); + split_halves_agree(&raw)?; + Ok(KernelResult { sgpr: raw[..KERNEL_SGPRS].to_vec(), vgpr, scc: raw[KERNEL_SCC_SLOT], raw, mem: mem_out, textures: tex_out }) } - let mut p = std::ptr::null_mut(); - readback.Map(0, None, Some(&mut p)).map_err(e)?; - readback.Unmap(0, None); - let vgpr = (0..KERNEL_LANES) - .map(|l| raw[KERNEL_SGPRS + l * KERNEL_VGPRS..KERNEL_SGPRS + (l + 1) * KERNEL_VGPRS].to_vec()) - .collect(); - drop(bound); - split_halves_agree(&raw)?; - Ok(KernelResult { sgpr: raw[..KERNEL_SGPRS].to_vec(), vgpr, scc: raw[KERNEL_SCC_SLOT], raw, mem: mem_out, textures: tex_out }) - } + }) } /// Run a whole console program: its code region is also placed in `mem` at address 0, @@ -600,13 +638,8 @@ pub fn run_code_with(code: &[u8], state: &KernelState, mem: &[u32], textures: &[ /// Translate + compile + run RDNA2 code as a kernel. pub fn run_code(code: &[u8], state: &KernelState, mem: &[u32]) -> Result { - let opt = options(super::Mode::Kernel); - let t = super::translate(code, &opt)?; - if !t.complete() { - return Err(format!("unsupported instructions: {:?}", t.unsupported)); - } - let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|x| format!("{x}\n--- HLSL ---\n{}", t.hlsl))?; - run(&dxil, state, mem) + // through run_code_with: a kernel with static samplers needs their root signature + run_code_with(code, state, mem, &[], &[]) } /// One vertex input element: (semantic name, index, format, byte offset). @@ -684,46 +717,46 @@ fn draw_gs_views( size: u32, clear: [f32; 4], ) -> Result, String> { - let mut g = GPU.lock().unwrap(); - let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?; - unsafe { - let dev = &gpu.dev; - let rs = root_signature(dev, true)?; - let names: Vec = layout.iter().map(|l| std::ffi::CString::new(l.semantic).unwrap()).collect(); - let elems: Vec = layout - .iter() - .zip(&names) - .map(|(l, n)| D3D12_INPUT_ELEMENT_DESC { - SemanticName: windows::core::PCSTR(n.as_ptr() as *const u8), - SemanticIndex: l.index, - Format: l.format, - InputSlot: 0, - AlignedByteOffset: l.offset, - InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, - InstanceDataStepRate: 0, - }) - .collect(); - let mut pd = D3D12_GRAPHICS_PIPELINE_STATE_DESC { - pRootSignature: transmute_copy(&rs), - VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as _, BytecodeLength: vs.len() }, - PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() }, - GS: gs.map_or_else(D3D12_SHADER_BYTECODE::default, |g| D3D12_SHADER_BYTECODE { pShaderBytecode: g.as_ptr() as _, BytecodeLength: g.len() }), - SampleMask: u32::MAX, - InputLayout: D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elems.as_ptr(), NumElements: elems.len() as u32 }, - PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, - NumRenderTargets: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - ..Default::default() - }; - pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; - pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; - pd.RasterizerState.DepthClipEnable = true.into(); - pd.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; - let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).map_err(|x| format!("CreateGraphicsPipelineState: {x}"))?; - let draw = Draw { sgprs: sgprs.to_vec(), scissor: [0, 0, size as i32, size as i32] }; - draw_on_multi(dev, &pso, &rs, vertices, stride, &[draw], mem, textures, samplers, size, clear) - } + with_gpu(|gpu| { + unsafe { + let dev = &gpu.dev; + let rs = root_signature(dev, true)?; + let names: Vec = layout.iter().map(|l| std::ffi::CString::new(l.semantic).unwrap()).collect(); + let elems: Vec = layout + .iter() + .zip(&names) + .map(|(l, n)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: windows::core::PCSTR(n.as_ptr() as *const u8), + SemanticIndex: l.index, + Format: l.format, + InputSlot: 0, + AlignedByteOffset: l.offset, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + InstanceDataStepRate: 0, + }) + .collect(); + let mut pd = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as _, BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() }, + GS: gs.map_or_else(D3D12_SHADER_BYTECODE::default, |g| D3D12_SHADER_BYTECODE { pShaderBytecode: g.as_ptr() as _, BytecodeLength: g.len() }), + SampleMask: u32::MAX, + InputLayout: D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elems.as_ptr(), NumElements: elems.len() as u32 }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = true.into(); + pd.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).map_err(|x| format!("CreateGraphicsPipelineState: {x}"))?; + let draw = Draw { sgprs: sgprs.to_vec(), scissor: [0, 0, size as i32, size as i32] }; + draw_on_multi(dev, &pso, &rs, vertices, stride, &[draw], mem, textures, samplers, size, clear) + } + }) } /// Render with an existing graphics pipeline on `dev` (its own queue): vertex buffer @@ -772,7 +805,7 @@ unsafe fn bind_views(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, textu Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }) - .map_err(e)?; + .map_err(werr)?; let sheap: ID3D12DescriptorHeap = dev .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, @@ -780,14 +813,14 @@ unsafe fn bind_views(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, textu Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }) - .map_err(e)?; + .map_err(werr)?; let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; let sinc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; let at = |h: &ID3D12DescriptorHeap, k: usize, step: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h.GetCPUDescriptorHandleForHeapStart().ptr + k * step }; for (j, sd) in samplers.iter().enumerate() { dev.CreateSampler(sd, at(&sheap, j, sinc)); } - let mut keep: Vec = vec![heap.cast().map_err(e)?, sheap.cast().map_err(e)?]; + let mut keep: Vec = vec![heap.cast().map_err(werr)?, sheap.cast().map_err(werr)?]; for (i, t) in textures.iter().enumerate() { let levels = t.res.MipLevels.max(1) as usize; let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); levels]; @@ -795,7 +828,7 @@ unsafe fn bind_views(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, textu dev.GetCopyableFootprints(&t.res, 0, levels as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), None, Some(&mut total)); let up = buffer(dev, total, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; let mut p = std::ptr::null_mut(); - up.Map(0, None, Some(&mut p)).map_err(e)?; + up.Map(0, None, Some(&mut p)).map_err(werr)?; let texel = t.row_bytes / (t.res.Width as usize).max(1); let mut offset = 0usize; for (k, fp) in fps.iter().enumerate() { @@ -819,8 +852,8 @@ unsafe fn bind_views(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, textu } list.ResourceBarrier(&[transition(&r, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)]); dev.CreateShaderResourceView(&r, Some(&t.srv), at(&heap, 2 * i, inc)); - keep.push(r.cast().map_err(e)?); - keep.push(up.cast().map_err(e)?); + keep.push(r.cast().map_err(werr)?); + keep.push(up.cast().map_err(werr)?); } list.SetDescriptorHeaps(&[Some(heap), Some(sheap)]); Ok(keep) @@ -845,8 +878,8 @@ pub fn draw_on_multi( ) -> Result, String> { unsafe { let queue: ID3D12CommandQueue = - dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; + dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(werr)?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(werr)?; let tex = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, @@ -869,11 +902,11 @@ pub fn draw_on_multi( Some(&cv), &mut rt, ) - .map_err(e)?; + .map_err(werr)?; let rt = rt.ok_or("render target")?; let heap: ID3D12DescriptorHeap = dev .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }) - .map_err(e)?; + .map_err(werr)?; let rtv = heap.GetCPUDescriptorHandleForHeapStart(); dev.CreateRenderTargetView(&rt, None, rtv); @@ -891,7 +924,7 @@ pub fn draw_on_multi( let mem_bytes = (mem_len * 4) as u64; let upload = buffer(dev, vb_bytes + io_bytes + mem_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; let mut p = std::ptr::null_mut(); - upload.Map(0, None, Some(&mut p)).map_err(e)?; + upload.Map(0, None, Some(&mut p)).map_err(werr)?; std::ptr::copy_nonoverlapping(vertices.as_ptr() as *const u32, p as *mut u32, vertices.len()); std::ptr::copy_nonoverlapping(io.as_ptr(), (p as *mut u32).add(vertices.len()), io.len()); let mut m = mem.to_vec(); @@ -907,8 +940,8 @@ pub fn draw_on_multi( dev.GetCopyableFootprints(&tex, 0, 1, 0, Some(&mut layout_fp), None, None, Some(&mut total)); let readback = buffer(dev, total, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, pso).map_err(e)?; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(werr)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, pso).map_err(werr)?; list.CopyBufferRegion(&io_buf, 0, &upload, vb_bytes, io_bytes); list.CopyBufferRegion(&mem_buf, 0, &upload, vb_bytes + io_bytes, mem_bytes); list.ResourceBarrier(&[ @@ -919,8 +952,9 @@ pub fn draw_on_multi( list.OMSetRenderTargets(1, Some(&rtv), false, None); list.ClearRenderTargetView(rtv, &clear, None); list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: size as f32, Height: size as f32, MinDepth: 0.0, MaxDepth: 1.0 }]); - list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left: 0, top: 0, right: size as i32, bottom: size as i32 }]); - let _bound = if textures.is_empty() && samplers.is_empty() { bind_resources(dev, &list, &[], &[]).map(|_| Vec::new())? } else { bind_views(dev, &list, textures, samplers)? }; + // the heaps must outlive the GPU work: SetDescriptorHeaps holds no reference + let _heaps: Box = + if textures.is_empty() && samplers.is_empty() { Box::new(bind_resources(dev, &list, &[], &[])?) } else { Box::new(bind_views(dev, &list, textures, samplers)?) }; list.SetGraphicsRootSignature(rs); list.SetGraphicsRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); list.SetGraphicsRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); @@ -946,11 +980,11 @@ pub fn draw_on_multi( Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, }; list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); - list.Close().map_err(e)?; - queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); + list.Close().map_err(werr)?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(werr)?)]); wait_for_submission(dev, &queue, &fence, 1, "draw")?; let mut p = std::ptr::null_mut(); - readback.Map(0, None, Some(&mut p)).map_err(e)?; + readback.Map(0, None, Some(&mut p)).map_err(werr)?; let pitch = layout_fp.Footprint.RowPitch as usize; let mut px = Vec::with_capacity((size * size) as usize); for y in 0..size as usize { @@ -1025,301 +1059,293 @@ pub fn mesh_draw_split( size: u32, clear: [f32; 4], ) -> Result<(Vec<[f32; 4]>, Vec), String> { - let mut g = GPU.lock().unwrap(); - let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?; - unsafe { - let dev = &gpu.dev; - let cpso: ID3D12PipelineState = dev - .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: transmute_copy(&gpu.rs), - CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as _, BytecodeLength: cs.len() }, + with_gpu(|gpu| { + unsafe { + let dev = &gpu.dev; + let cpso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&gpu.rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as _, BytecodeLength: cs.len() }, + ..Default::default() + }) + .map_err(|x| format!("CreateComputePipelineState: {x}"))?; + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + let rast = D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() }; + let mut rtv_formats = D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 1, ..Default::default() }; + rtv_formats.RTFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + let mut stream = MeshStream { + rs: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, v: gpu.rs.as_raw() }, + ms: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, v: D3D12_SHADER_BYTECODE { pShaderBytecode: ms.as_ptr() as _, BytecodeLength: ms.len() } }, + ps: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, v: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() } }, + blend: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, v: blend }, + mask: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, v: u32::MAX }, + rast: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, v: rast }, + depth: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, v: D3D12_DEPTH_STENCIL_DESC::default() }, + rtv: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, v: rtv_formats }, + samples: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, v: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 } }, + }; + let dev2: ID3D12Device2 = dev.cast().map_err(werr)?; + let mpso: ID3D12PipelineState = dev2 + .CreatePipelineState(&D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: std::mem::size_of::(), + pPipelineStateSubobjectStream: &mut stream as *mut MeshStream as *mut std::ffi::c_void, + }) + .map_err(|x| format!("CreatePipelineState (mesh): {x}"))?; + + let tex = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: size as u64, + Height: size, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, ..Default::default() - }) - .map_err(|x| format!("CreateComputePipelineState: {x}"))?; - let mut blend = D3D12_BLEND_DESC::default(); - blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; - let rast = D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() }; - let mut rtv_formats = D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 1, ..Default::default() }; - rtv_formats.RTFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; - let mut stream = MeshStream { - rs: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, v: gpu.rs.as_raw() }, - ms: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, v: D3D12_SHADER_BYTECODE { pShaderBytecode: ms.as_ptr() as _, BytecodeLength: ms.len() } }, - ps: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, v: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() } }, - blend: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, v: blend }, - mask: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, v: u32::MAX }, - rast: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, v: rast }, - depth: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, v: D3D12_DEPTH_STENCIL_DESC::default() }, - rtv: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, v: rtv_formats }, - samples: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, v: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 } }, - }; - let dev2: ID3D12Device2 = dev.cast().map_err(e)?; - let mpso: ID3D12PipelineState = dev2 - .CreatePipelineState(&D3D12_PIPELINE_STATE_STREAM_DESC { - SizeInBytes: std::mem::size_of::(), - pPipelineStateSubobjectStream: &mut stream as *mut MeshStream as *mut std::ffi::c_void, - }) - .map_err(|x| format!("CreatePipelineState (mesh): {x}"))?; - - let tex = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width: size as u64, - Height: size, - DepthOrArraySize: 1, - MipLevels: 1, - Format: DXGI_FORMAT_R32G32B32A32_FLOAT, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, - ..Default::default() - }; - let cv = D3D12_CLEAR_VALUE { Format: DXGI_FORMAT_R32G32B32A32_FLOAT, Anonymous: D3D12_CLEAR_VALUE_0 { Color: clear } }; - let mut rt: Option = None; - dev.CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, - D3D12_HEAP_FLAG_NONE, - &tex, - D3D12_RESOURCE_STATE_RENDER_TARGET, - Some(&cv), - &mut rt, - ) - .map_err(e)?; - let rt = rt.ok_or("render target")?; - let heap: ID3D12DescriptorHeap = dev - .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }) - .map_err(e)?; - let rtv = heap.GetCPUDescriptorHandleForHeapStart(); - dev.CreateRenderTargetView(&rt, None, rtv); - - let mut io = sgprs.to_vec(); - io.resize(KERNEL_SGPRS, 0); - let io_bytes = (io.len() * 4) as u64; - let mem_len = mem.len().max(64); - let mem_bytes = (mem_len * 4) as u64; - let res_len = record_dwords * groups as usize; - let res_bytes = (res_len * 4) as u64; - let upload = buffer(dev, io_bytes + mem_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; - let mut p = std::ptr::null_mut(); - upload.Map(0, None, Some(&mut p)).map_err(e)?; - std::ptr::copy_nonoverlapping(io.as_ptr(), p as *mut u32, io.len()); - let mut m = mem.to_vec(); - m.resize(mem_len, 0); - std::ptr::copy_nonoverlapping(m.as_ptr(), (p as *mut u32).add(io.len()), m.len()); - upload.Unmap(0, None); - let io_buf = buffer(dev, io_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; - let mem_buf = buffer(dev, mem_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; - let res_buf = buffer(dev, res_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; - let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); - let mut total = 0u64; - dev.GetCopyableFootprints(&tex, 0, 1, 0, Some(&mut fp), None, None, Some(&mut total)); - let readback = buffer(dev, total + res_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; - - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &cpso).map_err(e)?; - list.CopyBufferRegion(&io_buf, 0, &upload, 0, io_bytes); - list.CopyBufferRegion(&mem_buf, 0, &upload, io_bytes, mem_bytes); - list.ResourceBarrier(&[ - transition(&io_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - transition(&mem_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - ]); - // pass 1: the console program as a compute shader - let _bound = bind_resources(dev, &list, &[], &[])?; - list.SetComputeRootSignature(&gpu.rs); - list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); - list.Dispatch(groups, 1, 1); - list.ResourceBarrier(&[uav_barrier(&res_buf)]); - // pass 2: rasterise the records - list.SetPipelineState(&mpso); - list.SetGraphicsRootSignature(&gpu.rs); - list.SetGraphicsRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); - list.SetGraphicsRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); - list.SetGraphicsRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); - list.OMSetRenderTargets(1, Some(&rtv), false, None); - list.ClearRenderTargetView(rtv, &clear, None); - list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: size as f32, Height: size as f32, MinDepth: 0.0, MaxDepth: 1.0 }]); - list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left: 0, top: 0, right: size as i32, bottom: size as i32 }]); - let list6: ID3D12GraphicsCommandList6 = list.cast().map_err(e)?; - list6.DispatchMesh(groups * split, 1, 1); - list.ResourceBarrier(&[ - transition(&rt, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition(&res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), - ]); - let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; - let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&rt), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; - list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); - list.CopyBufferRegion(&readback, total, &res_buf, 0, res_bytes); - list.Close().map_err(e)?; - gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); - gpu.value += 1; - wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "mesh draw")?; - let mut q = std::ptr::null_mut(); - readback.Map(0, None, Some(&mut q)).map_err(e)?; - let pitch = fp.Footprint.RowPitch as usize; - let mut px = Vec::with_capacity((size * size) as usize); - for y in 0..size as usize { - for x in 0..size as usize { - let c = (q as *const u8).add(y * pitch + x * 16) as *const f32; - px.push([*c, *c.add(1), *c.add(2), *c.add(3)]); + }; + let cv = D3D12_CLEAR_VALUE { Format: DXGI_FORMAT_R32G32B32A32_FLOAT, Anonymous: D3D12_CLEAR_VALUE_0 { Color: clear } }; + let mut rt: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &tex, + D3D12_RESOURCE_STATE_RENDER_TARGET, + Some(&cv), + &mut rt, + ) + .map_err(werr)?; + let rt = rt.ok_or("render target")?; + let heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }) + .map_err(werr)?; + let rtv = heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&rt, None, rtv); + + let mut io = sgprs.to_vec(); + io.resize(KERNEL_SGPRS, 0); + let io_bytes = (io.len() * 4) as u64; + let mem_len = mem.len().max(64); + let mem_bytes = (mem_len * 4) as u64; + let res_len = record_dwords * groups as usize; + let res_bytes = (res_len * 4) as u64; + let upload = buffer(dev, io_bytes + mem_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).map_err(werr)?; + std::ptr::copy_nonoverlapping(io.as_ptr(), p as *mut u32, io.len()); + let mut m = mem.to_vec(); + m.resize(mem_len, 0); + std::ptr::copy_nonoverlapping(m.as_ptr(), (p as *mut u32).add(io.len()), m.len()); + upload.Unmap(0, None); + let io_buf = buffer(dev, io_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; + let mem_buf = buffer(dev, mem_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; + let res_buf = buffer(dev, res_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + dev.GetCopyableFootprints(&tex, 0, 1, 0, Some(&mut fp), None, None, Some(&mut total)); + let readback = buffer(dev, total + res_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; + + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(werr)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &cpso).map_err(werr)?; + list.CopyBufferRegion(&io_buf, 0, &upload, 0, io_bytes); + list.CopyBufferRegion(&mem_buf, 0, &upload, io_bytes, mem_bytes); + list.ResourceBarrier(&[ + transition(&io_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + transition(&mem_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]); + // pass 1: the console program as a compute shader + let _bound = bind_resources(dev, &list, &[], &[])?; + list.SetComputeRootSignature(&gpu.rs); + list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); + list.Dispatch(groups, 1, 1); + list.ResourceBarrier(&[uav_barrier(&res_buf)]); + // pass 2: rasterise the records + list.SetPipelineState(&mpso); + list.SetGraphicsRootSignature(&gpu.rs); + list.SetGraphicsRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); + list.SetGraphicsRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); + list.SetGraphicsRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.ClearRenderTargetView(rtv, &clear, None); + list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: size as f32, Height: size as f32, MinDepth: 0.0, MaxDepth: 1.0 }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left: 0, top: 0, right: size as i32, bottom: size as i32 }]); + let list6: ID3D12GraphicsCommandList6 = list.cast().map_err(werr)?; + list6.DispatchMesh(groups * split, 1, 1); + list.ResourceBarrier(&[ + transition(&rt, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(&res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + ]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&rt), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.CopyBufferRegion(&readback, total, &res_buf, 0, res_bytes); + list.Close().map_err(werr)?; + gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(werr)?)]); + gpu.value += 1; + wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "mesh draw")?; + let mut q = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut q)).map_err(werr)?; + let pitch = fp.Footprint.RowPitch as usize; + let mut px = Vec::with_capacity((size * size) as usize); + for y in 0..size as usize { + for x in 0..size as usize { + let c = (q as *const u8).add(y * pitch + x * 16) as *const f32; + px.push([*c, *c.add(1), *c.add(2), *c.add(3)]); + } } + let recs = std::slice::from_raw_parts((q as *const u8).add(total as usize) as *const u32, res_len).to_vec(); + readback.Unmap(0, None); + Ok((px, recs)) } - let recs = std::slice::from_raw_parts((q as *const u8).add(total as usize) as *const u32, res_len).to_vec(); - readback.Unmap(0, None); - Ok((px, recs)) - } + }) } -/// Process memory regions for `run_in_region` (see `gpu::uma`): the memory windows. +/// Process memory regions for `run_in_region` (see `gpu::uma`): the memory windows +/// (base, size), borrowed from the `Uma` that owns them. struct Arena { - pub windows: Vec<(*mut u8, usize)>, + windows: Vec<(*mut u8, usize)>, } -unsafe impl Send for Arena {} -unsafe impl Sync for Arena {} - +/// Root UAVs u2.. available for the arena windows (see `pso::abi_root_signature`). +const ARENA_MAX_WINDOWS: usize = 4; /// `run` with a unified memory region as `mem` (u2): the GPU works on the process memory /// itself, no copies. pub fn run_in_arena(dxil: &[u8], state: &KernelState, arena: &crate::gpu::uma::Uma) -> Result { let arena = Arena { windows: (0..arena.windows()).map(|k| (arena.window(k).0 as *mut u8, arena.window(k).1)).collect() }; - let r = run_in_region(dxil, state, &arena); - std::mem::forget(arena); // owned by the Uma - r + run_in_region(dxil, state, &arena) } fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result { - let mut g = GPU.lock().unwrap(); - let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?; - let mut io: Vec = state.sgpr.clone(); - io.resize(KERNEL_SGPRS, 0); - io[KERNEL_SCC_SLOT] = state.scc; - for lane in 0..KERNEL_LANES { - let mut regs = state.vgpr.get(lane).cloned().unwrap_or_default(); - regs.resize(KERNEL_VGPRS, 0); - io.extend_from_slice(®s); - } - unsafe { - let dev = &gpu.dev; - let dev3: ID3D12Device3 = dev.cast().map_err(e)?; - let mut bufs: Vec = Vec::new(); - for &(base, size) in &arena.windows { - let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(base as *const std::ffi::c_void).map_err(|x| format!("OpenExistingHeapFromAddress: {x}"))?; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size as u64, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, - ..Default::default() - }; - let mut mem_buf: Option = None; - dev.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut mem_buf).map_err(|x| format!("CreatePlacedResource: {x}"))?; - bufs.push(mem_buf.ok_or("arena")?); - } - let mem_buf = bufs[0].clone(); - let pso: ID3D12PipelineState = dev - .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: transmute_copy(&gpu.rs), - CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, - ..Default::default() - }) - .map_err(|x| format!("CreateComputePipelineState: {x}"))?; - let io_bytes = (io.len() * 4) as u64; - let res_bytes = (KERNEL_RES_DWORDS * 4) as u64; - let upload = buffer(dev, io_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; - let io_buf = buffer(dev, io_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; - let res_buf = buffer(dev, res_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; - let readback = buffer(dev, res_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; - let mut p = std::ptr::null_mut(); - upload.Map(0, None, Some(&mut p)).map_err(e)?; - std::ptr::copy_nonoverlapping(io.as_ptr(), p as *mut u32, io.len()); - upload.Unmap(0, None); - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).map_err(e)?; - list.CopyBufferRegion(&io_buf, 0, &upload, 0, io_bytes); - list.ResourceBarrier(&[ - transition(&io_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - transition(&mem_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - ]); - for b in &bufs[1..] { - list.ResourceBarrier(&[transition(b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); - } - list.SetComputeRootSignature(&gpu.rs); - list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); - for k in 0..4 { - list.SetComputeRootUnorderedAccessView(2 + k as u32, bufs.get(k).unwrap_or(&mem_buf).GetGPUVirtualAddress()); + with_gpu(|gpu| { + if arena.windows.is_empty() || arena.windows.len() > ARENA_MAX_WINDOWS { + return Err(format!("arena: {} memory windows (1..={ARENA_MAX_WINDOWS} supported)", arena.windows.len())); } - list.Dispatch(1, 1, 1); - list.ResourceBarrier(&[ - transition(&res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition(&mem_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON), - ]); - for b in &bufs[1..] { - list.ResourceBarrier(&[transition(b, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON)]); + let io = pack_io(state); + unsafe { + let dev = &gpu.dev; + let dev3: ID3D12Device3 = dev.cast().map_err(werr)?; + let mut bufs: Vec = Vec::new(); + for &(base, size) in &arena.windows { + let heap: ID3D12Heap = dev3 + .OpenExistingHeapFromAddress(base as *const std::ffi::c_void) + .map_err(|x| format!("OpenExistingHeapFromAddress: {x}"))?; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, + ..Default::default() + }; + let mut b: Option = None; + dev.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut b).map_err(|x| format!("CreatePlacedResource: {x}"))?; + bufs.push(b.ok_or("arena")?); + } + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&gpu.rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }) + .map_err(|x| format!("CreateComputePipelineState: {x}"))?; + let io_bytes = (io.len() * 4) as u64; + let res_bytes = (KERNEL_RES_DWORDS * 4) as u64; + let upload = buffer(dev, io_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; + let io_buf = buffer(dev, io_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; + let res_buf = buffer(dev, res_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; + let readback = buffer(dev, res_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).map_err(werr)?; + std::ptr::copy_nonoverlapping(io.as_ptr(), p as *mut u32, io.len()); + upload.Unmap(0, None); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(werr)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).map_err(werr)?; + list.CopyBufferRegion(&io_buf, 0, &upload, 0, io_bytes); + let mut before = vec![ + transition(&io_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]; + before.extend(bufs.iter().map(|b| transition(b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS))); + list.ResourceBarrier(&before); + // the heaps the directly indexed root signature expects (as in `dispatch_with`) + let _bound = bind_resources(dev, &list, &[], &[])?; + list.SetComputeRootSignature(&gpu.rs); + list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); + // u2..: one root UAV per window; unused slots repeat the first window + for k in 0..ARENA_MAX_WINDOWS { + list.SetComputeRootUnorderedAccessView(2 + k as u32, bufs.get(k).unwrap_or(&bufs[0]).GetGPUVirtualAddress()); + } + list.Dispatch(1, 1, 1); + let mut after = vec![transition(&res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]; + after.extend(bufs.iter().map(|b| transition(b, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON))); + list.ResourceBarrier(&after); + list.CopyBufferRegion(&readback, 0, &res_buf, 0, res_bytes); + list.Close().map_err(werr)?; + gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(werr)?)]); + gpu.value += 1; + wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "arena dispatch")?; + let mut q = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut q)).map_err(werr)?; + let raw = std::slice::from_raw_parts(q as *const u32, KERNEL_RES_DWORDS).to_vec(); + readback.Unmap(0, None); + let vgpr = (0..KERNEL_LANES).map(|l| raw[KERNEL_SGPRS + l * KERNEL_VGPRS..KERNEL_SGPRS + (l + 1) * KERNEL_VGPRS].to_vec()).collect(); + split_halves_agree(&raw)?; + Ok(KernelResult { sgpr: raw[..KERNEL_SGPRS].to_vec(), vgpr, scc: raw[KERNEL_SCC_SLOT], raw, mem: Vec::new(), textures: Vec::new() }) } - list.CopyBufferRegion(&readback, 0, &res_buf, 0, res_bytes); - list.Close().map_err(e)?; - gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); - gpu.value += 1; - wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "arena dispatch")?; - let mut q = std::ptr::null_mut(); - readback.Map(0, None, Some(&mut q)).map_err(e)?; - let raw = std::slice::from_raw_parts(q as *const u32, KERNEL_RES_DWORDS).to_vec(); - readback.Unmap(0, None); - let vgpr = (0..KERNEL_LANES).map(|l| raw[KERNEL_SGPRS + l * KERNEL_VGPRS..KERNEL_SGPRS + (l + 1) * KERNEL_VGPRS].to_vec()).collect(); - split_halves_agree(&raw)?; - Ok(KernelResult { sgpr: raw[..KERNEL_SGPRS].to_vec(), vgpr, scc: raw[KERNEL_SCC_SLOT], raw, mem: Vec::new(), textures: Vec::new() }) - } + }) } /// Create a committed resource from a description (validation of decoded descriptors). pub fn try_create_texture(desc: &D3D12_RESOURCE_DESC) -> Result<(), String> { - let mut g = GPU.lock().unwrap(); - let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?; - let mut r: Option = None; - unsafe { - gpu.dev - .CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r) - .map_err(|x| format!("CreateCommittedResource: {x}")) - } + with_gpu(|gpu| { + let mut r: Option = None; + unsafe { + gpu.dev + .CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r) + .map_err(|x| format!("CreateCommittedResource: {x}")) + } + }) } /// A compute shader with the console dispatch ABI (`Mode::Compute`): `groups` thread groups, /// u0 = user SGPRs, u2 = flat memory. Returns the memory afterwards. pub fn dispatch(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Result, String> { - let mut g = GPU.lock().unwrap(); - let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?; - let pso: ID3D12PipelineState = unsafe { - gpu.dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: transmute_copy(&gpu.rs), - CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, - ..Default::default() - }) - } - .map_err(|x| format!("CreateComputePipelineState: {x}"))?; - dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, 1, false).map(|(m, _)| m) + with_gpu(|gpu| { + let pso: ID3D12PipelineState = unsafe { + gpu.dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&gpu.rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }) + } + .map_err(|x| format!("CreateComputePipelineState: {x}"))?; + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, 1, false).map(|(m, _)| m) + }) } /// `dispatch` run `reps` times in one command list (a UAV barrier between them, memory not /// reset), each between two GPU timestamps: GPU milliseconds per dispatch – no pipeline, /// buffer, upload, submission or CPU wait time in them. For benchmarks. pub fn dispatch_timed(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32], reps: usize) -> Result, String> { - let mut g = GPU.lock().unwrap(); - let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?; - let pso: ID3D12PipelineState = unsafe { - gpu.dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: transmute_copy(&gpu.rs), - CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, - ..Default::default() - }) - } - .map_err(|x| format!("CreateComputePipelineState: {x}"))?; - dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, reps.max(1), true).map(|(_, t)| t) + with_gpu(|gpu| { + let pso: ID3D12PipelineState = unsafe { + gpu.dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&gpu.rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }) + } + .map_err(|x| format!("CreateComputePipelineState: {x}"))?; + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, reps.max(1), true).map(|(_, t)| t) + }) } /// Dispatch with an existing compute pipeline on `dev` (its own queue), e.g. one the D3D12.X @@ -1327,8 +1353,8 @@ pub fn dispatch_timed(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32], /// `sgprs`, u2 = `mem`. Returns the memory afterwards. pub fn dispatch_on(dev: &ID3D12Device, pso: &ID3D12PipelineState, rs: &ID3D12RootSignature, groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Result, String> { unsafe { - let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(werr)?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(werr)?; dispatch_with(dev, &queue, &fence, &mut 0, pso, rs, groups, sgprs, mem, 1, false).map(|(m, _)| m) } } @@ -1354,7 +1380,7 @@ fn dispatch_with( let (io_bytes, mem_bytes) = ((io.len() * 4) as u64, (mem_len * 4) as u64); let upload = buffer(dev, io_bytes + mem_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; let mut p = std::ptr::null_mut(); - upload.Map(0, None, Some(&mut p)).map_err(e)?; + upload.Map(0, None, Some(&mut p)).map_err(werr)?; std::ptr::copy_nonoverlapping(io.as_ptr(), p as *mut u32, io.len()); let mut m = mem.to_vec(); m.resize(mem_len, 0); @@ -1364,8 +1390,8 @@ fn dispatch_with( let mem_buf = buffer(dev, mem_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; let res_buf = buffer(dev, 256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; let readback = buffer(dev, mem_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, pso).map_err(e)?; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(werr)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, pso).map_err(werr)?; list.CopyBufferRegion(&io_buf, 0, &upload, 0, io_bytes); list.CopyBufferRegion(&mem_buf, 0, &upload, io_bytes, mem_bytes); list.ResourceBarrier(&[ @@ -1382,7 +1408,7 @@ fn dispatch_with( let stamps = 2 * reps as u32; let queries = if timed { let mut h: Option = None; - dev.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: stamps, NodeMask: 0 }, &mut h).map_err(e)?; + dev.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: stamps, NodeMask: 0 }, &mut h).map_err(werr)?; let heap = h.ok_or("CreateQueryHeap")?; let out = buffer(dev, stamps as u64 * 8, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; Some((heap, out)) @@ -1406,19 +1432,19 @@ fn dispatch_with( } list.ResourceBarrier(&[transition(&mem_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); list.CopyBufferRegion(&readback, 0, &mem_buf, 0, mem_bytes); - list.Close().map_err(e)?; - queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); + list.Close().map_err(werr)?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(werr)?)]); *value += 1; wait_for_submission(dev, queue, fence, *value, "compute dispatch")?; let mut q = std::ptr::null_mut(); - readback.Map(0, None, Some(&mut q)).map_err(e)?; + readback.Map(0, None, Some(&mut q)).map_err(werr)?; let out = std::slice::from_raw_parts(q as *const u32, mem_len).to_vec(); readback.Unmap(0, None); let mut ms = Vec::new(); if let Some((_, stamps_buf)) = &queries { - let hz = queue.GetTimestampFrequency().map_err(e)? as f64; + let hz = queue.GetTimestampFrequency().map_err(werr)? as f64; let mut t = std::ptr::null_mut(); - stamps_buf.Map(0, None, Some(&mut t)).map_err(e)?; + stamps_buf.Map(0, None, Some(&mut t)).map_err(werr)?; let ticks = std::slice::from_raw_parts(t as *const u64, stamps as usize); ms = ticks.chunks(2).map(|c| c[1].saturating_sub(c[0]) as f64 * 1000.0 / hz).collect(); stamps_buf.Unmap(0, None); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 37f443b..4d77c06 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4,7 +4,7 @@ //! as wave32 programs, and only need a GPU and DXC. use super::runner::{self, KernelState}; -use super::{translate, Mode, Options}; +use super::{translate, Mode, Options, PadWaves}; use crate::gpu::rdna2::encode; /// A GPU and DXC for the instruction tests. Wave64 programs run natively where the adapter @@ -1097,6 +1097,529 @@ fn gpu_clamp_and_omod_per_instruction() { } } +/// 16-bit VALU integer CLAMP=1 saturation vs CLAMP=0 wrapping, plus OP_SEL half selection and +/// preservation of the untouched half of the destination VGPR. +#[test] +fn gpu_int_clamp_16bit() { + let v = |name: &'static str, f: &'static [(&'static str, u64)]| (name, "ENC_VOP3", f, None); + let code = prog(&[ + // v_add_nc_u16 + v("V_ADD_NC_U16", &[("VDST", 10), ("SRC0", V + 0), ("SRC1", V + 1), ("CLAMP", 1)]), + v("V_ADD_NC_U16", &[("VDST", 11), ("SRC0", V + 0), ("SRC1", V + 1)]), + v("V_ADD_NC_U16", &[("VDST", 12), ("SRC0", V + 0), ("SRC1", V + 1), ("OP_SEL", 0b1011), ("CLAMP", 1)]), + v("V_ADD_NC_U16", &[("VDST", 13), ("SRC0", V + 0), ("SRC1", V + 1), ("OP_SEL", 0b1000), ("CLAMP", 1)]), + // v_sub_nc_u16 + v("V_SUB_NC_U16", &[("VDST", 14), ("SRC0", V + 1), ("SRC1", V + 0), ("CLAMP", 1)]), + v("V_SUB_NC_U16", &[("VDST", 15), ("SRC0", V + 1), ("SRC1", V + 0)]), + v("V_SUB_NC_U16", &[("VDST", 16), ("SRC0", V + 0), ("SRC1", V + 1), ("OP_SEL", 0b0011), ("CLAMP", 1)]), + v("V_SUB_NC_U16", &[("VDST", 17), ("SRC0", V + 1), ("SRC1", V + 1), ("CLAMP", 1)]), + // v_add_nc_i16 + v("V_ADD_NC_I16", &[("VDST", 18), ("SRC0", V + 2), ("SRC1", V + 3), ("CLAMP", 1)]), + v("V_ADD_NC_I16", &[("VDST", 19), ("SRC0", V + 2), ("SRC1", V + 3)]), + v("V_ADD_NC_I16", &[("VDST", 20), ("SRC0", V + 2), ("SRC1", V + 3), ("OP_SEL", 0b0011), ("CLAMP", 1)]), + v("V_ADD_NC_I16", &[("VDST", 21), ("SRC0", V + 2), ("SRC1", V + 3), ("OP_SEL", 0b0011)]), + // v_sub_nc_i16 + v("V_SUB_NC_I16", &[("VDST", 22), ("SRC0", V + 2), ("SRC1", V + 3), ("OP_SEL", 0b0010), ("CLAMP", 1)]), + v("V_SUB_NC_I16", &[("VDST", 23), ("SRC0", V + 2), ("SRC1", V + 3), ("OP_SEL", 0b0010)]), + v("V_SUB_NC_I16", &[("VDST", 24), ("SRC0", V + 2), ("SRC1", V + 3), ("OP_SEL", 0b0001), ("CLAMP", 1)]), + v("V_SUB_NC_I16", &[("VDST", 25), ("SRC0", V + 2), ("SRC1", V + 3), ("OP_SEL", 0b0001)]), + // v_mad_u16: max intermediate 65535*65535 + 65535 = 0xFFFF_0000 fits in u32 + v("V_MAD_U16", &[("VDST", 26), ("SRC0", V + 4), ("SRC1", V + 4), ("SRC2", V + 4), ("CLAMP", 1)]), + v("V_MAD_U16", &[("VDST", 27), ("SRC0", V + 4), ("SRC1", V + 4), ("SRC2", V + 4)]), + v("V_MAD_U16", &[("VDST", 28), ("SRC0", V + 7), ("SRC1", V + 7), ("SRC2", V + 8), ("OP_SEL", 0b0010), ("CLAMP", 1)]), + // v_mad_i16: extreme positive (-32768)*(-32768)+1 and negative (-32768)*32767+(-32768) + v("V_MAD_I16", &[("VDST", 29), ("SRC0", V + 5), ("SRC1", V + 5), ("SRC2", V + 6), ("CLAMP", 1)]), + v("V_MAD_I16", &[("VDST", 30), ("SRC0", V + 5), ("SRC1", V + 5), ("SRC2", V + 6)]), + v("V_MAD_I16", &[("VDST", 31), ("SRC0", V + 5), ("SRC1", V + 6), ("SRC2", V + 5), ("OP_SEL", 0b0010), ("CLAMP", 1)]), + v("V_MAD_I16", &[("VDST", 32), ("SRC0", V + 5), ("SRC1", V + 6), ("SRC2", V + 5), ("OP_SEL", 0b0010)]), + v("V_MAD_I16", &[("VDST", 33), ("SRC0", V + 3), ("SRC1", V + 7), ("SRC2", V + 8), ("OP_SEL", 0b0001), ("CLAMP", 1)]), + // Regression check for negative-clamped low half preserving upper half on packed/cvt i16: + // v_pk_add_i16 with lo = hi(v2)+hi(v3) (-32752 + -32 -> 0x8000), hi = lo(v2)+lo(v3) (+32752 + 32 -> 0x7FFF) + ("V_PK_ADD_I16", "ENC_VOP3P", &[("VDST", 34), ("SRC0", V + 2), ("SRC1", V + 3), ("OP_SEL", 3), ("CLAMP", 1)], None), + // v_cvt_pk_i16_i32 with lo = -40000 -> 0x8000, hi = 1 -> 0x0001 + v("V_CVT_PK_I16_I32", &[("VDST", 35), ("SRC0", V + 9), ("SRC1", 129)]), + // v_cvt_i16_f16 with -40000.0 (f16 = 0xF8E2), NaN (0x7E00), +inf (0x7C00), -inf (0xFC00) + v("V_CVT_I16_F16", &[("VDST", 36), ("SRC0", V + 37)]), + v("V_CVT_I16_F16", &[("VDST", 38), ("SRC0", V + 37), ("OP_SEL", 0b0001)]), + v("V_CVT_I16_F16", &[("VDST", 39), ("SRC0", V + 40)]), + v("V_CVT_I16_F16", &[("VDST", 41), ("SRC0", V + 40), ("OP_SEL", 0b0001)]), + // v_mul_lo_u16: 65535*65535 = 0xFFFE_0001 (overflow -> 0xFFFF / wrap -> 0x0001), 100*200 = 20000 (0x4E20) + v("V_MUL_LO_U16", &[("VDST", 42), ("SRC0", V + 4), ("SRC1", V + 4), ("CLAMP", 1)]), + v("V_MUL_LO_U16", &[("VDST", 43), ("SRC0", V + 4), ("SRC1", V + 4)]), + v("V_MUL_LO_U16", &[("VDST", 44), ("SRC0", V + 7), ("SRC1", V + 7), ("OP_SEL", 0b1010), ("CLAMP", 1)]), + // v_pk_mul_lo_u16: lo = 0xFFF0*0x0020 = 0x1F_FE00 (ov -> 0xFFFF / wrap -> 0xFE00), hi = 5*2 = 10 (in-range) + ("V_PK_MUL_LO_U16", "ENC_VOP3P", &[("VDST", 45), ("SRC0", V + 0), ("SRC1", V + 1), ("OP_SEL_HI", 3), ("CLAMP", 1)], None), + ("V_PK_MUL_LO_U16", "ENC_VOP3P", &[("VDST", 46), ("SRC0", V + 0), ("SRC1", V + 1), ("OP_SEL_HI", 3)], None), + // Negative-result i16 min/max/med3 sanity check (verifies upper half preservation on NVIDIA SPIR-V) + v("V_MIN_I16", &[("VDST", 47), ("SRC0", V + 2), ("SRC1", V + 3), ("OP_SEL", 0b0011)]), + v("V_MAX_I16", &[("VDST", 48), ("SRC0", V + 2), ("SRC1", V + 3), ("OP_SEL", 0b0011)]), + v("V_MED3_I16", &[("VDST", 49), ("SRC0", V + 2), ("SRC1", V + 3), ("SRC2", V + 5), ("OP_SEL", 0b0011)]), + v("V_MIN3_I16", &[("VDST", 50), ("SRC0", V + 2), ("SRC1", V + 3), ("SRC2", V + 5), ("OP_SEL", 0b0011)]), + v("V_MAX3_I16", &[("VDST", 51), ("SRC0", V + 2), ("SRC1", V + 3), ("SRC2", V + 5), ("OP_SEL", 0b0011)]), + ("V_PK_MIN_I16", "ENC_VOP3P", &[("VDST", 52), ("SRC0", V + 2), ("SRC1", V + 3), ("OP_SEL", 3)], None), + ("V_PK_MAX_I16", "ENC_VOP3P", &[("VDST", 53), ("SRC0", V + 2), ("SRC1", V + 3), ("OP_SEL", 3)], None), + // Exact boundary pairs: 0xFFFF + 0 vs +1, 32767 + 0 vs +1, -32768 - 0 vs -1 + v("V_ADD_NC_U16", &[("VDST", 54), ("SRC0", V + 4), ("SRC1", 128), ("CLAMP", 1)]), + v("V_ADD_NC_U16", &[("VDST", 55), ("SRC0", V + 4), ("SRC1", 129), ("CLAMP", 1)]), + v("V_ADD_NC_U16", &[("VDST", 56), ("SRC0", V + 4), ("SRC1", 129)]), + v("V_ADD_NC_I16", &[("VDST", 57), ("SRC0", V + 6), ("SRC1", 128), ("OP_SEL", 0b0001), ("CLAMP", 1)]), + v("V_ADD_NC_I16", &[("VDST", 58), ("SRC0", V + 6), ("SRC1", 129), ("OP_SEL", 0b0001), ("CLAMP", 1)]), + v("V_ADD_NC_I16", &[("VDST", 59), ("SRC0", V + 6), ("SRC1", 129), ("OP_SEL", 0b0001)]), + v("V_SUB_NC_I16", &[("VDST", 60), ("SRC0", V + 5), ("SRC1", 128), ("CLAMP", 1)]), + v("V_SUB_NC_I16", &[("VDST", 61), ("SRC0", V + 5), ("SRC1", 129), ("CLAMP", 1)]), + v("V_SUB_NC_I16", &[("VDST", 62), ("SRC0", V + 5), ("SRC1", 129)]), + ]); + let mut st = KernelState::default(); + for r in st.vgpr.iter_mut() { + r[0] = 0x0005_FFF0; + r[1] = 0x0002_0020; + r[2] = 0x8010_7FF0; + r[3] = 0xFFE0_0020; + r[4] = 0xFFFF_FFFF; + r[5] = 0x8000_8000; + r[6] = 0x7FFF_0001; + r[7] = 0x00C8_0064; + r[8] = 0x0000_0037; + r[9] = (-40_000i32) as u32; + r[37] = 0x7E00_F8E2; // hi: NaN, lo: -40000.0 in binary16 + r[40] = 0xFC00_7C00; // hi: -inf, lo: +inf in binary16 + for d in (10..=36).chain([38, 39]).chain(41..=62) { + r[d] = 0xDEAD_BEEF; + } + } + for wave64 in gpu_waves() { + let (r, lanes) = run_wave(&code, &st, wave64); + for (l, v) in r.vgpr.iter().take(lanes).enumerate() { + assert_eq!(v[10], 0xDEAD_FFFF, "wave{lanes} lane {l} v_add_nc_u16 clamp"); + assert_eq!(v[11], 0xDEAD_0010, "wave{lanes} lane {l} v_add_nc_u16 wrap"); + assert_eq!(v[12], 0x0007_BEEF, "wave{lanes} lane {l} v_add_nc_u16 clamp hi in-range"); + assert_eq!(v[13], 0xFFFF_BEEF, "wave{lanes} lane {l} v_add_nc_u16 clamp dst hi"); + assert_eq!(v[14], 0xDEAD_0000, "wave{lanes} lane {l} v_sub_nc_u16 clamp underflow"); + assert_eq!(v[15], 0xDEAD_0030, "wave{lanes} lane {l} v_sub_nc_u16 wrap"); + assert_eq!(v[16], 0xDEAD_0003, "wave{lanes} lane {l} v_sub_nc_u16 clamp in-range"); + assert_eq!(v[17], 0xDEAD_0000, "wave{lanes} lane {l} v_sub_nc_u16 clamp zero"); + assert_eq!(v[18], 0xDEAD_7FFF, "wave{lanes} lane {l} v_add_nc_i16 clamp +ov"); + assert_eq!(v[19], 0xDEAD_8010, "wave{lanes} lane {l} v_add_nc_i16 wrap +ov"); + assert_eq!(v[20], 0xDEAD_8000, "wave{lanes} lane {l} v_add_nc_i16 clamp -ov"); + assert_eq!(v[21], 0xDEAD_7FF0, "wave{lanes} lane {l} v_add_nc_i16 wrap -ov"); + assert_eq!(v[22], 0xDEAD_7FFF, "wave{lanes} lane {l} v_sub_nc_i16 clamp +ov"); + assert_eq!(v[23], 0xDEAD_8010, "wave{lanes} lane {l} v_sub_nc_i16 wrap +ov"); + assert_eq!(v[24], 0xDEAD_8000, "wave{lanes} lane {l} v_sub_nc_i16 clamp -ov"); + assert_eq!(v[25], 0xDEAD_7FF0, "wave{lanes} lane {l} v_sub_nc_i16 wrap -ov"); + assert_eq!(v[26], 0xDEAD_FFFF, "wave{lanes} lane {l} v_mad_u16 clamp max"); + assert_eq!(v[27], 0xDEAD_0000, "wave{lanes} lane {l} v_mad_u16 wrap max"); + assert_eq!(v[28], 0xDEAD_4E57, "wave{lanes} lane {l} v_mad_u16 clamp in-range"); + assert_eq!(v[29], 0xDEAD_7FFF, "wave{lanes} lane {l} v_mad_i16 clamp +ov"); + assert_eq!(v[30], 0xDEAD_0001, "wave{lanes} lane {l} v_mad_i16 wrap +ov"); + assert_eq!(v[31], 0xDEAD_8000, "wave{lanes} lane {l} v_mad_i16 clamp -ov"); + assert_eq!(v[32], 0xDEAD_0000, "wave{lanes} lane {l} v_mad_i16 wrap -ov"); + assert_eq!(v[33], 0xDEAD_F3B7, "wave{lanes} lane {l} v_mad_i16 clamp in-range neg"); + assert_eq!(v[34], 0x7FFF_8000, "wave{lanes} lane {l} v_pk_add_i16 clamp neg lo + pos hi"); + assert_eq!(v[35], 0x0001_8000, "wave{lanes} lane {l} v_cvt_pk_i16_i32 neg lo + pos hi"); + assert_eq!(v[36], 0xDEAD_8000, "wave{lanes} lane {l} v_cvt_i16_f16 neg clamp"); + assert_eq!(v[38], 0xDEAD_0000, "wave{lanes} lane {l} v_cvt_i16_f16 NaN"); + assert_eq!(v[39], 0xDEAD_7FFF, "wave{lanes} lane {l} v_cvt_i16_f16 +inf"); + assert_eq!(v[41], 0xDEAD_8000, "wave{lanes} lane {l} v_cvt_i16_f16 -inf"); + assert_eq!(v[42], 0xDEAD_FFFF, "wave{lanes} lane {l} v_mul_lo_u16 clamp"); + assert_eq!(v[43], 0xDEAD_0001, "wave{lanes} lane {l} v_mul_lo_u16 wrap"); + assert_eq!(v[44], 0x4E20_BEEF, "wave{lanes} lane {l} v_mul_lo_u16 clamp hi in-range"); + assert_eq!(v[45], 0x000A_FFFF, "wave{lanes} lane {l} v_pk_mul_lo_u16 clamp"); + assert_eq!(v[46], 0x000A_FE00, "wave{lanes} lane {l} v_pk_mul_lo_u16 wrap"); + assert_eq!(v[47], 0xDEAD_8010, "wave{lanes} lane {l} v_min_i16 neg preserves hi"); + assert_eq!(v[48], 0xDEAD_FFE0, "wave{lanes} lane {l} v_max_i16 neg preserves hi"); + assert_eq!(v[49], 0xDEAD_8010, "wave{lanes} lane {l} v_med3_i16 neg preserves hi"); + assert_eq!(v[50], 0xDEAD_8000, "wave{lanes} lane {l} v_min3_i16 neg preserves hi"); + assert_eq!(v[51], 0xDEAD_FFE0, "wave{lanes} lane {l} v_max3_i16 neg preserves hi"); + assert_eq!(v[52], 0x0020_8010, "wave{lanes} lane {l} v_pk_min_i16 neg lo + pos hi"); + assert_eq!(v[53], 0x7FF0_FFE0, "wave{lanes} lane {l} v_pk_max_i16 neg lo + pos hi"); + assert_eq!(v[54], 0xDEAD_FFFF, "wave{lanes} lane {l} v_add_nc_u16 0xFFFF + 0 clamp"); + assert_eq!(v[55], 0xDEAD_FFFF, "wave{lanes} lane {l} v_add_nc_u16 0xFFFF + 1 clamp"); + assert_eq!(v[56], 0xDEAD_0000, "wave{lanes} lane {l} v_add_nc_u16 0xFFFF + 1 wrap"); + assert_eq!(v[57], 0xDEAD_7FFF, "wave{lanes} lane {l} v_add_nc_i16 32767 + 0 clamp"); + assert_eq!(v[58], 0xDEAD_7FFF, "wave{lanes} lane {l} v_add_nc_i16 32767 + 1 clamp"); + assert_eq!(v[59], 0xDEAD_8000, "wave{lanes} lane {l} v_add_nc_i16 32767 + 1 wrap"); + assert_eq!(v[60], 0xDEAD_8000, "wave{lanes} lane {l} v_sub_nc_i16 -32768 - 0 clamp"); + assert_eq!(v[61], 0xDEAD_8000, "wave{lanes} lane {l} v_sub_nc_i16 -32768 - 1 clamp"); + assert_eq!(v[62], 0xDEAD_7FFF, "wave{lanes} lane {l} v_sub_nc_i16 -32768 - 1 wrap"); + } + } +} + +/// 32-bit integer CLAMP=1 saturation on MAD (u16/i16/u24/i24), MUL24 (u24/i24), SAD/MSAD, +/// SDWA CLAMP=1 on MUL24, and V_CVT_PKRTZ_F16_F32 ignoring VOP3 OMOD/CLAMP. +#[test] +fn gpu_int_clamp_32bit_mad_mul_sad() { + let v = |name: &'static str, f: &'static [(&'static str, u64)]| (name, "ENC_VOP3", f, None); + let code = prog(&[ + // v_mad_u32_u16: v0 = 0xFFFF_0003, v1 = 0xFFFF_0004, v2 = 0x0002_0000, v3 = 0x0001_FFFE + v("V_MAD_U32_U16", &[("VDST", 20), ("SRC0", V + 0), ("SRC1", V + 1), ("SRC2", V + 2), ("OP_SEL", 3), ("CLAMP", 1)]), + v("V_MAD_U32_U16", &[("VDST", 21), ("SRC0", V + 0), ("SRC1", V + 1), ("SRC2", V + 2), ("OP_SEL", 3)]), + v("V_MAD_U32_U16", &[("VDST", 22), ("SRC0", V + 0), ("SRC1", V + 1), ("SRC2", V + 3), ("OP_SEL", 3), ("CLAMP", 1)]), + // v_mad_i32_i16: v4 = 0x8000_7FFF, v5 = 0x7000_0000, v6 = 0x9000_0000 (-0x7000_0000) + // hi*hi + v5 = (-32768)*(-32768) + 0x7000_0000 = +0xB000_0000 -> +ov + v("V_MAD_I32_I16", &[("VDST", 23), ("SRC0", V + 4), ("SRC1", V + 4), ("SRC2", V + 5), ("OP_SEL", 3), ("CLAMP", 1)]), + v("V_MAD_I32_I16", &[("VDST", 24), ("SRC0", V + 4), ("SRC1", V + 4), ("SRC2", V + 5), ("OP_SEL", 3)]), + // hi*lo + v6 = (-32768)*32767 + (-0x7000_0000) -> -ov + v("V_MAD_I32_I16", &[("VDST", 25), ("SRC0", V + 4), ("SRC1", V + 4), ("SRC2", V + 6), ("OP_SEL", 1), ("CLAMP", 1)]), + v("V_MAD_I32_I16", &[("VDST", 26), ("SRC0", V + 4), ("SRC1", V + 4), ("SRC2", V + 6), ("OP_SEL", 1)]), + // v_mul_u32_u24: v7 = 0xABFF_FFFF (u24 = 0xFFFFFF), v8 = 0x0001_0000, v9 = 0x0000_FFFF + v("V_MUL_U32_U24", &[("VDST", 27), ("SRC0", V + 7), ("SRC1", V + 7), ("CLAMP", 1)]), + v("V_MUL_U32_U24", &[("VDST", 28), ("SRC0", V + 7), ("SRC1", V + 7)]), + v("V_MUL_U32_U24", &[("VDST", 29), ("SRC0", V + 8), ("SRC1", V + 9), ("CLAMP", 1)]), + // v_mul_i32_i24: v10 = 0x0080_0000 (i24 = -2^23), v11 = 0x007F_FFFF (i24 = 2^23 - 1) + v("V_MUL_I32_I24", &[("VDST", 30), ("SRC0", V + 10), ("SRC1", V + 10), ("CLAMP", 1)]), + v("V_MUL_I32_I24", &[("VDST", 31), ("SRC0", V + 10), ("SRC1", V + 10)]), + v("V_MUL_I32_I24", &[("VDST", 32), ("SRC0", V + 10), ("SRC1", V + 11), ("CLAMP", 1)]), + v("V_MUL_I32_I24", &[("VDST", 33), ("SRC0", V + 10), ("SRC1", V + 11)]), + // v_mad_u32_u24: product overflow and add-only overflow + v("V_MAD_U32_U24", &[("VDST", 34), ("SRC0", V + 7), ("SRC1", V + 7), ("SRC2", 133), ("CLAMP", 1)]), + v("V_MAD_U32_U24", &[("VDST", 35), ("SRC0", V + 7), ("SRC1", V + 7), ("SRC2", 133)]), + v("V_MAD_U32_U24", &[("VDST", 36), ("SRC0", V + 8), ("SRC1", V + 9), ("SRC2", V + 2), ("CLAMP", 1)]), + v("V_MAD_U32_U24", &[("VDST", 37), ("SRC0", V + 8), ("SRC1", V + 9), ("SRC2", V + 2)]), + // v_mad_i32_i24: positive overflow, negative underflow, and wrapping control + v("V_MAD_I32_I24", &[("VDST", 38), ("SRC0", V + 11), ("SRC1", V + 11), ("SRC2", 138), ("CLAMP", 1)]), + v("V_MAD_I32_I24", &[("VDST", 39), ("SRC0", V + 11), ("SRC1", V + 11), ("SRC2", 138)]), + v("V_MAD_I32_I24", &[("VDST", 40), ("SRC0", V + 10), ("SRC1", V + 11), ("SRC2", 198), ("CLAMP", 1)]), + v("V_MAD_I32_I24", &[("VDST", 41), ("SRC0", V + 10), ("SRC1", V + 11), ("SRC2", 198)]), + // v_sad_u32: v12 = 0xFFFF_FFF0, v13 = 0x0000_0010, v14 = 0x0000_0100 + v("V_SAD_U32", &[("VDST", 42), ("SRC0", V + 12), ("SRC1", V + 13), ("SRC2", V + 14), ("CLAMP", 1)]), + v("V_SAD_U32", &[("VDST", 43), ("SRC0", V + 12), ("SRC1", V + 13), ("SRC2", V + 14)]), + v("V_SAD_U32", &[("VDST", 44), ("SRC0", V + 13), ("SRC1", V + 12), ("SRC2", V + 14), ("CLAMP", 1)]), + // v_sad_u8 / v_sad_hi_u8 / v_sad_u16 / v_msad_u8: v15 = 0xFFFF_FFFF, v16 = 0x0000_0000, v17 = 0x0001_0101 + v("V_SAD_U8", &[("VDST", 45), ("SRC0", V + 15), ("SRC1", V + 16), ("SRC2", V + 12), ("CLAMP", 1)]), + v("V_SAD_U8", &[("VDST", 46), ("SRC0", V + 15), ("SRC1", V + 16), ("SRC2", V + 12)]), + v("V_SAD_HI_U8", &[("VDST", 47), ("SRC0", V + 15), ("SRC1", V + 16), ("SRC2", V + 18), ("CLAMP", 1)]), + v("V_SAD_HI_U8", &[("VDST", 48), ("SRC0", V + 15), ("SRC1", V + 16), ("SRC2", V + 18)]), + v("V_SAD_U16", &[("VDST", 49), ("SRC0", V + 15), ("SRC1", V + 16), ("SRC2", V + 19), ("CLAMP", 1)]), + v("V_SAD_U16", &[("VDST", 50), ("SRC0", V + 15), ("SRC1", V + 16), ("SRC2", V + 19)]), + v("V_MSAD_U8", &[("VDST", 51), ("SRC0", V + 15), ("SRC1", V + 17), ("SRC2", V + 12), ("CLAMP", 1)]), + v("V_MSAD_U8", &[("VDST", 52), ("SRC0", V + 15), ("SRC1", V + 17), ("SRC2", V + 12)]), + v("V_MSAD_U8", &[("VDST", 53), ("SRC0", V + 15), ("SRC1", V + 17), ("SRC2", 138), ("CLAMP", 1)]), + // v_cvt_pkrtz_f16_f32 ignores VOP3 OMOD and CLAMP on RDNA2 (ABS/NEG still apply): + // v54 = -2.0 (f16 0xC000), v55 = 3.0 (0x4200), v56 = 1.5 (0x3E00), v57 = -0.5 (0xB800) + v("V_CVT_PKRTZ_F16_F32", &[("VDST", 58), ("SRC0", V + 54), ("SRC1", V + 55), ("CLAMP", 1)]), + v("V_CVT_PKRTZ_F16_F32", &[("VDST", 59), ("SRC0", V + 56), ("SRC1", V + 57), ("OMOD", 1)]), + // SDWA CLAMP=1 path: v_mul_u32_u24_sdwa & v_mul_i32_i24_sdwa (+ov and -ov) + ("V_MUL_U32_U24", "VOP2_VOP_SDWA", &[("VDST", 60), ("SRC0", 0xF9), ("VSRC0", 7), ("VSRC1", 7), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("DST_SEL", 6), ("CLAMP", 1)], None), + ("V_MUL_I32_I24", "VOP2_VOP_SDWA", &[("VDST", 61), ("SRC0", 0xF9), ("VSRC0", 10), ("VSRC1", 10), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("DST_SEL", 6), ("CLAMP", 1)], None), + ("V_MUL_I32_I24", "VOP2_VOP_SDWA", &[("VDST", 62), ("SRC0", 0xF9), ("VSRC0", 10), ("VSRC1", 11), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("DST_SEL", 6), ("CLAMP", 1)], None), + ]); + let mut st = KernelState::default(); + for r in st.vgpr.iter_mut() { + r[0] = 0xFFFF_0003; + r[1] = 0xFFFF_0004; + r[2] = 0x0002_0000; + r[3] = 0x0001_FFFE; + r[4] = 0x8000_7FFF; + r[5] = 0x7000_0000; + r[6] = 0x9000_0000; + r[7] = 0xABFF_FFFF; + r[8] = 0x0001_0000; + r[9] = 0x0000_FFFF; + r[10] = 0x0080_0000; + r[11] = 0x007F_FFFF; + r[12] = 0xFFFF_FFF0; + r[13] = 0x0000_0010; + r[14] = 0x0000_0100; + r[15] = 0xFFFF_FFFF; + r[16] = 0x0000_0000; + r[17] = 0x0001_0101; + r[18] = 0xFF00_0000; + r[19] = 0xFFFF_0000; + r[54] = f(-2.0); + r[55] = f(3.0); + r[56] = f(1.5); + r[57] = f(-0.5); + } + for wave64 in gpu_waves() { + let (r, lanes) = run_wave(&code, &st, wave64); + for (l, v) in r.vgpr.iter().take(lanes).enumerate() { + assert_eq!(v[20], 0xFFFF_FFFF, "wave{lanes} lane {l} v_mad_u32_u16 clamp"); + assert_eq!(v[21], 0x0000_0001, "wave{lanes} lane {l} v_mad_u32_u16 wrap"); + assert_eq!(v[22], 0xFFFF_FFFF, "wave{lanes} lane {l} v_mad_u32_u16 exact max"); + assert_eq!(v[23], 0x7FFF_FFFF, "wave{lanes} lane {l} v_mad_i32_i16 clamp +ov"); + assert_eq!(v[24], 0xB000_0000, "wave{lanes} lane {l} v_mad_i32_i16 wrap +ov"); + assert_eq!(v[25], 0x8000_0000, "wave{lanes} lane {l} v_mad_i32_i16 clamp -ov"); + assert_eq!( + v[26], + ((-32768i32).wrapping_mul(32767).wrapping_add(-0x7000_0000i32)) as u32, + "wave{lanes} lane {l} v_mad_i32_i16 wrap -ov" + ); + assert_eq!(v[27], 0xFFFF_FFFF, "wave{lanes} lane {l} v_mul_u32_u24 clamp"); + assert_eq!(v[28], 0xFE00_0001, "wave{lanes} lane {l} v_mul_u32_u24 wrap"); + assert_eq!(v[29], 0xFFFF_0000, "wave{lanes} lane {l} v_mul_u32_u24 clamp in-range"); + assert_eq!(v[30], 0x7FFF_FFFF, "wave{lanes} lane {l} v_mul_i32_i24 clamp +ov"); + assert_eq!(v[31], 0x0000_0000, "wave{lanes} lane {l} v_mul_i32_i24 wrap +ov"); + assert_eq!(v[32], 0x8000_0000, "wave{lanes} lane {l} v_mul_i32_i24 clamp -ov"); + assert_eq!(v[33], 0x0080_0000, "wave{lanes} lane {l} v_mul_i32_i24 wrap -ov"); + assert_eq!(v[34], 0xFFFF_FFFF, "wave{lanes} lane {l} v_mad_u32_u24 clamp prod ov"); + assert_eq!(v[35], 0xFE00_0006, "wave{lanes} lane {l} v_mad_u32_u24 wrap prod ov"); + assert_eq!(v[36], 0xFFFF_FFFF, "wave{lanes} lane {l} v_mad_u32_u24 clamp add ov"); + assert_eq!(v[37], 0x0001_0000, "wave{lanes} lane {l} v_mad_u32_u24 wrap add ov"); + assert_eq!(v[38], 0x7FFF_FFFF, "wave{lanes} lane {l} v_mad_i32_i24 clamp +ov"); + assert_eq!( + v[39], + ((0x007F_FFFFi32).wrapping_mul(0x007F_FFFF).wrapping_add(10)) as u32, + "wave{lanes} lane {l} v_mad_i32_i24 wrap +ov" + ); + assert_eq!(v[40], 0x8000_0000, "wave{lanes} lane {l} v_mad_i32_i24 clamp -ov"); + assert_eq!( + v[41], + ((-0x0080_0000i32).wrapping_mul(0x007F_FFFF).wrapping_add(-6)) as u32, + "wave{lanes} lane {l} v_mad_i32_i24 wrap -ov" + ); + assert_eq!(v[42], 0xFFFF_FFFF, "wave{lanes} lane {l} v_sad_u32 clamp a>b"); + assert_eq!(v[43], 0x0000_00E0, "wave{lanes} lane {l} v_sad_u32 wrap"); + assert_eq!(v[44], 0xFFFF_FFFF, "wave{lanes} lane {l} v_sad_u32 clamp a even: 0 - 0xFFFF_FFFF - 1 (-2^32, borrow=1), + // odd: 0xFFFF_FFFF - 0xFFFF_FFFF - 1 (-1, borrow=1, wrap=0xFFFF_FFFF, clamp=0) + vs("V_SUB_CO_CI_U32", &[("VDST", 24), ("SDST", 40), ("SRC0", V + 45), ("SRC1", V + 44), ("SRC2", 20), ("CLAMP", 1)]), + vs("V_SUB_CO_CI_U32", &[("VDST", 25), ("SDST", 42), ("SRC0", V + 45), ("SRC1", V + 44), ("SRC2", 20)]), + vs("V_SUBREV_CO_CI_U32", &[("VDST", 26), ("SDST", 44), ("SRC0", V + 44), ("SRC1", V + 45), ("SRC2", 20), ("CLAMP", 1)]), + vs("V_SUBREV_CO_CI_U32", &[("VDST", 27), ("SDST", 46), ("SRC0", V + 44), ("SRC1", V + 45), ("SRC2", 20)]), + // SDWA CLAMP=1 on V_ADD_CO_CI_U32 & V_SUB_CO_CI_U32 (reads/writes VCC = s[106:107]): + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 20)], None), + ("V_ADD_CO_CI_U32", "VOP2_VOP_SDWA", &[("VDST", 28), ("SRC0", 0xF9), ("VSRC0", 3), ("VSRC1", 46), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("DST_SEL", 6), ("CLAMP", 1)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 48), ("SSRC0", 106)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 20)], None), + ("V_SUB_CO_CI_U32", "VOP2_VOP_SDWA", &[("VDST", 29), ("SRC0", 0xF9), ("VSRC0", 4), ("VSRC1", 46), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("DST_SEL", 6), ("CLAMP", 1)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 50), ("SSRC0", 106)], None), + // v_mad_u64_u32: even lanes overflow, odd lanes hit exact u64::MAX without carry + vs("V_MAD_U64_U32", &[("VDST", 30), ("SDST", 26), ("SRC0", V + 5), ("SRC1", V + 6), ("SRC2", V + 7), ("CLAMP", 1)]), + vs("V_MAD_U64_U32", &[("VDST", 32), ("SDST", 28), ("SRC0", V + 5), ("SRC1", V + 6), ("SRC2", V + 7)]), + // v_mad_i64_i32: 8 cases across lanes (l % 8) covering +ov, -ov, exact bounds, opposite signs + vs("V_MAD_I64_I32", &[("VDST", 34), ("SDST", 30), ("SRC0", V + 40), ("SRC1", V + 41), ("SRC2", V + 42), ("CLAMP", 1)]), + vs("V_MAD_I64_I32", &[("VDST", 36), ("SDST", 32), ("SRC0", V + 40), ("SRC1", V + 41), ("SRC2", V + 42)]), + ]); + let set64 = |r: &mut [u32], idx: usize, val: u64| { + r[idx] = val as u32; + r[idx + 1] = (val >> 32) as u32; + }; + let get64 = |v: &[u32], idx: usize| v[idx] as u64 | ((v[idx + 1] as u64) << 32); + let mut st = KernelState::default(); + st.sgpr[20] = u32::MAX; + st.sgpr[21] = u32::MAX; + st.sgpr[34] = 0x5555_5555; + st.sgpr[35] = 0x5555_5555; + for (l, r) in st.vgpr.iter_mut().enumerate() { + let even = l & 1 == 0; + r[0] = if even { 0xFFFF_FFF0 } else { 10 }; + r[1] = 0x20; + r[2] = if even { 0x10 } else { 0x30 }; + r[3] = if even { 0xFFFF_FFFF } else { 0xFFFF_FFFE }; + r[4] = if even { 0 } else { 1 }; + r[5] = if even { 0xFFFF_FFFF } else { 0x0001_0000 }; + r[6] = if even { 0xFFFF_FFFF } else { 0x0001_0000 }; + set64(r, 7, if even { u64::MAX } else { 0xFFFF_FFFE_FFFF_FFFF }); + r[44] = 0xFFFF_FFFF; + r[45] = if even { 0 } else { 0xFFFF_FFFF }; + r[46] = 0; + match l % 8 { + 0 => { + // (-2^31)*(-2^31) + 2^62 = +2^63 > i64::MAX (bit64 = 0) + r[40] = i32::MIN as u32; + r[41] = i32::MIN as u32; + set64(r, 42, 0x4000_0000_0000_0000); + } + 1 => { + // (-2^31)*(2^31-1) + i64::MIN < i64::MIN (bit64 = 1) + r[40] = i32::MIN as u32; + r[41] = i32::MAX as u32; + set64(r, 42, i64::MIN as u64); + } + 2 => { + // 1*(-1) + i64::MIN = i64::MIN - 1 < i64::MIN (bit64 = 1) + r[40] = 1; + r[41] = (-1i32) as u32; + set64(r, 42, i64::MIN as u64); + } + 3 => { + // (-1)*1 + (i64::MIN + 1) = exact i64::MIN (bit64 = 1) + r[40] = (-1i32) as u32; + r[41] = 1; + set64(r, 42, (i64::MIN + 1) as u64); + } + 4 => { + // 1*1 + (i64::MAX - 1) = exact i64::MAX (bit64 = 0) + r[40] = 1; + r[41] = 1; + set64(r, 42, (i64::MAX - 1) as u64); + } + 5 => { + // 1*1 + i64::MAX = i64::MAX + 1 > i64::MAX (bit64 = 0) + r[40] = 1; + r[41] = 1; + set64(r, 42, i64::MAX as u64); + } + 6 => { + // (-2^31)*(2^31-1) + i64::MAX: opposite signs, > 0 (bit64 = 0) + r[40] = i32::MIN as u32; + r[41] = i32::MAX as u32; + set64(r, 42, i64::MAX as u64); + } + _ => { + // (-2^31)*(-2^31) + i64::MIN: opposite signs, -2^62 < 0 (bit64 = 1) + r[40] = i32::MIN as u32; + r[41] = i32::MIN as u32; + set64(r, 42, i64::MIN as u64); + } + } + } + for wave64 in gpu_waves() { + let (r, lanes) = run_wave(&code, &st, wave64); + let even_mask = (0x5555_5555u32, if wave64 { 0x5555_5555u32 } else { 0 }); + let sdwa_vcc_mask = (0x5555_5555u32, if wave64 { 0x5555_5555u32 } else { u32::MAX }); + let all_mask = (u32::MAX, if wave64 { u32::MAX } else { 0 }); + let mad_i64_mask = (0x8E8E_8E8Eu32, if wave64 { 0x8E8E_8E8Eu32 } else { 0 }); + for (slot, want, label) in [ + (0, even_mask, "v_add_co_u32 clamp sdst"), + (2, even_mask, "v_add_co_u32 wrap sdst"), + (4, even_mask, "v_sub_co_u32 clamp sdst"), + (6, even_mask, "v_sub_co_u32 wrap sdst"), + (8, even_mask, "v_subrev_co_u32 clamp sdst"), + (10, even_mask, "v_subrev_co_u32 wrap sdst"), + (12, even_mask, "v_add_co_ci_u32 clamp sdst"), + (14, even_mask, "v_add_co_ci_u32 wrap sdst"), + (16, even_mask, "v_sub_co_ci_u32 clamp sdst"), + (18, even_mask, "v_sub_co_ci_u32 wrap sdst"), + (22, even_mask, "v_subrev_co_ci_u32 clamp sdst"), + (24, even_mask, "v_subrev_co_ci_u32 wrap sdst"), + (36, all_mask, "v_add_co_ci_u32 max+max+cin clamp sdst"), + (38, all_mask, "v_add_co_ci_u32 max+max+cin wrap sdst"), + (40, all_mask, "v_sub_co_ci_u32 b+cin wraparound clamp sdst"), + (42, all_mask, "v_sub_co_ci_u32 b+cin wraparound wrap sdst"), + (44, all_mask, "v_subrev_co_ci_u32 b+cin wraparound clamp sdst"), + (46, all_mask, "v_subrev_co_ci_u32 b+cin wraparound wrap sdst"), + (48, sdwa_vcc_mask, "v_add_co_ci_u32 sdwa clamp vcc"), + (50, sdwa_vcc_mask, "v_sub_co_ci_u32 sdwa clamp vcc"), + (26, even_mask, "v_mad_u64_u32 clamp sdst"), + (28, even_mask, "v_mad_u64_u32 wrap sdst"), + (30, mad_i64_mask, "v_mad_i64_i32 clamp sdst (65-bit sign)"), + (32, mad_i64_mask, "v_mad_i64_i32 wrap sdst (65-bit sign)"), + ] { + assert_eq!((r.sgpr[slot], r.sgpr[slot + 1]), want, "wave{lanes} {label}"); + } + for (l, v) in r.vgpr.iter().take(lanes).enumerate() { + let even = l & 1 == 0; + assert_eq!(v[10], if even { 0xFFFF_FFFF } else { 10 + 0x20 }, "wave{lanes} lane {l} v_add_co_u32 clamp"); + assert_eq!(v[11], if even { 0x10 } else { 10 + 0x20 }, "wave{lanes} lane {l} v_add_co_u32 wrap"); + assert_eq!(v[12], if even { 0 } else { 0x10 }, "wave{lanes} lane {l} v_sub_co_u32 clamp"); + assert_eq!(v[13], if even { 0xFFFF_FFF0 } else { 0x10 }, "wave{lanes} lane {l} v_sub_co_u32 wrap"); + assert_eq!(v[14], if even { 0 } else { 0x10 }, "wave{lanes} lane {l} v_subrev_co_u32 clamp"); + assert_eq!(v[15], if even { 0xFFFF_FFF0 } else { 0x10 }, "wave{lanes} lane {l} v_subrev_co_u32 wrap"); + assert_eq!(v[16], 0xFFFF_FFFF, "wave{lanes} lane {l} v_add_co_ci_u32 clamp"); + assert_eq!(v[17], if even { 0 } else { 0xFFFF_FFFF }, "wave{lanes} lane {l} v_add_co_ci_u32 wrap"); + assert_eq!(v[18], 0, "wave{lanes} lane {l} v_sub_co_ci_u32 clamp"); + assert_eq!(v[19], if even { 0xFFFF_FFFF } else { 0 }, "wave{lanes} lane {l} v_sub_co_ci_u32 wrap"); + assert_eq!(v[20], 0, "wave{lanes} lane {l} v_subrev_co_ci_u32 clamp"); + assert_eq!(v[21], if even { 0xFFFF_FFFF } else { 0 }, "wave{lanes} lane {l} v_subrev_co_ci_u32 wrap"); + assert_eq!(v[22], 0xFFFF_FFFF, "wave{lanes} lane {l} v_add_co_ci_u32 max+max+cin clamp"); + assert_eq!(v[23], if even { 0xFFFF_FFFF } else { 0xFFFF_FFFE }, "wave{lanes} lane {l} v_add_co_ci_u32 max+max+cin wrap"); + assert_eq!(v[24], 0, "wave{lanes} lane {l} v_sub_co_ci_u32 b+cin wraparound clamp"); + assert_eq!(v[25], if even { 0 } else { 0xFFFF_FFFF }, "wave{lanes} lane {l} v_sub_co_ci_u32 b+cin wraparound wrap"); + assert_eq!(v[26], 0, "wave{lanes} lane {l} v_subrev_co_ci_u32 b+cin wraparound clamp"); + assert_eq!(v[27], if even { 0 } else { 0xFFFF_FFFF }, "wave{lanes} lane {l} v_subrev_co_ci_u32 b+cin wraparound wrap"); + assert_eq!(v[28], 0xFFFF_FFFF, "wave{lanes} lane {l} v_add_co_ci_u32 sdwa clamp"); + assert_eq!(v[29], 0, "wave{lanes} lane {l} v_sub_co_ci_u32 sdwa clamp"); + assert_eq!(get64(v, 30), u64::MAX, "wave{lanes} lane {l} v_mad_u64_u32 clamp"); + assert_eq!( + get64(v, 32), + if even { 0xFFFF_FFFE_0000_0000 } else { u64::MAX }, + "wave{lanes} lane {l} v_mad_u64_u32 wrap" + ); + let (want_clamp, want_wrap) = match l % 8 { + 0 => (i64::MAX as u64, i64::MIN as u64), + 1 => (i64::MIN as u64, 0x4000_0000_8000_0000u64), + 2 => (i64::MIN as u64, i64::MAX as u64), + 3 => (i64::MIN as u64, i64::MIN as u64), + 4 => (i64::MAX as u64, i64::MAX as u64), + 5 => (i64::MAX as u64, i64::MIN as u64), + 6 => (0x4000_0000_7FFF_FFFFu64, 0x4000_0000_7FFF_FFFFu64), + _ => (0xC000_0000_0000_0000u64, 0xC000_0000_0000_0000u64), + }; + assert_eq!(get64(v, 34), want_clamp, "wave{lanes} lane {l} v_mad_i64_i32 clamp"); + assert_eq!(get64(v, 36), want_wrap, "wave{lanes} lane {l} v_mad_i64_i32 wrap"); + } + } +} + +/// CPU-only codegen test so GPU-less CI exercises the integer CLAMP=1 HLSL emission paths +/// and verifies V_CVT_PKRTZ_F16_F32 ignores VOP3 OMOD/CLAMP. +#[test] +fn int_clamp_hlsl_codegen() { + let v = |name: &'static str, f: &'static [(&'static str, u64)]| (name, "ENC_VOP3", f, None); + let vs = |name: &'static str, f: &'static [(&'static str, u64)]| (name, "VOP3_SDST_ENC", f, None); + let code = prog(&[ + v("V_ADD_NC_U16", &[("VDST", 10), ("SRC0", V + 0), ("SRC1", V + 1), ("CLAMP", 1)]), + v("V_ADD_NC_I16", &[("VDST", 11), ("SRC0", V + 0), ("SRC1", V + 1), ("CLAMP", 1)]), + v("V_MUL_LO_U16", &[("VDST", 12), ("SRC0", V + 0), ("SRC1", V + 1), ("CLAMP", 1)]), + ("V_PK_MUL_LO_U16", "ENC_VOP3P", &[("VDST", 13), ("SRC0", V + 0), ("SRC1", V + 1), ("OP_SEL_HI", 3), ("CLAMP", 1)], None), + v("V_MAD_U32_U16", &[("VDST", 14), ("SRC0", V + 0), ("SRC1", V + 1), ("SRC2", V + 2), ("CLAMP", 1)]), + v("V_MAD_I32_I24", &[("VDST", 15), ("SRC0", V + 0), ("SRC1", V + 1), ("SRC2", V + 2), ("CLAMP", 1)]), + v("V_SAD_U32", &[("VDST", 16), ("SRC0", V + 0), ("SRC1", V + 1), ("SRC2", V + 2), ("CLAMP", 1)]), + vs("V_ADD_CO_U32", &[("VDST", 17), ("SDST", 0), ("SRC0", V + 0), ("SRC1", V + 1), ("CLAMP", 1)]), + vs("V_SUB_CO_CI_U32", &[("VDST", 18), ("SDST", 2), ("SRC0", V + 0), ("SRC1", V + 1), ("SRC2", 0), ("CLAMP", 1)]), + vs("V_MAD_U64_U32", &[("VDST", 20), ("SDST", 4), ("SRC0", V + 0), ("SRC1", V + 1), ("SRC2", V + 2), ("CLAMP", 1)]), + vs("V_MAD_I64_I32", &[("VDST", 22), ("SDST", 6), ("SRC0", V + 0), ("SRC1", V + 1), ("SRC2", V + 2), ("CLAMP", 1)]), + v("V_CVT_PKRTZ_F16_F32", &[("VDST", 24), ("SRC0", V + 0), ("SRC1", V + 1), ("OMOD", 1), ("CLAMP", 1)]), + ]); + let t = translate(&code, &Options::default()).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + assert!(t.hlsl.contains("0u - min((uint)(r >> 32), 1u)"), "expected branchless DXC-safe sat_u32"); + assert!(t.hlsl.contains("sat_i16("), "expected sat_i16 helper call"); + assert!(t.hlsl.contains("sat_u32("), "expected sat_u32 helper call"); + assert!(t.hlsl.contains("sat_i32("), "expected sat_i32 helper call"); + assert!(t.hlsl.contains("0xFFFFu)"), "expected 16-bit unsigned saturation"); + assert!(t.hlsl.contains("_s64 ="), "expected 65-bit signed carry-out for v_mad_i64_i32"); + assert!(t.hlsl.contains("f16_rtz(asfloat(v0)) | (f16_rtz(asfloat(v1)) << 16)"), "v_cvt_pkrtz_f16_f32 must ignore VOP3 omod/clamp"); +} + #[test] fn gpu_bench_really_runs() { if !gpu_ready() { @@ -1953,6 +2476,156 @@ fn gpu_ps_image_sample_offset_implicit_lod_between_mips() { } } +/// A 2-level texture (8², 4²; level k texel x holds 100·k + x); `r32`: one channel, else four. +fn two_mip_texture(r32: bool) -> runner::ViewTexture { + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32_FLOAT, DXGI_SAMPLE_DESC}; + let format = if r32 { DXGI_FORMAT_R32_FLOAT } else { DXGI_FORMAT_R32G32B32A32_FLOAT }; + let mut data = Vec::new(); + for k in 0..2u32 { + let n = 8 >> k; + for _y in 0..n { + for x in 0..n { + let v = (100 * k + x) as f32; + data.extend_from_slice(&if r32 { v.to_le_bytes().to_vec() } else { [v; 4].map(f32::to_le_bytes).concat() }); + } + } + } + let res = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 2, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let mut srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ..Default::default() + }; + srv.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: 2, ..Default::default() }; + runner::ViewTexture { res, srv, data, row_bytes: 8 * if r32 { 4 } else { 16 } } +} + +/// Draws `ps` (its sample's VDATA in v20) with `two_mip_texture`, point min / mag / mip, clamp +/// (`cmp`: one channel and a LESS_EQUAL comparison sampler); every pixel's red is `want(u)`, +/// u = v = pixel centre · `scale`. +fn assert_two_mip_sample(name: &str, ps: &[u8], cmp: bool, scale: f32, want: &dyn Fn(f32) -> f32) { + // S#: clamp u / v / w, point min / mag (0), MIP_FILTER point (1), DEPTH_COMPARE LESS_EQUAL (3 + 1) + let s_sharp = [2 | 2 << 3 | 2 << 6 | if cmp { 3 << 12 } else { 0 }, 0xFFF << 12, 1 << 26, 0]; + let mut sgprs = vec![0u32; 32]; + sgprs[16..24].copy_from_slice(&tsharp(0, 77, 9)); + sgprs[24..28].copy_from_slice(&s_sharp); + let px = draw_console_views(None, Some(ps), &[[0.0, 0.0], [0.0, 32.0], [32.0, 0.0]], &sgprs, &[two_mip_texture(cmp)], &[crate::gpu::desc::sampler_d3d12(&s_sharp, cmp)]); + for y in 0..16 { + for x in 0..16 { + let u = (x as f32 + 0.5) * scale; + let (got, w) = (px[y * 16 + x][0], want(u)); + assert!((got - w).abs() < 0.02, "{name}: pixel ({x},{y}) = {got}, expected {w}"); + } + } +} + +/// The texel of mip `k` (point filter) at u, moved by one of that mip's texels (offset +1, clamp). +fn texel_moved(k: u32, u: f32) -> f32 { + let size = (8 >> k) as f32; + 100.0 * k as f32 + ((u * size).floor() + 1.0).clamp(0.0, size - 1.0) +} + +const EXP_V20: (&str, &str, &[(&str, u64)], Option) = + ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 20), ("VSRC1", 20), ("VSRC2", 20), ("VSRC3", 20), ("DONE", 1), ("VM", 1)], None); + +/// Control for the tests below: `image_sample_o` at implicit LOD 0.75 with a point mip filter +/// reads mip 1 alone, moved by one of its texels (right on main since #229). +#[test] +fn gpu_ps_image_sample_offset_point_mip() { + if !gpu_ready() { + return; + } + let s = 2f32.powf(0.75) / 8.0; + let ps = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 129)], None), // offset x +1, y 0 + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 2)], Some(s.to_bits())), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 3)], Some(s.to_bits())), + ("IMAGE_SAMPLE_O", "ENC_MIMG", &[("VDATA", 20), ("VADDR", 4), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0x1), ("DIM", 1)], None), + EXP_V20, + ]); + assert_two_mip_sample("sample_o", &ps, false, s, &|u| texel_moved(1, u)); +} + +/// `image_sample_b_o`: implicit LOD 0 + bias 1 reads mip 1, so the offset is one of mip 1's texels. +#[test] +fn gpu_ps_image_sample_offset_bias_lod() { + if !gpu_ready() { + return; + } + let s = 1f32 / 8.0; + let ps = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 129)], None), // offset x +1, y 0 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 242)], None), // bias 1.0 + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 2)], Some(s.to_bits())), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 255), ("VSRC1", 3)], Some(s.to_bits())), + ("IMAGE_SAMPLE_B_O", "ENC_MIMG", &[("VDATA", 20), ("VADDR", 4), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0x1), ("DIM", 1)], None), + EXP_V20, + ]); + assert_two_mip_sample("sample_b_o", &ps, false, s, &|u| texel_moved(1, u)); +} + +/// `image_sample_d_o` / `image_sample_cd_o`: gradients of 2 mip-0 texels per pixel (LOD 1) read +/// mip 1, so the offset is one of mip 1's texels. +#[test] +fn gpu_ps_image_sample_offset_gradient_lod() { + if !gpu_ready() { + return; + } + let (s, g) = (1f32 / 8.0, 2f32 / 8.0); + for op in ["IMAGE_SAMPLE_D_O", "IMAGE_SAMPLE_CD_O"] { + let ps = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 129)], None), // offset x +1, y 0 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 255)], Some(g.to_bits())), // du/dx + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 255)], Some(g.to_bits())), // dv/dy + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 255), ("VSRC1", 2)], Some(s.to_bits())), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 255), ("VSRC1", 3)], Some(s.to_bits())), + (op, "ENC_MIMG", &[("VDATA", 20), ("VADDR", 4), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0x1), ("DIM", 1)], None), + EXP_V20, + ]); + assert_two_mip_sample(op, &ps, false, s, &|u| texel_moved(1, u)); + } +} + +/// `image_sample_c_o` at implicit LOD 1, LESS_EQUAL: z is the moved mip-1 texel - 0.5, so each +/// pixel passes (1) only if the offset was one of mip 1's texels; u = v = pixel centre / 4 - 1/16 +/// puts mip 0's single texel (half of mip 1's) short of the next mip-1 texel. +#[test] +fn gpu_ps_image_sample_offset_compare_lod() { + if !gpu_ready() { + return; + } + let s = 2f32 / 8.0; + let ps = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 129)], None), // offset x +1, y 0 + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 2)], Some(s.to_bits())), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 255), ("VSRC1", 3)], Some(s.to_bits())), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 6)], Some((-1f32 / 16.0).to_bits())), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 255), ("VSRC1", 7)], Some((-1f32 / 16.0).to_bits())), + // z = 100 + min(floor(4u) + 1, 3) - 0.5 + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 246), ("VSRC1", 6)], None), + ("V_FLOOR_F32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 5)], None), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 242), ("VSRC1", 5)], None), + ("V_MIN_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 5)], Some(3f32.to_bits())), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 5)], Some(99.5f32.to_bits())), + ("IMAGE_SAMPLE_C_O", "ENC_MIMG", &[("VDATA", 20), ("VADDR", 4), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0x1), ("DIM", 1)], None), + EXP_V20, + ]); + assert_two_mip_sample("sample_c_o", &ps, true, s, &|_| 1.0); +} + /// 48 SGPR spill slots in lanes 0..47 of v30 (`v_writelane` / `v_readlane`, as 287 retail /// pixel shaders do – 11 up to lane 47): slot k = `slot(k)`, then s44 = the sum of slots /// 0..31, s45 = the sum of slots 32..47. @@ -7000,6 +7673,24 @@ fn sdwa_f16_inline_constants_hlsl() { assert!(!t_int.hlsl.contains("0x00003C00u"), "{}", t_int.hlsl); } +#[test] +fn valu64_clamp_and_omod_hlsl() { + let code = prog(&[ + ("V_ADD_F64", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", V + 2), ("CLAMP", 1)], None), + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 4), ("SRC0", V), ("SRC1", V + 2), ("OMOD", 1)], None), + ("V_FMA_F64", "ENC_VOP3", &[("VDST", 6), ("SRC0", V), ("SRC1", V + 2), ("SRC2", V + 4), ("OMOD", 2), ("CLAMP", 1)], None), + ]); + let t = translate(&code, &Options { wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + assert!(t.hlsl.contains("double t1_d = clamp(asdouble(v0, v1) + asdouble(v2, v3), 0.0, 1.0);"), "{}", t.hlsl); + assert!(t.hlsl.contains("double t2_d = ((asdouble(v0, v1) * asdouble(v2, v3)) * 2.0);"), "{}", t.hlsl); + assert!(t.hlsl.contains("double t3_d = clamp(((fma(asdouble(v0, v1), asdouble(v2, v3), asdouble(v4, v5))) * 4.0), 0.0, 1.0);"), "{}", t.hlsl); + assert!(!t.hlsl.contains("saturate(asdouble"), "{}", t.hlsl); + if super::dxc::location().is_ok() { + super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + } +} + #[test] fn gpu_wave32_and_wave64_src_vccz_execz() { if !gpu_ready() { @@ -7141,3 +7832,259 @@ fn fspx_containers_translate_and_compile() { println!("FSPX: {ok} / {n} translated and compiled"); assert_eq!(ok, n); } + +// ---- compute groups that are not whole waves ---- + +fn cs_of(threads: [u32; 3], tg_size: bool) -> super::CsInterface { + super::CsInterface { threads, user_sgprs: 4, tgid: [true, false, false], tg_size, tid_components: 3 } +} + +/// A compute program that can tell the lanes its last, partial wave did not launch +/// (`partial_waves`): on the console they exist, inactive – code that turns them on in EXEC +/// runs in them (a compare of a register with itself is true there whatever it holds, `v_mov` +/// writes them) and `v_writelane` writes them whatever EXEC is. v0 = thread index in the +/// group (s1 = x, s2 = x · y of the group). Each thread stores at s0 + 16 · thread: the bits +/// of `v_cmp_eq_u32 vcc, v0, v0` after `s_not exec, exec` and after `s_or_saveexec s, -1`, +/// the wave's last lane of a VGPR written with EXEC = -1, and a lane `v_writelane` wrote. +fn lanes_not_launched_program(wave64: bool) -> Vec { + let (b, last) = if wave64 { ("B64", 63) } else { ("B32", 31) }; + let s1 = |n: &str, d: u64, s: u64| ins(&format!("{n}_{b}"), "ENC_SOP1", &[("SDST", d), ("SSRC0", s)], None); + let all = || ins("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 0)], None); + let lane = |n: &str, d: u64, s: u64, l: u64| ins(n, "ENC_VOP3", &[("VDST", d), ("SRC0", s), ("SRC1", 128 + l)], None); + let mut parts = vec![ + ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 1), ("SRC1", 1), ("SRC2", V)], None), + ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 0), ("SRC0", V + 2), ("SRC1", 2), ("SRC2", V + 20)], None), + s1("S_MOV", 30, 126), + s1("S_NOT", 126, 126), + all(), + s1("S_BCNT1_I32", 20, 106), + s1("S_MOV", 126, 30), + s1("S_OR_SAVEEXEC", 12, 193), + all(), + s1("S_BCNT1_I32", 21, 106), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 135)], None), + s1("S_MOV", 126, 30), + lane("V_READLANE_B32", 22, V + 9, last), + lane("V_WRITELANE_B32", 10, 128 + 33, last - 1), + lane("V_READLANE_B32", 23, V + 10, last - 1), + ]; + for k in 0..4 { + parts.push(ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 24 + k), ("SRC0", 20 + k)], None)); + } + parts.extend([ + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 30), ("SRC0", 132), ("VSRC1", 0)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 30), ("SRC0", 0), ("VSRC1", 30)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 31), ("SRC0", 128)], None), + ins("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 30), ("DATA", 24), ("SADDR", 0x7D)], None), + ]); + program_of(&parts) +} + +/// Runs `lanes_not_launched_program` in groups of each of `groups`' dimensions: one line per +/// console wave whose threads did not all store what the console's would (the ISA's +/// definition, not a measurement), and per group in which a thread the console does not +/// have stored anything. +fn lanes_not_launched_mismatches(groups: &[[u32; 3]], wave64: bool, pad_waves: PadWaves) -> Vec { + let (base, lanes) = (0x100usize, if wave64 { 64 } else { 32 }); + let code = lanes_not_launched_program(wave64); + let mut bad = Vec::new(); + for &dims in groups { + let threads = dims.iter().product::(); + let t = translate(&code, &on_gpu(Options { mode: Mode::Compute(cs_of(dims, false)), wave64, pad_waves, ..Default::default() })).unwrap(); + assert!(t.complete(), "{dims:?}: {:?}", t.unsupported_why); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{dims:?}: {e}")); + let mem = vec![0xDEAD_BEEFu32; (base + threads.next_multiple_of(lanes) as usize * 16) / 4]; + let out = runner::dispatch(&dxil, [1, 1, 1], &[base as u32, dims[0], dims[0] * dims[1]], &mem).unwrap_or_else(|e| panic!("{dims:?}: {e}")); + for w in 0..threads.div_ceil(lanes) { + let n = (threads - w * lanes).min(lanes); + let want = [lanes - n, lanes, 7, 33]; + let mut got: Vec<[u32; 4]> = (w * lanes..w * lanes + n).map(|tid| out[base / 4 + tid as usize * 4..][..4].try_into().unwrap()).collect(); + got.dedup(); + if got != [want] { + bad.push(format!("{pad_waves:?} | group {dims:?} wave {w} ({n} lanes) | want {want:?} | got {got:?}")); + } + } + if out[base / 4 + threads as usize * 4..].iter().any(|&x| x != 0xDEAD_BEEF) { + bad.push(format!("{pad_waves:?} | group {dims:?}: a thread past the group's {threads} stored")); + } + } + bad +} + +/// A wave64 compute group that is not whole waves, for a program that can tell: before, a +/// group of 40 threads counted no lane after `s_not_b64 exec, exec` (24 on the console) and +/// 40 after `s_or_saveexec_b64 s, -1` (64), and lost what it wrote to lane 62. In 1-D, 2-D +/// and 3-D groups; without the padding lanes (`PadWaves::Never`: the translation as it was) +/// each of the 11 partial waves differs. +#[test] +fn gpu_wave64_valu_code_in_lanes_not_launched() { + if !gpu_ready() { + return; + } + let groups = [[64, 1, 1], [40, 1, 1], [42, 1, 1], [20, 1, 1], [10, 1, 1], [96, 1, 1], [8, 5, 1], [4, 5, 2], [6, 7, 1], [2, 5, 1], [8, 12, 1], [1, 1, 1]]; + let bad = lanes_not_launched_mismatches(&groups, true, PadWaves::WhereSeen); + assert!(bad.is_empty(), "{bad:#?}"); + let before = lanes_not_launched_mismatches(&groups, true, PadWaves::Never); + assert_eq!(before.len(), 11, "{before:#?}"); +} + +/// The same for wave32 programs: groups of 20, 10, 52 (a full wave and 20 lanes), 5 x 4 and +/// 1 threads; a group of 32 is a whole wave. +#[test] +fn gpu_wave32_valu_code_in_lanes_not_launched() { + if !gpu_ready() { + return; + } + let groups = [[32, 1, 1], [20, 1, 1], [10, 1, 1], [52, 1, 1], [5, 4, 1], [1, 1, 1]]; + let bad = lanes_not_launched_mismatches(&groups, false, PadWaves::WhereSeen); + assert!(bad.is_empty(), "{bad:#?}"); + let before = lanes_not_launched_mismatches(&groups, false, PadWaves::Never); + assert_eq!(before.len(), 5, "{before:#?}"); +} + +/// Only a program that can tell gets the padded group (`partial_waves`), and only in a group +/// that is not whole waves: every other translation is the one it was. +#[test] +fn compute_groups_are_padded_only_where_the_program_can_tell() { + // the switches (for comparison) replace `WhereSeen` + if std::env::var_os("XCL_CS_PAD_ALL").is_some() || std::env::var_os("XCL_NO_CS_PAD").is_some() { + return; + } + // an if block: EXEC stays inside the launched lanes + let plain = prog(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)], None), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 106)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 129)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 6)], None), + ]); + let wide = lanes_not_launched_program(true); + let hlsl = |code: &[u8], dims: [u32; 3], wave64: bool, split: bool, pad: PadWaves| { + let t = translate(code, &Options { mode: Mode::Compute(cs_of(dims, false)), wave64, split_wave64: split, pad_waves: pad, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + t.hlsl + }; + for split in [false, true] { + for dims in [[40, 1, 1], [8, 5, 1], [96, 1, 1], [1, 1, 1]] { + let h = hlsl(&plain, dims, true, split, PadWaves::WhereSeen); + assert!(h.contains(&format!("[numthreads({}, {}, {})]", dims[0], dims[1], dims[2])) && h.contains("(true); exec_lo = e0.x;"), "{dims:?}"); + assert_eq!(h, hlsl(&plain, dims, true, split, PadWaves::Never), "{dims:?}"); + } + // one that can: whole waves, the lanes past its threads inactive at the start + for (dims, padded, threads) in [([40, 1, 1], 64, 40), ([8, 5, 1], 64, 40), ([1, 1, 1], 64, 1), ([4, 4, 6], 128, 96), ([1000, 1, 1], 1024, 1000)] { + let h = hlsl(&wide, dims, true, split, PadWaves::WhereSeen); + assert!(h.contains(&format!("[numthreads({padded}, 1, 1)]")) && h.contains(&format!("(gi < {threads}u); exec_lo = e0.x;")), "{dims:?}"); + // the split form's halves both exist then + assert_eq!(h.contains(&format!("#define XCL_X_THREADS {padded}u")), split, "{dims:?}"); + } + // whole waves are never padded + for dims in [[64, 1, 1], [8, 8, 4]] { + assert_eq!(hlsl(&wide, dims, true, split, PadWaves::Always), hlsl(&wide, dims, true, split, PadWaves::Never), "{dims:?}"); + } + } + // a wave32 program's waves have 32 lanes + let h = hlsl(&lanes_not_launched_program(false), [20, 1, 1], false, false, PadWaves::WhereSeen); + assert!(h.contains("[numthreads(32, 1, 1)]") && h.contains("(gi < 20u); exec_lo = e0.x;")); +} + +/// What a program sees of its group when the group is padded to whole waves is what it sees +/// otherwise: thread ids (1-D, 2-D and 3-D groups), the group id, TG_SIZE, its lane and the +/// launched lanes of its wave, LDS shared across the group around `s_barrier`, and memory – +/// each console thread runs once (an atomic count per group) and no padding lane stores. +/// Wave64 programs (split on 32-lane GPUs: the barrier and the counter-paired forms) and +/// wave32 ones, three groups each. +#[test] +fn gpu_padded_compute_groups_look_the_same_to_the_program() { + if !gpu_ready() { + return; + } + let w64 = [[40u32, 1, 1], [20, 1, 1], [10, 1, 1], [96, 1, 1], [8, 5, 1], [4, 5, 2], [4, 4, 6], [3, 1, 1], [1, 1, 1]]; + let w32 = [[20u32, 1, 1], [10, 1, 1], [52, 1, 1], [5, 4, 1], [1, 1, 1]]; + for (wave64, dims) in w64.map(|d| (true, d)).into_iter().chain(w32.map(|d| (false, d))) { + let lanes: u32 = if wave64 { 64 } else { 32 }; + let (x, xy, n) = (dims[0], dims[0] * dims[1], dims.iter().product::()); + let mut parts = vec![ + // v21 = thread index in the group + ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 1), ("SRC1", 1), ("SRC2", V)], None), + ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 2), ("SRC1", 2), ("SRC2", V + 20)], None), + // LDS[4 · thread] = thread + 100; after the barrier, the word of thread n - 1 - thread + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 22), ("SRC0", 130), ("VSRC1", 21)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 23), ("SRC0", 255), ("VSRC1", 21)], Some(100)), + ins("DS_WRITE_B32", "ENC_DS", &[("ADDR", 22), ("DATA0", 23)], None), + ins("S_BARRIER", "ENC_SOPP", &[], None), + ins("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 32), ("SRC0", 3), ("VSRC1", 21)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 32), ("SRC0", 193), ("VSRC1", 32)], None), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 32), ("SRC0", 130), ("VSRC1", 32)], None), + ins("DS_READ_B32", "ENC_DS", &[("VDST", 29), ("ADDR", 32)], None), + // count[group] += 1 at s0 - 64 + 4 · group + ins("S_SUB_U32", "ENC_SOP2", &[("SDST", 8), ("SSRC0", 0), ("SSRC1", 192)], None), + ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 9), ("SSRC0", 128)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 40), ("SRC0", 4)], None), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 40), ("SRC0", 130), ("VSRC1", 40)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 41), ("SRC0", 129)], None), + ins("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 42), ("ADDR", 40), ("DATA", 41), ("SADDR", 8), ("OFFSET", 0), ("GLC", 1)], None), + // the thread id, TG_SIZE (s5), the group id (s4), the lane and the wave's lanes + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 24), ("SRC0", V)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", V + 1)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 26), ("SRC0", V + 2)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 27), ("SRC0", 5)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 28), ("SRC0", 4)], None), + ins("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 126), ("SRC1", 128)], None), + ]; + if wave64 { + parts.push(ins("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 127), ("SRC1", V + 30)], None)); + parts.push(ins("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 126)], None)); + } else { + parts.push(ins("S_BCNT1_I32_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 126)], None)); + } + parts.extend([ + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 31), ("SRC0", 10)], None), + // out[(group · 256 + thread) · 32]: v24..v27, v28..v31 + ins("S_LSHL_B32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 4), ("SSRC1", 136)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 34), ("SRC0", 11), ("VSRC1", 21)], None), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 34), ("SRC0", 133), ("VSRC1", 34)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 34), ("SRC0", 0), ("VSRC1", 34)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 35), ("SRC0", 128)], None), + ins("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 34), ("DATA", 24), ("SADDR", 0x7D)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 34), ("SRC0", 144), ("VSRC1", 34)], None), + ins("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 34), ("DATA", 28), ("SADDR", 0x7D)], None), + ]); + let code = program_of(&parts); + let (base, groups) = (0x100usize, 3usize); + let mut tg_size = Vec::new(); + for pad in [PadWaves::Never, PadWaves::Always, PadWaves::WhereSeen] { + let what = format!("{dims:?}, wave{lanes}, {pad:?}"); + let t = translate(&code, &on_gpu(Options { mode: Mode::Compute(cs_of(dims, true)), wave64, pad_waves: pad, ..Default::default() })).unwrap(); + assert!(t.complete(), "{what}: {:?}", t.unsupported_why); + let padded = t.hlsl.contains(&format!("[numthreads({}, 1, 1)]", n.next_multiple_of(lanes))); + // nothing here turns on a lane the wave did not launch: only `Always` pads + // (`XCL_CS_PAD_ALL` makes `WhereSeen` that) + assert_eq!(padded, pad == PadWaves::Always || pad == PadWaves::WhereSeen && std::env::var_os("XCL_CS_PAD_ALL").is_some(), "{what}"); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{what}: {e}")); + let mut mem = vec![0xDEAD_BEEFu32; (base + groups * 256 * 32) / 4]; + mem[..base / 4].fill(0); + let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &[base as u32, x, xy, n], &mem).unwrap_or_else(|e| panic!("{what}: {e}")); + let mut tg = Vec::new(); + for g in 0..groups { + assert_eq!(out[(base - 64) / 4 + g], n, "{what}: threads of group {g} that ran"); + for tid in 0..256u32 { + let at = (base + (g * 256 + tid as usize) * 32) / 4; + let got = &out[at..at + 8]; + if tid >= n { + assert!(got.iter().all(|&v| v == 0xDEAD_BEEF), "{what}: group {g}, a thread {tid} stored"); + continue; + } + let (wave, lane) = (tid / lanes, tid % lanes); + assert_eq!(&got[..3], &[tid % x, tid / x % dims[1], tid / xy], "{what}: group {g} thread {tid}: thread id"); + assert_eq!(got[3] >> 6, wave, "{what}: group {g} thread {tid}: wave in TG_SIZE"); + assert_eq!(got[4], g as u32, "{what}: thread {tid}: group id"); + assert_eq!(got[5], n - 1 - tid + 100, "{what}: group {g} thread {tid}: LDS word of thread {}", n - 1 - tid); + assert_eq!(got[6], lane, "{what}: group {g} thread {tid}: lane"); + assert_eq!(got[7], (n - wave * lanes).min(lanes), "{what}: group {g} thread {tid}: lanes of its wave"); + tg.push(got[3]); + } + } + tg_size.push(tg); + } + assert!(tg_size[0] == tg_size[1] && tg_size[0] == tg_size[2], "{dims:?}, wave{lanes}: TG_SIZE with and without padding"); + } +} diff --git a/crates/xcl/src/gpu/recomp/upper_lanes.rs b/crates/xcl/src/gpu/recomp/upper_lanes.rs index d6981b2..db1c867 100644 --- a/crates/xcl/src/gpu/recomp/upper_lanes.rs +++ b/crates/xcl/src/gpu/recomp/upper_lanes.rs @@ -484,7 +484,7 @@ fn evaluate(d: &Decoded, st: &State, vdst: u64) -> Option<[Hi; 32]> { } /// SGPRs an instruction may write (first register, count), from its output operands. -fn sgpr_outputs(d: &Decoded) -> Vec<(u64, u64)> { +pub(super) fn sgpr_outputs(d: &Decoded) -> Vec<(u64, u64)> { let mut out = Vec::new(); for o in d.ienc.operands.iter().filter(|o| o.output) { let n = (o.size as u64).div_ceil(32).max(1); @@ -512,7 +512,7 @@ fn sgpr_outputs(d: &Decoded) -> Vec<(u64, u64)> { out } -fn is_valu(d: &Decoded) -> bool { +pub(super) fn is_valu(d: &Decoded) -> bool { d.enc.name.starts_with("ENC_VOP") || d.enc.name.starts_with("VOP") } @@ -713,7 +713,7 @@ fn classify(d: &Decoded, st: &State) -> Option<(Read, Option<(u64, u32)>)> { } /// Successors of each instruction (index); None: unknown (an indirect jump). -fn successors(insts: &[Decoded], pcs: &BTreeMap) -> Vec>> { +pub(super) fn successors(insts: &[Decoded], pcs: &BTreeMap) -> Vec>> { insts .iter() .enumerate() diff --git a/crates/xcl/src/hle/bcpack/bc1.rs b/crates/xcl/src/hle/bcpack/bc1.rs new file mode 100644 index 0000000..a9c91a4 --- /dev/null +++ b/crates/xcl/src/hle/bcpack/bc1.rs @@ -0,0 +1,94 @@ +//! BC1 blocks from the 12 lanes of a BCPack BC1 stream (one symbol per lane and block). +//! +//! For block `i`, in stream order: +//! * lane 0 is a distance `d` back to the block whose endpoints predict this one's: symbol 0 is +//! "none" (predict zeros), an even symbol `v` is `v / 2`, an odd one `255 - v / 2`. Block +//! `i - d` is meant, and before block 0 a built-in history of 255 endpoint sets, the same for +//! every stream ([`Tables::history`]), +//! * lane 1 was 0 in every stream the format notes describe, +//! * lanes 2–7 are the differences of R0, G0, B0, R1, G1, B1 from the prediction, 0, -1, 1, +//! -2, 2 … for the symbols 0, 1, 2, 3, 4 …, modulo the channel's range (5, 6, 5 bits), +//! * lanes 8–11 are the selectors of the top-left, top-right, bottom-left and bottom-right 2×2 +//! texels, each symbol the index of one of the 256 possible quadrants in a fixed order +//! ([`Tables::quadrants`]). +//! +//! The blocks are in the order of the surface's memory, tiled as the console stores it. +//! +//! After the BC1 sections of the public format notes of bcpack-decoder (Tim0219800, +//! `docs/SPEC.md`) and bcpack-rs (Ahmet Dedeler, `docs/BCPACK_SPEC.md`), both MIT; written for +//! XCL on 2026-11-23. + +use super::{lanes, lane_widths, Error}; + +/// The constants of the BC1 rebuild that are not in a stream. +pub struct Tables { + /// The endpoints `[R0, G0, B0, R1, G1, B1]` of the blocks before a stream's first: + /// `history[256 - k]` is the block `k` before block 0 (k = 1..=255; entry 0 is never read). + /// `None`: not known. + pub history: [Option<[u8; 6]>; 256], + /// The selectors of each quadrant symbol, 2 bits a texel: bits 0–1 the top-left texel, + /// 2–3 top-right, 4–5 bottom-left, 6–7 bottom-right. + pub quadrants: [u8; 256], +} + +/// The range of each endpoint channel. +const RANGE: [u8; 6] = [32, 64, 32, 32, 64, 32]; + +/// Unpack a BC1 stream to its `out_len` bytes of blocks. +pub fn decode(src: &[u8], out_len: usize, tables: &Tables) -> Result, Error> { + let widths = lane_widths(1).unwrap(); + if out_len % 8 != 0 { + return Err(Error::OutputSize); + } + 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 endpoints `[R0, G0, B0, R1, G1, B1]` of a block. +fn endpoints(block: &[u8]) -> [u8; 6] { + let c0 = u16::from_le_bytes([block[0], block[1]]); + let c1 = u16::from_le_bytes([block[2], block[3]]); + [(c0 >> 11) as u8, (c0 >> 5 & 63) as u8, (c0 & 31) as u8, (c1 >> 11) as u8, (c1 >> 5 & 63) as u8, (c1 & 31) as u8] +} + +/// The blocks of `symbols` (12 per block, in [`super::decode_lanes`]'s order). +pub fn assemble(symbols: &[u8], tables: &Tables) -> Result, Error> { + let blocks = symbols.len() / 12; + let mut out = Vec::new(); + out.try_reserve_exact(blocks * 8).map_err(|_| Error::OutputSize)?; + out.resize(blocks * 8, 0u8); + for (i, s) in symbols.chunks_exact(12).enumerate() { + if s[1] != 0 { + return Err(Error::Lane1 { block: i }); + } + let v = s[0] as usize; + let d = if v % 2 == 0 { v / 2 } else { 255 - v / 2 }; + let predicted = if d == 0 { + [0; 6] + } else if d <= i { + endpoints(&out[(i - d) * 8..]) + } else { + let slot = 256 + i - d; + tables.history[slot].ok_or(Error::History { block: i, slot })? + }; + let mut e = [0u16; 6]; + for c in 0..6 { + let v = s[2 + c] as i32; + let delta = if v % 2 == 0 { v / 2 } else { -(v / 2) - 1 }; + e[c] = (predicted[c] as i32 + delta).rem_euclid(RANGE[c] as i32) as u16; + } + let [tl, tr, bl, br] = [8, 9, 10, 11].map(|l| tables.quadrants[s[l] as usize]); + let b = &mut out[i * 8..i * 8 + 8]; + b[..2].copy_from_slice(&(e[0] << 11 | e[1] << 5 | e[2]).to_le_bytes()); + b[2..4].copy_from_slice(&(e[3] << 11 | e[4] << 5 | e[5]).to_le_bytes()); + // a row of the block is four texels, 2 bits each, the left one lowest + b[4] = (tl & 15) | (tr & 15) << 4; + b[5] = (tl >> 4) | (tr >> 4) << 4; + b[6] = (bl & 15) | (br & 15) << 4; + b[7] = (bl >> 4) | (br >> 4) << 4; + } + Ok(out) +} diff --git a/crates/xcl/src/hle/bcpack/bc1_fitted.rs b/crates/xcl/src/hle/bcpack/bc1_fitted.rs new file mode 100644 index 0000000..e7bafc2 --- /dev/null +++ b/crates/xcl/src/hle/bcpack/bc1_fitted.rs @@ -0,0 +1,125 @@ +// Generated by scripts/gen_bcpack_bc1_tables.py from the tables of +// bcpack-rs by Ahmet Dedeler (https://github.com/Ahmet-Dedeler/bcpack-rs, commit c51ec52, +// data/bc1_window.json and data/bc1_quad_table.json), used under its MIT license: +// +// MIT License +// +// Copyright (c) 2026 Ahmet Dedeler +// +// 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 BC1 block rebuild that no stream carries. They were estimated by +// bcpack-rs from retail data (decoded blocks against the next smaller mip level, which is +// stored unpacked); they are constants of the codec, not game content. Being estimates, they +// make the BC1 output of XCL an approximation wherever one of them is wrong: +// * history: 254 of the 255 entries that can be read; the `None` ones were never referred to +// in the data of the fit. Fits on two halves of that data differ, by a step or so, in +// 17 entries (12, 14, 30, 47, 59, 67, 70, 83, 108, 125, 127, 130, 152, 159, 176, 231, 236). +// * quadrants: all 256. Fits on two halves of the data swap 8 entries +// (229, 230, 231, 235, 247, 248, 254, 255; rare mirror pairs). +// A block rebuilt from a history entry carries its error, and so do the blocks that refer to it. + +use super::bc1::Tables; + +pub static TABLES: Tables = Tables { + history: [ + None, Some([7, 29, 6, 8, 30, 7]), Some([15, 29, 15, 16, 36, 17]), Some([20, 37, 14, 3, 6, 2]), + None, Some([10, 21, 11, 6, 15, 7]), Some([12, 23, 11, 7, 15, 6]), Some([12, 26, 12, 7, 15, 7]), + Some([22, 36, 15, 20, 32, 14]), Some([14, 23, 8, 1, 2, 1]), Some([23, 5, 30, 9, 5, 30]), Some([11, 22, 11, 7, 15, 7]), + Some([17, 22, 7, 10, 11, 3]), Some([12, 25, 12, 7, 16, 7]), Some([13, 28, 8, 5, 12, 3]), Some([11, 20, 8, 16, 31, 14]), + Some([23, 32, 30, 17, 12, 29]), Some([8, 44, 30, 6, 26, 30]), Some([10, 24, 30, 6, 45, 30]), Some([10, 12, 4, 8, 8, 2]), + Some([16, 23, 30, 14, 6, 26]), Some([12, 25, 13, 10, 22, 12]), Some([19, 27, 10, 13, 16, 5]), Some([11, 24, 12, 4, 11, 6]), + Some([29, 60, 29, 6, 13, 6]), Some([17, 31, 11, 1, 2, 1]), Some([26, 54, 24, 12, 24, 10]), Some([23, 48, 30, 20, 37, 30]), + Some([16, 23, 10, 10, 15, 6]), Some([11, 24, 10, 6, 13, 5]), Some([18, 52, 30, 14, 22, 30]), Some([14, 51, 30, 9, 34, 30]), + Some([2, 3, 1, 19, 37, 16]), Some([14, 15, 30, 10, 32, 30]), Some([29, 57, 27, 27, 52, 25]), Some([13, 29, 15, 8, 20, 11]), + Some([13, 17, 5, 9, 10, 3]), Some([18, 50, 29, 15, 10, 29]), Some([11, 25, 13, 8, 19, 10]), Some([17, 31, 12, 6, 12, 4]), + Some([22, 18, 30, 19, 41, 30]), Some([10, 22, 11, 8, 18, 9]), Some([18, 30, 31, 10, 44, 30]), Some([25, 50, 24, 2, 4, 1]), + Some([11, 30, 31, 7, 15, 29]), Some([12, 19, 8, 11, 16, 7]), Some([19, 29, 30, 14, 55, 28]), Some([9, 20, 10, 4, 10, 5]), + Some([12, 23, 10, 7, 14, 5]), Some([26, 53, 25, 6, 13, 6]), Some([19, 27, 31, 11, 19, 30]), Some([21, 31, 30, 22, 31, 30]), + Some([10, 19, 5, 11, 21, 6]), Some([30, 50, 3, 29, 46, 2]), Some([15, 9, 30, 7, 9, 30]), Some([14, 18, 6, 11, 14, 4]), + Some([28, 56, 26, 4, 7, 3]), Some([8, 20, 10, 6, 13, 7]), Some([28, 58, 26, 15, 32, 14]), Some([10, 19, 8, 7, 10, 4]), + Some([16, 22, 9, 13, 17, 7]), Some([1, 2, 1, 14, 28, 12]), Some([22, 45, 30, 9, 15, 30]), Some([19, 22, 30, 16, 23, 31]), + Some([25, 50, 24, 21, 43, 20]), Some([6, 11, 4, 16, 31, 13]), Some([13, 25, 8, 3, 6, 1]), Some([5, 9, 3, 12, 24, 10]), + Some([16, 29, 13, 8, 14, 6]), Some([20, 37, 16, 13, 26, 10]), Some([18, 35, 15, 5, 9, 3]), Some([13, 25, 11, 7, 12, 5]), + Some([11, 21, 7, 7, 14, 4]), Some([20, 39, 16, 11, 21, 8]), Some([16, 31, 12, 4, 8, 2]), Some([22, 41, 30, 18, 23, 30]), + Some([24, 50, 24, 9, 20, 8]), Some([3, 12, 7, 4, 16, 8]), Some([18, 27, 12, 16, 22, 10]), Some([24, 49, 23, 13, 28, 12]), + Some([24, 49, 24, 18, 38, 18]), Some([17, 32, 12, 14, 28, 9]), Some([20, 10, 31, 13, 10, 31]), Some([7, 8, 2, 5, 5, 1]), + Some([1, 2, 1, 10, 21, 9]), Some([10, 18, 6, 1, 1, 0]), Some([22, 46, 21, 1, 3, 1]), Some([11, 20, 8, 8, 14, 5]), + Some([17, 35, 31, 14, 14, 29]), Some([16, 22, 31, 12, 40, 31]), Some([12, 22, 9, 8, 15, 6]), Some([18, 15, 30, 15, 33, 31]), + Some([19, 32, 30, 15, 43, 31]), Some([18, 35, 15, 8, 15, 5]), Some([21, 43, 20, 18, 37, 17]), Some([10, 17, 6, 9, 15, 6]), + Some([14, 27, 12, 7, 14, 5]), Some([8, 15, 7, 12, 26, 11]), Some([18, 37, 17, 1, 1, 0]), Some([17, 45, 30, 15, 33, 31]), + Some([13, 24, 11, 8, 17, 7]), Some([23, 47, 22, 16, 32, 15]), Some([18, 33, 13, 11, 22, 8]), Some([4, 10, 4, 8, 17, 7]), + Some([1, 2, 1, 3, 7, 3]), Some([11, 22, 9, 6, 12, 4]), Some([16, 28, 11, 13, 24, 9]), Some([12, 24, 12, 7, 13, 6]), + Some([23, 47, 22, 7, 15, 6]), Some([11, 32, 30, 11, 31, 30]), Some([14, 26, 11, 10, 19, 7]), Some([20, 41, 19, 1, 3, 1]), + Some([14, 27, 12, 8, 17, 6]), Some([11, 21, 9, 8, 15, 6]), Some([1, 2, 1, 7, 13, 6]), Some([19, 34, 14, 16, 30, 12]), + Some([13, 27, 13, 7, 16, 7]), Some([15, 32, 16, 8, 19, 9]), Some([15, 42, 31, 11, 22, 30]), Some([23, 48, 23, 5, 10, 4]), + Some([22, 45, 21, 11, 23, 10]), Some([31, 62, 30, 31, 61, 29]), Some([13, 26, 11, 5, 8, 3]), Some([19, 39, 19, 9, 21, 10]), + Some([7, 14, 2, 6, 12, 2]), Some([21, 42, 20, 4, 7, 3]), Some([10, 17, 7, 8, 13, 5]), Some([10, 22, 8, 11, 19, 7]), + Some([19, 33, 31, 12, 31, 31]), Some([21, 43, 20, 5, 11, 5]), Some([9, 21, 8, 8, 13, 7]), Some([10, 21, 10, 6, 13, 6]), + Some([15, 29, 12, 11, 21, 8]), Some([21, 43, 20, 9, 19, 8]), Some([3, 8, 3, 5, 11, 5]), Some([16, 31, 13, 9, 18, 7]), + Some([11, 21, 11, 6, 13, 6]), Some([10, 21, 10, 7, 15, 7]), Some([27, 3, 1, 26, 1, 0]), Some([18, 37, 18, 16, 32, 16]), + Some([12, 23, 10, 9, 18, 7]), Some([12, 25, 12, 8, 18, 8]), Some([11, 20, 9, 2, 5, 1]), Some([7, 15, 7, 8, 18, 9]), + Some([17, 33, 15, 13, 24, 11]), Some([9, 19, 9, 7, 15, 7]), Some([21, 43, 20, 13, 28, 12]), Some([17, 36, 17, 2, 4, 2]), + Some([10, 19, 9, 6, 13, 5]), Some([20, 41, 19, 7, 14, 7]), Some([3, 9, 6, 2, 8, 5]), Some([13, 24, 10, 11, 20, 8]), + Some([18, 39, 18, 6, 10, 5]), Some([19, 38, 18, 8, 17, 8]), Some([16, 35, 17, 4, 11, 4]), Some([11, 23, 11, 10, 21, 10]), + Some([17, 36, 17, 7, 15, 7]), Some([13, 27, 13, 7, 13, 7]), Some([9, 15, 4, 8, 13, 4]), Some([9, 19, 7, 6, 9, 3]), + Some([19, 39, 19, 11, 25, 11]), Some([11, 23, 11, 8, 17, 8]), Some([14, 29, 14, 7, 16, 7]), Some([12, 22, 8, 5, 9, 4]), + Some([10, 20, 9, 8, 17, 8]), Some([21, 41, 19, 15, 32, 14]), Some([14, 28, 13, 1, 2, 0]), Some([8, 16, 8, 7, 14, 7]), + Some([9, 18, 8, 8, 16, 7]), Some([10, 17, 7, 3, 4, 1]), Some([14, 28, 13, 2, 4, 1]), Some([14, 30, 14, 3, 6, 3]), + Some([19, 38, 18, 5, 11, 5]), Some([12, 26, 12, 1, 2, 1]), Some([9, 16, 6, 8, 13, 5]), Some([8, 13, 4, 7, 11, 4]), + Some([16, 35, 16, 4, 8, 4]), Some([13, 28, 13, 4, 9, 4]), Some([15, 31, 15, 6, 13, 6]), Some([12, 24, 11, 9, 19, 9]), + Some([9, 19, 8, 7, 14, 6]), Some([14, 28, 13, 5, 10, 4]), Some([10, 21, 7, 4, 6, 2]), Some([16, 34, 17, 11, 25, 12]), + Some([15, 30, 15, 8, 16, 8]), Some([13, 27, 13, 10, 20, 10]), Some([9, 20, 9, 0, 1, 0]), Some([16, 32, 15, 2, 4, 2]), + Some([13, 27, 12, 3, 6, 3]), Some([13, 26, 12, 12, 23, 11]), Some([12, 25, 12, 5, 11, 5]), Some([11, 23, 11, 5, 11, 5]), + Some([16, 34, 16, 7, 13, 6]), Some([16, 35, 31, 15, 25, 31]), Some([16, 33, 16, 7, 16, 7]), Some([13, 26, 13, 8, 19, 8]), + Some([18, 35, 17, 11, 23, 10]), Some([18, 36, 18, 13, 28, 13]), Some([12, 25, 12, 4, 9, 4]), Some([9, 18, 7, 6, 11, 4]), + Some([15, 30, 14, 9, 20, 9]), Some([17, 35, 16, 9, 19, 9]), Some([11, 24, 11, 2, 4, 2]), Some([16, 33, 16, 0, 1, 0]), + Some([15, 31, 15, 4, 9, 4]), Some([16, 31, 15, 14, 27, 13]), Some([14, 29, 14, 13, 25, 12]), Some([11, 23, 11, 3, 6, 3]), + Some([16, 32, 16, 10, 22, 10]), Some([11, 22, 11, 4, 9, 4]), Some([11, 22, 10, 1, 2, 0]), Some([8, 14, 5, 2, 4, 1]), + Some([9, 16, 6, 6, 10, 4]), Some([10, 21, 10, 9, 19, 9]), Some([14, 29, 14, 11, 23, 11]), Some([9, 18, 8, 6, 13, 6]), + Some([6, 13, 6, 5, 11, 5]), Some([7, 14, 6, 0, 1, 0]), Some([4, 7, 2, 3, 4, 1]), Some([10, 20, 9, 4, 8, 4]), + Some([9, 17, 7, 5, 9, 3]), Some([7, 14, 7, 1, 2, 1]), Some([10, 20, 10, 6, 11, 5]), Some([8, 15, 5, 4, 6, 2]), + Some([8, 17, 8, 1, 2, 1]), Some([10, 20, 10, 3, 6, 3]), Some([7, 10, 3, 6, 8, 3]), Some([8, 15, 7, 6, 12, 6]), + Some([9, 19, 9, 2, 4, 2]), Some([6, 11, 4, 3, 4, 1]), Some([6, 11, 4, 0, 1, 0]), Some([8, 16, 7, 2, 5, 2]), + Some([16, 34, 16, 15, 29, 15]), Some([7, 16, 7, 5, 10, 5]), Some([8, 14, 5, 5, 9, 3]), Some([9, 18, 8, 4, 8, 4]), + Some([5, 9, 3, 4, 7, 2]), Some([9, 18, 8, 5, 10, 5]), Some([6, 12, 6, 2, 4, 2]), Some([7, 12, 5, 4, 7, 3]), + Some([5, 11, 5, 1, 2, 1]), Some([8, 17, 8, 3, 6, 3]), Some([16, 31, 31, 16, 32, 31]), Some([7, 14, 7, 3, 6, 3]), + Some([5, 11, 6, 4, 9, 4]), Some([7, 15, 7, 4, 8, 4]), Some([2, 4, 2, 0, 0, 1]), Some([5, 11, 5, 3, 6, 3]), + Some([4, 8, 4, 1, 1, 1]), Some([3, 6, 3, 1, 2, 1]), Some([2, 4, 1, 1, 2, 1]), Some([4, 8, 4, 3, 6, 3]), + Some([3, 6, 3, 2, 4, 2]), Some([4, 9, 4, 2, 4, 2]), Some([17, 27, 31, 15, 34, 31]), Some([0, 0, 1, 0, 0, 0]), + ], + quadrants: [ + 170, 255, 0, 85, 250, 175, 251, 191, 254, 239, 187, 238, 223, 186, 90, 174, + 127, 234, 171, 247, 253, 165, 95, 245, 221, 119, 102, 153, 42, 138, 162, 80, + 5, 168, 17, 154, 68, 63, 166, 169, 207, 190, 252, 243, 106, 235, 126, 231, + 219, 189, 122, 167, 218, 15, 173, 87, 213, 10, 93, 117, 47, 110, 240, 143, + 248, 230, 61, 242, 185, 37, 124, 155, 59, 133, 206, 236, 88, 179, 211, 160, + 82, 222, 123, 43, 183, 94, 199, 237, 91, 178, 142, 204, 111, 25, 246, 159, + 100, 232, 229, 41, 249, 51, 70, 34, 181, 215, 45, 120, 86, 134, 136, 104, + 145, 149, 146, 210, 135, 125, 118, 103, 157, 89, 101, 217, 21, 55, 147, 92, + 198, 53, 108, 205, 57, 69, 220, 84, 115, 81, 83, 197, 46, 139, 141, 39, + 226, 31, 244, 29, 216, 241, 114, 163, 79, 116, 184, 202, 58, 172, 209, 137, + 71, 38, 98, 152, 112, 13, 161, 26, 74, 107, 27, 208, 164, 233, 7, 177, + 158, 182, 228, 78, 188, 227, 62, 203, 130, 49, 2, 40, 76, 19, 196, 32, + 14, 11, 8, 150, 128, 224, 9, 176, 105, 96, 6, 144, 35, 151, 140, 214, + 33, 109, 121, 50, 200, 72, 132, 23, 18, 212, 77, 113, 1, 54, 99, 156, + 201, 64, 4, 16, 225, 97, 148, 73, 75, 30, 180, 22, 3, 12, 192, 66, + 129, 24, 48, 36, 195, 60, 194, 20, 65, 131, 44, 56, 67, 52, 28, 193, + ], +}; diff --git a/crates/xcl/src/hle/bcpack/lanes.rs b/crates/xcl/src/hle/bcpack/lanes.rs new file mode 100644 index 0000000..7cf65f3 --- /dev/null +++ b/crates/xcl/src/hle/bcpack/lanes.rs @@ -0,0 +1,350 @@ +//! The entropy stage of BCPack: a set of rANS decoders ("lanes") that share one byte stream. +//! +//! Every lane yields one symbol per 8 bytes of output. A lane's own bytes are a chain of +//! fragments, each a 2- or 3-byte header and its payload: +//! * byte 0: bits 0–3 the model `q`, bit 4 "reset the state when this fragment ends", bit 5 +//! "a third header byte follows", bits 6–7 `z`, by how many bits this fragment's symbols are +//! narrower than the lane's, +//! * the payload length: byte 1 plus 1, or with a third byte `(byte 2 << 8 | byte 1) + 257`; +//! it counts every byte the lane reads in the fragment, the first state bytes included. +//! +//! The state is 32 bits with the lower limit `L` = 2^24 and 16-bit probabilities; a byte is +//! shifted in while it is below `L`, a symbol leaves while it is above. A fragment's encoder +//! started at `L`, so a decoded fragment ends there, or at `L >> 8` / `L >> 16` when the +//! encoder dropped trailing zero bytes. +//! +//! Which lane gets which byte of the stream is decided clock by clock, as in the hardware: +//! * each lane holds one byte of input and one symbol of output; in a clock it first applies +//! its last symbol to the state and takes a byte, then reads a header byte or shifts the byte +//! in and decodes, +//! * the lanes that ask for a byte are served in lane order, eight bytes a clock at most; a +//! lane that asked and got none does nothing in that clock, +//! * a lane hands its symbol over only when its place in the symbol vector is free, and the +//! places are freed together when every lane has filled its own. A lane with a symbol it +//! cannot hand over does nothing either. +//! +//! The lane is a port of the `decoder` module of Microsoft's silicon-rans sample +//! (`mdu_minirans.v`, Copyright (c) Microsoft Corporation, MIT), made for XCL on 2026-11-23: +//! same registers, same two phases, same control states. The sample leaves the feeder and the +//! symbol vector out; the two rules above are from the public format notes of bcpack-decoder +//! (Tim0219800) and bcpack-rs (Ahmet Dedeler), both MIT, which report them as checked against +//! retail streams. + +use super::rans_tables::FREQ; +use super::Error; + +/// The lower limit of the rANS state. +pub const L: u32 = 1 << 24; +/// Bytes the feeder hands out per clock. +const FEED_WINDOW: usize = 8; + +/// One of the 16 static models at one symbol width: the cumulative base and the per-symbol +/// frequency of each segment. Segment 0 is symbol 0, segment k >= 1 the symbols +/// `2^(k-1) .. 2^k`. Slot 0 belongs to no symbol: symbol 0 starts at slot 1. +#[derive(Clone, Copy)] +struct Model { + /// `base[k]` for the segments in use, 65536 for the rest + base: [u32; 10], + freq: [u32; 9], +} + +impl Model { + fn new(bits: usize, q: usize) -> Self { + let mut m = Model { base: [65536; 10], freq: [1; 9] }; + let mut at = 0u32; + for k in 0..=bits { + m.base[k] = at; + m.freq[k] = FREQ[bits - 1][q][k] as u32; + at += m.freq[k] * if k < 2 { 1 } else { 1 << (k - 1) }; + } + m + } + + /// The symbol of slot `cf` (1..=65535). + fn symbol(&self, cf: u32) -> u32 { + let mut seg = 0; + for k in 1..9 { + seg += (cf >= self.base[k]) as usize; + } + ((1u32 << seg) >> 1) + (cf - self.base[seg]) / self.freq[seg] + } + + /// The state after `sym` left state `x`. + fn advance(&self, x: u32, sym: u32) -> u32 { + let seg = (32 - sym.leading_zeros()) as usize; + let cfa = self.base[seg] + self.freq[seg] * (sym - ((1u32 << seg) >> 1)); + let (f, cf) = if cfa == 0 { (self.freq[seg] - 1, 1) } else { (self.freq[seg], cfa) }; + f.wrapping_mul(x >> 16).wrapping_add(x & 0xFFFF).wrapping_sub(cf) + } +} + +/// Where a fragment's decoding may end: the state its encoder started from, less the zero +/// bytes (two at most) the encoder's first symbol pushed out and the encoder did not store. +fn is_end_state(x: u32) -> bool { + x == L || x == L >> 8 || x == L >> 16 +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Ctrl { + Hdr0, + Hdr1, + Hdr2, + Processing, + /// the fragment's bytes are all in the state; symbols still leave + Draining, + Done, +} + +struct Lane { + /// the lane's symbol width + bits: u8, + ctrl: Ctrl, + input_buf: u8, + input_buf_full: bool, + sym: u32, + sym_buf_full: bool, + /// its place in the symbol vector is taken + slot_full: bool, + input_remaining: u32, + output_remaining: u32, + /// the state after the last symbol was applied + p0: u32, + /// the state the symbol in `sym` was read from + p1: u32, + hdr3: bool, + flush: bool, + q: u8, + model: Model, + stalled: bool, +} + +/// Decode the lanes of one stream: `widths[i]` is lane i's symbol width in bits (1..=8), +/// `units` the number of symbols every lane holds. The symbols come back unit by unit +/// (`symbols[unit * lanes + lane]`), with the number of bytes of `src` the lanes read. +pub(super) fn decode(src: &[u8], widths: &[u8], units: usize) -> Result<(Vec, usize), Error> { + let mut pos = 0; + let symbols = run(widths, units, |_| { + let b = src.get(pos).copied(); + pos += b.is_some() as usize; + b + })?; + Ok((symbols, pos)) +} + +/// [`decode`] with the stream as a function: the next byte, for the lane that gets it. +pub(super) fn run(widths: &[u8], units: usize, mut next: impl FnMut(usize) -> Option) -> Result, Error> { + let n = widths.len(); + assert!(n > 0 && widths.iter().all(|w| (1..=8).contains(w))); + if units == 0 { + return Ok(Vec::new()); + } + if units > u32::MAX as usize { + return Err(Error::OutputSize); + } + // grows with the units the stream really yields: the size a request names costs nothing + let mut symbols: Vec = Vec::new(); + let mut lanes: Vec = widths + .iter() + .map(|&bits| Lane { + bits, + ctrl: Ctrl::Hdr0, + input_buf: 0, + input_buf_full: false, + sym: 0, + sym_buf_full: false, + slot_full: false, + input_remaining: 0, + output_remaining: units as u32, + p0: 0, + p1: 0, + hdr3: false, + flush: false, + q: 0, + model: Model::new(bits as usize, 0), + stalled: false, + }) + .collect(); + let mut released = 0usize; + + // a lane is done when it has its symbols and has read its last fragment to the end + while lanes.iter().any(|l| l.ctrl != Ctrl::Done || l.sym_buf_full) { + let mut progress = false; + + // phase 0: the feeder fills input buffers, a lane applies its symbol and hands it over + let mut served = 0; + for (i, l) in lanes.iter_mut().enumerate() { + let blocked_on_output = l.sym_buf_full && l.slot_full; + let need = !l.input_buf_full + && match l.ctrl { + Ctrl::Hdr0 | Ctrl::Hdr1 | Ctrl::Hdr2 => true, + Ctrl::Processing => l.input_remaining > 0, + Ctrl::Draining | Ctrl::Done => false, + }; + let mut fed = None; + if need && !blocked_on_output && served < FEED_WINDOW { + // the stream never grows: a lane that waits for a byte past its end waits forever + let Some(b) = next(i) else { return Err(Error::Truncated { lane: i }) }; + fed = Some(b); + served += 1; + } + l.stalled = blocked_on_output || (need && fed.is_none()); + if l.stalled { + continue; + } + if matches!(l.ctrl, Ctrl::Processing | Ctrl::Draining) { + let p0 = if l.sym_buf_full { l.model.advance(l.p1, l.sym) } else { l.p1 }; + progress |= p0 != l.p0; + l.p0 = p0; + } + if let Some(b) = fed { + l.input_buf = b; + l.input_buf_full = true; + progress = true; + } + if l.sym_buf_full { + // the lane's last symbol leaves a state its encoder started from + let done = units - l.output_remaining as usize; + if l.output_remaining == 0 { + if !is_end_state(l.model.advance(l.p1, l.sym)) { + return Err(Error::EndState { lane: i }); + } + } + if symbols.len() < done * n { + symbols.try_reserve(n).map_err(|_| Error::OutputSize)?; + symbols.resize(done * n, 0); + } + symbols[(done - 1) * n + i] = l.sym as u8; + l.sym_buf_full = false; + l.slot_full = true; + progress = true; + } + } + + // phase 1: header bytes, or a byte into the state and a symbol out of it + for (i, l) in lanes.iter_mut().enumerate() { + if l.stalled { + continue; + } + match l.ctrl { + Ctrl::Hdr0 => { + if l.input_buf_full { + let b = l.input_buf; + l.input_buf_full = false; + l.input_remaining = 0; + l.q = b & 15; + l.flush = b & 0x10 != 0; + l.hdr3 = b & 0x20 != 0; + let z = b >> 6; + if z >= l.bits { + return Err(Error::Width { lane: i }); + } + l.model = Model::new((l.bits - z) as usize, l.q as usize); + l.ctrl = Ctrl::Hdr1; + progress = true; + } + } + Ctrl::Hdr1 => { + if l.input_buf_full { + l.input_buf_full = false; + if l.hdr3 { + l.input_remaining = l.input_buf as u32; + l.ctrl = Ctrl::Hdr2; + } else { + l.input_remaining = l.input_buf as u32 + 1; + l.ctrl = Ctrl::Processing; + } + progress = true; + } + } + Ctrl::Hdr2 => { + if l.input_buf_full { + l.input_buf_full = false; + l.input_remaining = ((l.input_buf as u32) << 8 | l.input_remaining) + 257; + l.ctrl = Ctrl::Processing; + progress = true; + } + } + Ctrl::Processing => { + let feed = l.p0 < L && l.input_remaining > 0 && l.input_buf_full; + let x = if feed { l.p0 << 8 | l.input_buf as u32 } else { l.p0 }; + let out = x > L && l.output_remaining > 0; + if out { + l.sym = l.model.symbol(x & 0xFFFF); + if x & 0xFFFF == 0 { + return Err(Error::Symbol { lane: i }); + } + l.output_remaining -= 1; + } + progress |= feed || out || x != l.p1; + l.p1 = x; + l.sym_buf_full = out; + if feed { + l.input_buf_full = false; + l.input_remaining -= 1; + } + if l.input_remaining == 0 { + progress = true; + if l.output_remaining == 0 { + l.ctrl = Ctrl::Done; + } else if x == L { + l.ctrl = Ctrl::Hdr0; + if l.flush { + l.p1 = 0; + } + } else { + l.ctrl = Ctrl::Draining; + } + } + } + Ctrl::Draining => { + let x = l.p0; + let out = x > L && l.output_remaining > 0; + if out { + l.sym = l.model.symbol(x & 0xFFFF); + if x & 0xFFFF == 0 { + return Err(Error::Symbol { lane: i }); + } + l.output_remaining -= 1; + } + progress |= out || x != l.p1; + l.p1 = x; + l.sym_buf_full = out; + if x <= L { + progress = true; + if l.output_remaining == 0 { + l.ctrl = Ctrl::Done; + } else { + l.ctrl = Ctrl::Hdr0; + if l.flush { + // The hardware drops whatever state is left here. A state that + // is thrown away took symbols with it unless it is where the + // fragment's encoder started, so anything else is damage. + if !is_end_state(x) { + return Err(Error::EndState { lane: i }); + } + l.p0 = 0; + l.p1 = 0; + } + } + } + } + Ctrl::Done => {} + } + } + + // the symbol vector leaves when every lane has put its symbol in + if lanes.iter().all(|l| l.slot_full) { + for l in lanes.iter_mut() { + l.slot_full = false; + } + released += 1; + progress = true; + } + if !progress { + // nothing moved in a whole clock, so nothing ever will + return Err(Error::Stuck); + } + } + debug_assert_eq!((released, symbols.len()), (units, units * n)); + Ok(symbols) +} diff --git a/crates/xcl/src/hle/bcpack/mod.rs b/crates/xcl/src/hle/bcpack/mod.rs new file mode 100644 index 0000000..845acaa --- /dev/null +++ b/crates/xcl/src/hle/bcpack/mod.rs @@ -0,0 +1,145 @@ +//! BCPack, the console's lossless packing of BCn texture blocks (`DSTORAGE_BCPACK_MODE`, the +//! DirectStorage stage between zlib and swizzle): a stream unpacks to plain BCn blocks. +//! +//! A stream has no header. The fields of the blocks are split over 12 or 16 rANS lanes, one +//! symbol per lane for every 8 bytes of output, and the lanes share the byte stream +//! (`lanes.rs`). The blocks are then rebuilt from the symbols; that part differs per format. +//! +//! What is here: +//! * the entropy stage for BC1, BC3, BC4, BC5, BC6H and BC7 ([`lane_widths`]); no lane layout +//! 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. +//! +//! 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. +//! +//! 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. + +pub mod bc1; +mod bc1_fitted; +mod lanes; +mod rans_tables; + +/// Why a stream was not unpacked. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Error { + /// no block rebuild for this mode (or no lane layout, or no tables) + Unsupported, + /// the output is not a whole number of blocks, or too large + OutputSize, + /// the stream ends before the lane has its bytes + Truncated { lane: usize }, + /// a fragment narrows the lane's symbols to nothing + Width { lane: usize }, + /// the state points at the slot no symbol has + Symbol { lane: usize }, + /// the lane's last symbol leaves a state no encoder starts from + EndState { lane: usize }, + /// the lanes wait for each other or for a byte their fragments do not have + Stuck, + /// bytes other than zero padding follow the stream + Trailing { consumed: usize }, + /// BC1 lane 1 is not zero; what it then means is not known + Lane1 { block: usize }, + /// a block refers to an entry of the built-in history that is not known + History { block: usize, slot: usize }, +} + +impl Error { + /// The kind of failure, without its numbers. + pub fn kind(&self) -> &'static str { + match self { + Error::Unsupported => "unsupported", + Error::OutputSize => "output size", + Error::Truncated { .. } => "truncated", + Error::Width { .. } => "width", + Error::Symbol { .. } => "reserved slot", + Error::EndState { .. } => "end state", + Error::Stuck => "stuck", + Error::Trailing { .. } => "trailing data", + Error::Lane1 { .. } => "lane 1", + Error::History { .. } => "unknown history", + } + } +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { + Error::Unsupported => write!(f, "no decoder for this mode"), + Error::OutputSize => write!(f, "the output size is not a whole number of blocks"), + Error::Truncated { lane } => write!(f, "the stream ends while lane {lane} waits for a byte"), + Error::Width { lane } => write!(f, "a fragment of lane {lane} narrows its symbols to nothing"), + Error::Symbol { lane } => write!(f, "lane {lane} reads the reserved slot"), + Error::EndState { lane } => write!(f, "lane {lane} ends in a state no encoder starts from"), + Error::Stuck => write!(f, "the lanes cannot go on"), + Error::Trailing { consumed } => write!(f, "data follows the stream's {consumed} bytes"), + Error::Lane1 { block } => write!(f, "BC1 block {block} has a non-zero lane 1 symbol"), + Error::History { block, slot } => write!(f, "BC1 block {block} refers to the unknown history entry {slot}"), + } + } +} + +/// The symbol width of each lane of a `DSTORAGE_BCPACK_MODE` (1 BC1 … 7 BC7), in stream order. +/// Every lane holds one symbol per 8 bytes of output: one per BC1/BC4 block, two per 16-byte +/// block. +pub fn lane_widths(mode: u8) -> Option<&'static [u8]> { + Some(match mode { + 1 => &[8, 8, 5, 6, 5, 5, 6, 5, 8, 8, 8, 8], + 3 => &[4, 4, 8, 6, 6, 6, 6, 5, 6, 5, 8, 8], + 4 => &[8, 8, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6], + 5 => &[4, 4, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6], + 6 => &[4, 4, 8, 8, 8, 5, 5, 5, 6, 6, 6, 8, 8, 8, 8, 5], + 7 => &[4, 4, 8, 8, 8, 8, 8, 7, 7, 5, 6, 8, 8, 8, 8, 5], + _ => return None, + }) +} + +/// The symbols of a stream that unpacks to `out_len` bytes, unit by unit +/// (`symbols[unit * lanes + lane]`). Zero padding may follow the stream. +pub fn decode_lanes(mode: u8, src: &[u8], out_len: usize) -> Result, Error> { + let widths = lane_widths(mode).ok_or(Error::Unsupported)?; + if out_len % 8 != 0 { + return Err(Error::OutputSize); + } + let (symbols, consumed) = lanes::decode(src, widths, out_len / 8)?; + if src[consumed..].iter().any(|&b| b != 0) { + return Err(Error::Trailing { consumed }); + } + Ok(symbols) +} + +/// The BC1 constants, when XCL has them: the estimates of bcpack-rs, and in the tests the +/// made-up set their fixtures were built with. +fn bc1_tables() -> Option<&'static bc1::Tables> { + #[cfg(test)] + { + Some(tests::tables()) + } + #[cfg(not(test))] + { + Some(&bc1_fitted::TABLES) + } +} + +/// Whether [`decode`] has a block rebuild for `mode`. +pub fn can_decode(mode: u8) -> bool { + 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), + _ => Err(Error::Unsupported), + } +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/crates/xcl/src/hle/bcpack/rans_tables.rs b/crates/xcl/src/hle/bcpack/rans_tables.rs new file mode 100644 index 0000000..7466a9c --- /dev/null +++ b/crates/xcl/src/hle/bcpack/rans_tables.rs @@ -0,0 +1,161 @@ +// Generated by scripts/gen_bcpack_tables.py from Microsoft's silicon-rans sample (mdu_minirans.v, +// https://github.com/microsoft/silicon-rans commit 2f6827d): Copyright (c) Microsoft Corporation, MIT. +// `FREQ[bits - 1][q][segment]`: the frequency of each symbol of a segment, out of 65536. Segment 0 +// is symbol 0, segment k >= 1 is the symbols 2^(k-1) .. 2^k - 1. + +#![allow(clippy::unreadable_literal)] + +pub static FREQ: [[[u16; 9]; 16]; 8] = [ + // 1-bit alphabet + [ + [32768, 32768, 0, 0, 0, 0, 0, 0, 0], + [38761, 26775, 0, 0, 0, 0, 0, 0, 0], + [44484, 21052, 0, 0, 0, 0, 0, 0, 0], + [49818, 15718, 0, 0, 0, 0, 0, 0, 0], + [54623, 10913, 0, 0, 0, 0, 0, 0, 0], + [58721, 6815, 0, 0, 0, 0, 0, 0, 0], + [61911, 3625, 0, 0, 0, 0, 0, 0, 0], + [64036, 1500, 0, 0, 0, 0, 0, 0, 0], + [65121, 415, 0, 0, 0, 0, 0, 0, 0], + [65477, 59, 0, 0, 0, 0, 0, 0, 0], + [65534, 2, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + [65535, 1, 0, 0, 0, 0, 0, 0, 0], + ], + // 2-bit alphabet + [ + [16384, 16384, 16384, 0, 0, 0, 0, 0, 0], + [21168, 17592, 13388, 0, 0, 0, 0, 0, 0], + [26354, 18130, 10526, 0, 0, 0, 0, 0, 0], + [31900, 17918, 7859, 0, 0, 0, 0, 0, 0], + [37750, 16874, 5456, 0, 0, 0, 0, 0, 0], + [43800, 14920, 3408, 0, 0, 0, 0, 0, 0], + [49850, 12062, 1812, 0, 0, 0, 0, 0, 0], + [55537, 8499, 750, 0, 0, 0, 0, 0, 0], + [60308, 4812, 208, 0, 0, 0, 0, 0, 0], + [63575, 1901, 30, 0, 0, 0, 0, 0, 0], + [65132, 402, 1, 0, 0, 0, 0, 0, 0], + [65511, 23, 1, 0, 0, 0, 0, 0, 0], + [65533, 1, 1, 0, 0, 0, 0, 0, 0], + [65533, 1, 1, 0, 0, 0, 0, 0, 0], + [65533, 1, 1, 0, 0, 0, 0, 0, 0], + [65533, 1, 1, 0, 0, 0, 0, 0, 0], + ], + // 3-bit alphabet + [ + [8192, 8192, 8192, 8192, 0, 0, 0, 0, 0], + [11073, 10095, 8796, 6694, 0, 0, 0, 0, 0], + [14406, 11948, 9065, 5263, 0, 0, 0, 0, 0], + [18234, 13666, 8958, 3930, 0, 0, 0, 0, 0], + [22624, 15126, 8437, 2728, 0, 0, 0, 0, 0], + [27657, 16143, 7460, 1704, 0, 0, 0, 0, 0], + [33414, 16436, 6031, 906, 0, 0, 0, 0, 0], + [39920, 15616, 4250, 375, 0, 0, 0, 0, 0], + [47024, 13284, 2406, 104, 0, 0, 0, 0, 0], + [54201, 9375, 950, 15, 0, 0, 0, 0, 0], + [60388, 4744, 200, 1, 0, 0, 0, 0, 0], + [64250, 1262, 10, 1, 0, 0, 0, 0, 0], + [65456, 74, 1, 1, 0, 0, 0, 0, 0], + [65529, 1, 1, 1, 0, 0, 0, 0, 0], + [65529, 1, 1, 1, 0, 0, 0, 0, 0], + [65529, 1, 1, 1, 0, 0, 0, 0, 0], + ], + // 4-bit alphabet + [ + [4096, 4096, 4096, 4096, 4096, 0, 0, 0, 0], + [5665, 5407, 5048, 4398, 3347, 0, 0, 0, 0], + [7539, 6867, 5973, 4532, 2632, 0, 0, 0, 0], + [9773, 8461, 6833, 4479, 1965, 0, 0, 0, 0], + [12447, 10177, 7564, 4218, 1364, 0, 0, 0, 0], + [15679, 11977, 8072, 3730, 852, 0, 0, 0, 0], + [19640, 13774, 8217, 3016, 453, 0, 0, 0, 0], + [24559, 15361, 7808, 2124, 188, 0, 0, 0, 0], + [30704, 16320, 6642, 1203, 52, 0, 0, 0, 0], + [38280, 15920, 4688, 476, 7, 0, 0, 0, 0], + [47169, 13219, 2372, 99, 1, 0, 0, 0, 0], + [56354, 7896, 631, 4, 1, 0, 0, 0, 0], + [63248, 2208, 34, 1, 1, 0, 0, 0, 0], + [65465, 57, 1, 1, 1, 0, 0, 0, 0], + [65521, 1, 1, 1, 1, 0, 0, 0, 0], + [65521, 1, 1, 1, 1, 0, 0, 0, 0], + ], + // 5-bit alphabet + [ + [2048, 2048, 2048, 2048, 2048, 2048, 0, 0, 0], + [2865, 2799, 2704, 2524, 2200, 1673, 0, 0, 0], + [3858, 3682, 3434, 2986, 2266, 1316, 0, 0, 0], + [5063, 4709, 4230, 3418, 2240, 982, 0, 0, 0], + [6536, 5912, 5088, 3782, 2109, 682, 0, 0, 0], + [8366, 7314, 5988, 4036, 1865, 426, 0, 0, 0], + [10688, 8952, 6888, 4108, 1507, 227, 0, 0, 0], + [13713, 10847, 7680, 3904, 1062, 94, 0, 0, 0], + [17758, 12946, 8160, 3320, 602, 26, 0, 0, 0], + [23272, 15008, 7960, 2344, 237, 4, 0, 0, 0], + [30841, 16327, 6610, 1187, 48, 1, 0, 0, 0], + [41006, 15348, 3947, 316, 1, 1, 0, 0, 0], + [53291, 9957, 1104, 14, 1, 1, 0, 0, 0], + [63380, 2084, 22, 1, 1, 1, 0, 0, 0], + [65505, 1, 1, 1, 1, 1, 0, 0, 0], + [65505, 1, 1, 1, 1, 1, 0, 0, 0], + ], + // 6-bit alphabet + [ + [1024, 1024, 1024, 1024, 1024, 1024, 1024, 0, 0], + [1441, 1423, 1400, 1352, 1262, 1099, 837, 0, 0], + [1951, 1907, 1841, 1717, 1493, 1133, 658, 0, 0], + [2577, 2487, 2354, 2115, 1709, 1120, 491, 0, 0], + [3350, 3186, 2956, 2544, 1890, 1055, 341, 0, 0], + [4324, 4042, 3657, 2994, 2019, 932, 213, 0, 0], + [5581, 5107, 4476, 3444, 2055, 754, 113, 0, 0], + [7258, 6454, 5424, 3840, 1952, 531, 47, 0, 0], + [9579, 8179, 6473, 4080, 1660, 301, 13, 0, 0], + [12907, 10365, 7504, 3980, 1171, 119, 2, 0, 0], + [17852, 12988, 8164, 3304, 594, 23, 1, 0, 0], + [25441, 15565, 7673, 1974, 155, 1, 1, 0, 0], + [37208, 16084, 4978, 552, 4, 1, 1, 0, 0], + [53649, 9731, 1042, 4, 1, 1, 1, 0, 0], + [65147, 327, 1, 1, 1, 1, 1, 0, 0], + [65473, 1, 1, 1, 1, 1, 1, 0, 0], + ], + // 7-bit alphabet + [ + [512, 512, 512, 512, 512, 512, 512, 512, 0], + [722, 718, 712, 700, 676, 632, 550, 418, 0], + [981, 971, 952, 920, 858, 748, 566, 329, 0], + [1300, 1276, 1244, 1178, 1058, 854, 559, 246, 0], + [1696, 1654, 1593, 1478, 1272, 946, 526, 171, 0], + [2198, 2126, 2022, 1828, 1498, 1009, 467, 106, 0], + [2852, 2728, 2554, 2238, 1721, 1028, 376, 57, 0], + [3736, 3522, 3227, 2712, 1920, 977, 266, 23, 0], + [4979, 4601, 4090, 3236, 2040, 831, 151, 6, 0], + [6807, 6101, 5182, 3752, 1991, 586, 59, 1, 0], + [9634, 8218, 6494, 4082, 1652, 296, 11, 1, 0], + [14275, 11165, 7784, 3836, 988, 74, 1, 1, 0], + [22449, 14759, 8042, 2489, 272, 1, 1, 1, 0], + [37625, 16023, 4866, 509, 1, 1, 1, 1, 0], + [60485, 4663, 132, 1, 1, 1, 1, 1, 0], + [65409, 1, 1, 1, 1, 1, 1, 1, 0], + ], + // 8-bit alphabet + [ + [256, 256, 256, 256, 256, 256, 256, 256, 256], + [362, 360, 359, 356, 350, 338, 316, 275, 209], + [492, 488, 486, 476, 460, 429, 374, 284, 164], + [653, 647, 638, 622, 589, 529, 426, 280, 123], + [853, 843, 828, 796, 739, 636, 473, 264, 85], + [1108, 1090, 1063, 1011, 914, 748, 504, 234, 53], + [1442, 1410, 1364, 1277, 1120, 860, 514, 189, 28], + [1895, 1841, 1760, 1614, 1356, 961, 488, 132, 12], + [2538, 2442, 2300, 2045, 1618, 1021, 414, 76, 3], + [3497, 3311, 3050, 2591, 1875, 996, 292, 29, 1], + [5008, 4626, 4109, 3247, 2041, 826, 149, 4, 1], + [7575, 6701, 5582, 3892, 1918, 494, 34, 1, 1], + [12397, 10051, 7380, 4020, 1245, 129, 1, 1, 1], + [22767, 14857, 8012, 2432, 240, 1, 1, 1, 1], + [47343, 13141, 2332, 35, 1, 1, 1, 1, 1], + [65281, 1, 1, 1, 1, 1, 1, 1, 1], + ], +]; diff --git a/crates/xcl/src/hle/bcpack/tests.rs b/crates/xcl/src/hle/bcpack/tests.rs new file mode 100644 index 0000000..a5ab53a --- /dev/null +++ b/crates/xcl/src/hle/bcpack/tests.rs @@ -0,0 +1,373 @@ +//! Tests of the BCPack decoder on synthetic streams: the fixtures of `tests/data/bcpack` +//! (built by its `generate.py`, an encoder written from the format notes and not from this +//! decoder) and streams of the encoder below. None of them shows what a console would write. + +use super::lanes::{self, L}; +use super::rans_tables::FREQ; +use super::{bc1, 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. +pub(crate) fn tables() -> &'static bc1::Tables { + static T: std::sync::OnceLock = std::sync::OnceLock::new(); + T.get_or_init(|| { + let range = [32usize, 64, 32, 32, 64, 32]; + bc1::Tables { + history: std::array::from_fn(|slot| Some(std::array::from_fn(|k| ((7 * slot + 13 * k) % range[k]) as u8))), + quadrants: std::array::from_fn(|s| s as u8), + } + }) +} + +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() +} + +/// `bc--` → (mode, units) +fn fixture(stem: &str) -> (u8, usize) { + let mut p = stem.strip_prefix("bc").unwrap().split('-'); + (p.next().unwrap().parse().unwrap(), p.next().unwrap().parse().unwrap()) +} + +/// A `.lanes` file (all of lane 0, then lane 1 …) in the decoder's order. +fn by_unit(lane_major: &[u8], lanes: usize) -> Vec { + let units = lane_major.len() / lanes; + (0..units * lanes).map(|i| lane_major[(i % lanes) * units + i / lanes]).collect() +} + +const FIXTURES: [&str; 14] = [ + "bc1-1-8", "bc1-2-0", "bc1-16-1", "bc1-16-9", "bc1-700-2", "bc1-8192-3", "bc3-16-1", "bc4-16-1", "bc5-16-1", "bc6-16-1", "bc7-2-0", "bc7-16-1", + "bc7-700-2", "bc7-8192-3", +]; + +/// The symbols of the two 64 KiB fixtures, which ship without a `.lanes` file (`generate.py`). +pub(crate) fn large_fixture_symbols(mode: u8) -> Vec { + let n = lane_widths(mode).unwrap().len(); + let mut s = vec![0u8; 8192 * n]; + if mode == 1 { + for i in (0..8192).step_by(511) { + s[i * n + 2] = 30; + s[i * n + 8] = 5; + } + for i in (31..8192).step_by(31) { + s[i * n] = 2; + } + } + s +} + +#[test] +fn fixtures_decode_to_their_lanes() { + for stem in FIXTURES { + let (mode, units) = fixture(stem); + let n = lane_widths(mode).unwrap().len(); + let bin = data(&format!("{stem}.bin")).unwrap(); + let want = match data(&format!("{stem}.lanes")) { + Some(l) => by_unit(&l, n), + None => large_fixture_symbols(mode), + }; + assert_eq!(want.len(), units * n, "{stem}"); + // bc1-1-8 has states cut to fewer bytes than an encoder that starts at `L` can drop, + // which the hardware's decoder does not take either + if stem == "bc1-1-8" { + assert!(decode_lanes(mode, &bin, units * 8).is_err(), "{stem}"); + continue; + } + assert_eq!(decode_lanes(mode, &bin, units * 8).as_deref(), Ok(&want[..]), "{stem}"); + // zero padding after the stream is not part of it; anything else is + let mut padded = bin.clone(); + padded.extend([0; 37]); + assert_eq!(decode_lanes(mode, &padded, units * 8).as_deref(), Ok(&want[..]), "{stem} padded"); + padded.push(1); + assert_eq!(decode_lanes(mode, &padded, units * 8), Err(Error::Trailing { consumed: bin.len() }), "{stem}"); + } +} + +#[test] +fn bc1_fixtures_decode_to_their_blocks() { + for stem in FIXTURES.iter().filter(|s| s.starts_with("bc1-") && **s != "bc1-1-8") { + let (_, units) = fixture(stem); + let bin = data(&format!("{stem}.bin")).unwrap(); + let blocks = bc1::decode(&bin, units * 8, tables()).unwrap(); + match data(&format!("{stem}.bc1")) { + Some(want) => assert_eq!(blocks, want, "{stem}"), + None => assert_eq!(blocks, bc1::assemble(&large_fixture_symbols(1), tables()).unwrap(), "{stem}"), + } + 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] { + assert!(!super::can_decode(mode)); + assert_eq!(super::decode(mode, &[], 16), Err(Error::Unsupported)); + } +} + +/// One BC1 block by hand: every field of the rebuild, without the entropy stage. +#[test] +fn bc1_block_rebuild() { + let t = tables(); + // block 0: no reference; R0 +3, G0 -1, B0 0, R1 -2, G1 +5, B1 +1; the four quadrants + let b0 = [0u8, 0, 6, 1, 0, 3, 10, 2, 0b11_10_01_00, 0b00_00_00_01, 0b10_10_10_10, 0b11_00_11_00]; + // block 1: one block back; R0 -4 (wraps to 31), the rest unchanged + let b1 = [2u8, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + // block 2: 255 back, which is before the stream: history entry 256 + 2 - 255 = 3 + let b2 = [1u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let out = bc1::assemble(&[b0, b1, b2].concat(), t).unwrap(); + let c = |r: u16, g: u16, b: u16| (r << 11 | g << 5 | b).to_le_bytes(); + assert_eq!(out[0..2], c(3, 63, 0)); + assert_eq!(out[2..4], c(30, 5, 1)); + // rows: left quadrant's two texels in the low nibble, right quadrant's in the high one + assert_eq!(out[4..8], [0b00_01_01_00, 0b00_00_11_10, 0b11_00_10_10, 0b11_00_10_10]); + assert_eq!(out[8..10], c(31, 63, 0)); + assert_eq!(out[10..12], c(30, 5, 1)); + assert_eq!(out[12..16], [0; 4]); + let h = t.history[3].unwrap().map(|v| v as u16); + assert_eq!(out[16..20], [c(h[0], h[1], h[2]), c(h[3], h[4], h[5])].concat()[..]); + + // lane 1 is not understood beyond "0" + let mut odd = b0; + odd[1] = 1; + assert_eq!(bc1::assemble(&odd, t), Err(Error::Lane1 { block: 0 })); + // an unknown history entry stops the stream instead of guessing + let mut holes = bc1::Tables { history: t.history, quadrants: t.quadrants }; + holes.history[3] = None; + assert_eq!(bc1::assemble(&[b0, b1, b2].concat(), &holes), Err(Error::History { block: 2, slot: 3 })); +} + +/// The 8-bit model 11 as US 11,234,023 prints it (its `base_table[8][12]`, counted from 1). +#[test] +fn model_matches_the_patent_excerpt() { + let base = [0u32, 7575, 14276, 25440, 41008, 56352, 64256, 65344, 65408]; + let freq = [7575u16, 6701, 5582, 3892, 1918, 494, 34, 1, 1]; + assert_eq!(FREQ[7][11], freq); + let mut at = 0; + for k in 0..9 { + assert_eq!(at, base[k]); + at += freq[k] as u32 * if k < 2 { 1 } else { 1 << (k - 1) }; + } + assert_eq!(at, 65536); + for (bits, per_q) in FREQ.iter().enumerate() { + for f in per_q { + let total: u32 = (0..9).map(|k| f[k] as u32 * if k < 2 { 1 } else { 1 << (k - 1) }).sum(); + assert_eq!(total, 65536); + assert!(f[..bits + 2].iter().all(|&v| v >= 1) && f[bits + 2..].iter().all(|&v| v == 0)); + } + } +} + +// --------------------------------------------------------------------------------------- +// a test encoder: any model, any fragment sizes +// --------------------------------------------------------------------------------------- + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u32 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 33) as u32 + } + fn below(&mut self, n: u32) -> u32 { + self.next() % n + } +} + +/// (frequency, first slot) of `sym` in model (`bits`, `q`). +fn slot(bits: usize, q: usize, sym: u32) -> (u32, u32) { + let seg = (32 - sym.leading_zeros()) as usize; + let base: u32 = (0..seg).map(|k| FREQ[bits - 1][q][k] as u32 * if k < 2 { 1 } else { 1 << (k - 1) }).sum(); + let f = FREQ[bits - 1][q][seg] as u32; + let cf = base + f * (sym - ((1u32 << seg) >> 1)); + if cf == 0 { + (f - 1, 1) + } else { + (f, cf) + } +} + +/// One flushed fragment: header, state, payload. `trim`: drop the zero bytes an encoder +/// that starts at `L` may drop (those its first symbol pushed out). +fn fragment(symbols: &[u8], lane_bits: usize, z: usize, q: usize, trim: bool) -> Vec { + let mut x = L; + let mut emitted = Vec::new(); + let mut droppable = 0; + for (k, &s) in symbols.iter().rev().enumerate() { + let (f, cf) = slot(lane_bits - z, q, s as u32); + while x >= f << 16 { + emitted.push(x as u8); + x >>= 8; + } + if k == 0 { + droppable = emitted.len(); + } + x = (x / f) << 16 | (x % f + cf); + } + let mut body = x.to_be_bytes().to_vec(); + body.extend(emitted.iter().rev()); + if trim { + body.truncate(body.len() - droppable); + } + let mode = (z << 6 | 0x10 | q) as u8; + let mut out = if body.len() <= 256 { + vec![mode, (body.len() - 1) as u8] + } else { + let n = body.len() - 257; + vec![mode | 0x20, n as u8, (n >> 8) as u8] + }; + out.extend(body); + out +} + +/// A stream of random symbols and fragments, with its symbols (the decoder's order). The +/// lanes' bytes are put in the order the decoder asks for them, so this checks the decoder +/// against the encoder's arithmetic and itself, not the byte order against anything. +fn random_stream(widths: &[u8], units: usize, rng: &mut Rng) -> (Vec, Vec) { + let n = widths.len(); + let mut symbols = vec![0u8; units * n]; + let mut queues: Vec> = Vec::new(); + for (l, &w) in widths.iter().enumerate() { + let mut bytes = Vec::new(); + let mut at = 0; + while at < units { + let longest = if rng.below(4) == 0 { 700 } else { 40 }; + let len = (1 + rng.below(longest) as usize).min(units - at); + let z = rng.below(4).min(w as u32 - 1) as usize; + let q = rng.below(16) as usize; + let bits = w as usize - z; + // the steeper models leave one slot to most symbols: keep those symbols rare + let frag: Vec = (0..len) + .map(|_| { + let top = if q >= 8 && rng.below(8) != 0 { 1u32 << bits.min(2) } else { 1 << bits }; + rng.below(top) as u8 + }) + .collect(); + for (k, &s) in frag.iter().enumerate() { + symbols[(at + k) * n + l] = s; + } + bytes.extend(fragment(&frag, w as usize, z, q, rng.below(2) == 0)); + at += len; + } + queues.push(bytes.into()); + } + let mut stream = Vec::new(); + let got = lanes::run(widths, units, |lane| { + let b = queues[lane].pop_front(); + stream.extend(b); + b + }) + .expect("the encoder's own fragments decode"); + assert_eq!(got, symbols); + assert!(queues.iter().all(|q| q.is_empty()), "every fragment was read to its end"); + (stream, symbols) +} + +#[test] +fn random_streams_round_trip_in_every_model() { + let mut rng = Rng(0x5EED); + let dump = std::env::var_os("XCL_BCPACK_DUMP").map(std::path::PathBuf::from); + for round in 0..60 { + for mode in [1u8, 3, 4, 5, 6, 7] { + let widths = lane_widths(mode).unwrap(); + let units = [1, 2, 7, 64, 300, 2048][round % 6] * if mode == 1 || mode == 4 { 1 } else { 2 }; + let (stream, symbols) = random_stream(widths, units, &mut rng); + assert_eq!(decode_lanes(mode, &stream, units * 8).as_deref(), Ok(&symbols[..]), "mode {mode} round {round}"); + // every byte of the stream is needed + assert!(decode_lanes(mode, &stream[..stream.len() - 1], units * 8).is_err()); + if let Some(dir) = &dump { + // for a comparison with other decoders: the stream and its lanes, lane by lane + let stem = dir.join(format!("r{round}-bc{mode}-{units}")); + let n = widths.len(); + let lane_major: Vec = (0..units * n).map(|i| symbols[(i % units) * n + i / units]).collect(); + std::fs::write(stem.with_extension("bin"), &stream).unwrap(); + std::fs::write(stem.with_extension("lanes"), lane_major).unwrap(); + } + } + } +} + +/// Damaged input ends in an answer, never a panic or a hang. (The answer can be other +/// symbols: a stream has no checksum, and under a uniform model any bytes are symbols.) +#[test] +fn damaged_streams_end_cleanly() { + let mut rng = Rng(7); + for stem in ["bc1-2-0", "bc1-16-1", "bc1-16-9", "bc7-16-1", "bc1-700-2", "bc7-700-2"] { + let (mode, units) = fixture(stem); + let bin = data(&format!("{stem}.bin")).unwrap(); + let check = |bytes: &[u8], units: usize| { + let lanes = decode_lanes(mode, bytes, units * 8); + if mode == 1 { + assert_eq!(super::decode(1, bytes, units * 8).is_ok(), lanes.is_ok()); + } + lanes + }; + // every byte of a stream is some lane's: a shorter one is never whole + for cut in (0..bin.len()).step_by((bin.len() / 300).max(1)) { + assert!(check(&bin[..cut], units).is_err(), "{stem} cut at {cut}"); + } + for _ in 0..400 { + let mut b = bin.clone(); + let at = rng.below(b.len() as u32) as usize; + match rng.below(3) { + 0 => b[at] ^= 1 << rng.below(8), + 1 => b[at] = rng.next() as u8, + _ => { + b.remove(at); + } + } + let _ = check(&b, units); + } + // the wrong number of blocks, and a size that is no number of blocks + assert!(check(&bin, units + 1).is_err()); + assert!(check(&bin, units - 1).is_err()); + assert_eq!(decode_lanes(mode, &bin, units * 8 + 4), Err(Error::OutputSize)); + } + // noise, and headers that claim more than there is + for len in [0usize, 1, 2, 3, 47, 48, 64, 500, 5000] { + for _ in 0..40 { + let noise: Vec = (0..len).map(|_| rng.next() as u8).collect(); + for mode in [1u8, 7] { + let _ = decode_lanes(mode, &noise, 64 * 8); + let _ = super::decode(mode, &noise, 64 * 8); + } + } + } + assert!(decode_lanes(1, &[0xFF; 4096], 1 << 20).is_err()); + assert!(decode_lanes(7, &[0x00; 4096], 1 << 20).is_err()); + assert_eq!(decode_lanes(2, &[], 16), Err(Error::Unsupported)); + assert_eq!(decode_lanes(1, &[], 0), Ok(Vec::new())); +} + +/// The tables XCL ships (`bc1_fitted.rs`) are whole and in the layout [`bc1::assemble`] reads. +#[test] +fn fitted_bc1_tables_are_well_formed() { + let t = &super::bc1_fitted::TABLES; + // every quadrant once, the four uniform ones first + let mut seen = [false; 256]; + for &q in &t.quadrants { + assert!(!std::mem::replace(&mut seen[q as usize], true), "quadrant {q:#04x} twice"); + } + let uniform = |s: usize| t.quadrants[s] & 3; + for s in 0..4 { + assert_eq!(t.quadrants[s], uniform(s) * 0x55); + } + for h in t.history.iter().flatten() { + assert!(h.iter().zip([32, 64, 32, 32, 64, 32]).all(|(&c, range)| c < range)); + } + + // a first block that takes the endpoints of the block before the stream as they are + let mut s = [0u8; 12]; + s[0] = 2; + s[8..].copy_from_slice(&[0, 1, 2, 3]); + let b = bc1::assemble(&s, t).unwrap(); + let e = t.history[255].unwrap().map(u16::from); + assert_eq!(b[..2], (e[0] << 11 | e[1] << 5 | e[2]).to_le_bytes()); + assert_eq!(b[2..4], (e[3] << 11 | e[4] << 5 | e[5]).to_le_bytes()); + let row = |left: usize, right: usize| uniform(left) * 5 | uniform(right) * 5 << 4; + assert_eq!(b[4..], [row(0, 1), row(0, 1), row(2, 3), row(2, 3)]); + + // an entry the estimate does not have ends the rebuild + if let Some(slot) = (1..256).find(|&k| t.history[k].is_none()) { + let d = 256 - slot; + s[0] = if d < 128 { 2 * d } else { 2 * (255 - d) + 1 } as u8; + assert_eq!(bc1::assemble(&s, t), Err(Error::History { block: 0, slot })); + } +} diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index e793810..aee3d02 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -674,6 +674,12 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { if matches!(format, 86 | 115) && flags & 5 != 0 { d[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); } + // R9G9B9E5_SHAREDEXP targets: the PC renders into the format neither as a target nor through + // unordered access (a retail game's 1920x1080 one on the Series S profile, flags 0x300005: + // E_INVALIDARG, then its assertion) – half floats hold every shared-exponent value exactly + if format == 67 && flags & 5 != 0 { + d[0x20..0x24].copy_from_slice(&10u32.to_le_bytes()); + } // a depth buffer the console also lets shaders write (a retail game's: ALLOW_DEPTH_STENCIL | // ALLOW_UNORDERED_ACCESS): the PC refuses the pair – the depth buffer stays if flags & 2 != 0 { @@ -715,6 +721,7 @@ fn depth_typeless(f: u32) -> Option { pub fn pc_target_format(f: u32) -> u32 { match f { 86 | 115 => 28, + 67 => 10, f => pc_view_format(f), } } @@ -737,6 +744,8 @@ pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { (53 | 55, 0 | 53 | 55) => 56, // a target made R8G8B8A8 (`pc_resource_desc`) (28, 86 | 115) => 28, + // an R9G9B9E5 target made half floats + (10, 67) => 10, (_, v) => v, } } @@ -1049,6 +1058,12 @@ mod tests { x[0x20] = 86; // B5G5R5A1 target that is also a UAV x[0x30..0x34].copy_from_slice(&0x5u32.to_le_bytes()); assert_eq!(desc(&x), (28, 0x5)); + x[0x20] = 67; // R9G9B9E5 target that is also a UAV (and console bits): half floats + x[0x30..0x34].copy_from_slice(&0x30_0005u32.to_le_bytes()); + assert_eq!(desc(&x), (10, 0x5)); + x[0x30..0x34].copy_from_slice(&0x0u32.to_le_bytes()); // a sampled one stays R9G9B9E5 + assert_eq!(desc(&x), (67, 0)); + assert_eq!((pc_shader_view_format(10, 67), pc_shader_view_format(67, 67), pc_target_format(67)), (10, 67, 10)); // views: a D24S8 format or R16_UNORM of the D16S8 buffer read depth; stencil formats plane 1 assert_eq!(pc_shader_view_format(44, 45), 46); assert_eq!(pc_shader_view_format(44, 56), 46); diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 78c8359..3f5c77f 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -226,6 +226,31 @@ pub fn swap_format(f: DXGI_FORMAT) -> Option { }) } +/// HDR color space for a swap chain format (None = SDR or default color space). +pub fn hdr_color_space(fmt: DXGI_FORMAT) -> Option { + match fmt { + DXGI_FORMAT_R10G10B10A2_UNORM => Some(DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020), + DXGI_FORMAT_R16G16B16A16_FLOAT => Some(DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709), + _ => None, + } +} + +/// Configures HDR color space on the swap chain for HDR formats (Issue #103 Item 3). +/// Logs a warning if unsupported on the display instead of failing presentation. +pub unsafe fn configure_color_space(sc: &IDXGISwapChain3, fmt: DXGI_FORMAT) -> Result<(), windows::core::Error> { + if let Some(cs) = hdr_color_space(fmt) { + let res = sc.SetColorSpace1(cs); + if let Err(ref e) = res { + crate::xlog_warn!("present: HDR color space {cs:?} unsupported on display: {e}"); + } else { + crate::xlog_info!("present: HDR color space {cs:?} configured for {fmt:?}"); + } + res + } else { + Ok(()) + } +} + unsafe fn backbuffer_like(res: usize) -> Option { let raw = res as *mut c_void; let r = ID3D12Resource::from_raw_borrowed(&raw)?; @@ -554,6 +579,7 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D p.h = h; p.fmt = fmt; crate::xlog_info!("present: swap chain {w}x{h} {:?}", fmt); + let _ = configure_color_space(sc, fmt); return true; } return false; @@ -576,7 +602,11 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D match factory.CreateSwapChainForHwnd(queue, hwnd, &desc, None, None) { Ok(sc1) => { let _ = factory.MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER); - p.sc = sc1.cast::().ok(); + let sc3 = sc1.cast::().ok(); + if let Some(sc) = &sc3 { + let _ = configure_color_space(sc, fmt); + } + p.sc = sc3; p.w = w; p.h = h; p.fmt = fmt; @@ -967,6 +997,7 @@ impl Drop for Presenter { #[cfg(test)] mod tests { use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; // XCL_WINDOW_POS is process-global; one test covers all modes in sequence. #[test] @@ -1002,6 +1033,53 @@ mod tests { std::env::remove_var("XCL_WINDOW_POS"); } } + + #[test] + fn hdr_color_space_format_matching() { + assert_eq!(hdr_color_space(DXGI_FORMAT_R10G10B10A2_UNORM), Some(DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020)); + assert_eq!(hdr_color_space(DXGI_FORMAT_R16G16B16A16_FLOAT), Some(DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709)); + assert_eq!(hdr_color_space(DXGI_FORMAT_R8G8B8A8_UNORM), None); + assert_eq!(hdr_color_space(DXGI_FORMAT_B8G8R8A8_UNORM), None); + assert_eq!(hdr_color_space(DXGI_FORMAT_UNKNOWN), None); + } + + #[test] + fn hdr_color_space_configuration() { + unsafe { + let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) else { return }; + let Ok(adapter) = factory.EnumWarpAdapter::() else { return }; + let mut dev: Option = None; + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let Ok(queue) = dev.CreateCommandQueue::(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) else { return }; + let desc = DXGI_SWAP_CHAIN_DESC1 { + Width: 64, + Height: 64, + Format: DXGI_FORMAT_R10G10B10A2_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount: 2, + Scaling: DXGI_SCALING_STRETCH, + SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, + AlphaMode: DXGI_ALPHA_MODE_IGNORE, + ..Default::default() + }; + if let Ok(sc1) = factory.CreateSwapChainForComposition(&queue, &desc, None) { + if let Ok(sc3) = sc1.cast::() { + // SDR format does nothing and returns Ok + assert!(configure_color_space(&sc3, DXGI_FORMAT_R8G8B8A8_UNORM).is_ok()); + // HDR formats invoke SetColorSpace1 without panic (returns Ok or display unsupported error) + let _ = configure_color_space(&sc3, DXGI_FORMAT_R10G10B10A2_UNORM); + let _ = configure_color_space(&sc3, DXGI_FORMAT_R16G16B16A16_FLOAT); + } + } + } + } } #[cfg(test)] diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 22c5a22..22683de 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -182,12 +182,17 @@ fn decommit_tiles( } } } - if !unmapped.is_empty() { - to_zero.retain(|&(za, _)| mapped.contains_key(&(za & !(TILE - 1)))); - } unmapped } +/// Drop the runs of `to_zero` whose tile is no longer mapped – once, where the runs are taken. +/// (Pruning at every decommit that unmapped a tile walked the whole list each time: it grows +/// until the next ExecuteCommandLists, and a title mapping gigabytes of physical pages while it +/// loads – a newer retail title – spent seconds there, its watchdog ended the game.) +fn prune_zero_runs(mapped: &FxHashMap, runs: &mut Vec<(usize, usize)>) { + runs.retain(|&(za, _)| mapped.contains_key(&(za & !(TILE - 1)))); +} + struct UploadSlot { alloc: ID3D12CommandAllocator, list: ID3D12GraphicsCommandList, @@ -1204,7 +1209,8 @@ pub unsafe fn readback_now(va: usize, len: usize) { if s.window_index(va).is_none() { return; } - let zeroed = std::mem::take(&mut s.to_zero); + let mut zeroed = std::mem::take(&mut s.to_zero); + prune_zero_runs(&s.mapped, &mut zeroed); if !zeroed.is_empty() { for &(a, n) in &zeroed { s.clear_sent_range(a, n); @@ -1350,7 +1356,8 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: let Some(s) = g.as_mut() else { return }; let t_locked = std::time::Instant::now(); PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Ordering::Relaxed); - let zero_runs = std::mem::take(&mut s.to_zero); + let mut zero_runs = std::mem::take(&mut s.to_zero); + prune_zero_runs(&s.mapped, &mut zero_runs); for &(a, n) in &zero_runs { s.clear_sent_range(a, n); } @@ -1728,6 +1735,7 @@ mod tests { assert_eq!(unmapped, vec![t0]); assert!(!mapped.contains_key(&t0)); assert_eq!(free, vec![(0, 10)]); + prune_zero_runs(&mapped, &mut to_zero); assert!(to_zero.is_empty(), "stale to_zero entries for the unmapped tile must be pruned"); // 2. Sixteen individual 4 KiB decommits in reverse order. @@ -1743,6 +1751,7 @@ mod tests { assert_eq!(u, vec![t1]); assert!(!mapped.contains_key(&t1)); assert_eq!(free, vec![(0, 11)]); + prune_zero_runs(&mapped, &mut to_zero); assert!(to_zero.is_empty()); // 3. Pinned tile decommitted in two halves: unmapped from `mapped`, NOT returned to `free`. @@ -1755,6 +1764,7 @@ mod tests { assert_eq!(u, vec![t2]); assert!(!mapped.contains_key(&t2)); assert!(free.is_empty(), "pinned pool tile must not return to free list"); + prune_zero_runs(&mapped, &mut to_zero); assert!(to_zero.is_empty()); // 4. Single-committed-page tile decommit reclaims tile without dropping another tile's to_zero. diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 557266e..32b215b 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -24,9 +24,10 @@ //! then 5 more. //! //! Each queue has a worker thread: submitted requests run in order (file reads through the -//! VFS like the title's own, memory copies, zlib), a status entry gets the first failure of -//! the requests since the previous one, a signal sets the fence from the CPU. Methods not -//! listed are logged and answer E_NOTIMPL; BCPack and other console formats are refused. +//! VFS like the title's own, memory copies, zlib, BCPack where `hle::bcpack` rebuilds the +//! blocks of the mode), a status entry gets the first failure of the requests since the +//! previous one, a signal sets the fence from the CPU. Methods not listed are logged and +//! answer E_NOTIMPL; the other BCPack modes and the hardware swizzle are refused. #![allow(non_snake_case)] @@ -131,7 +132,7 @@ fn bcpack_name(mode: u8) -> String { BCPACK_NAMES.get(mode as usize).map_or_else(|| format!("mode {mode}"), |n| n.to_string()) } -/// BCPack requests refused at enqueue (XCL has no BCPack decoder), by mode. +/// BCPack requests refused at enqueue (XCL has no decoder for their mode), by mode. struct BcpackRefusals { requests: [AtomicU64; 16], with_zlib: [AtomicU64; 16], @@ -197,10 +198,81 @@ pub struct BcpackStats { pub struct DStorageStats { /// BCPack requests refused (no decoder), by `DSTORAGE_BCPACK_MODE` pub bcpack_refused: BTreeMap, + /// BCPack requests the decoder ran on, by `DSTORAGE_BCPACK_MODE` + #[serde(default)] + pub bcpack_unpacked: BTreeMap, } pub fn stats() -> DStorageStats { - DStorageStats { bcpack_refused: BCPACK.stats() } + DStorageStats { bcpack_refused: BCPACK.stats(), bcpack_unpacked: UNPACKED.stats() } +} + +/// BCPack requests that reached the decoder, by mode. +struct BcpackUnpacked { + requests: [AtomicU64; 16], + bytes: [AtomicU64; 16], + failed: [AtomicU64; 16], +} + +impl BcpackUnpacked { + const fn new() -> Self { + const Z: AtomicU64 = AtomicU64::new(0); + Self { requests: [Z; 16], bytes: [Z; 16], failed: [Z; 16] } + } + + fn stats(&self) -> BTreeMap { + (1..16u8) + .filter(|&m| self.requests[m as usize].load(Ordering::Relaxed) + self.failed[m as usize].load(Ordering::Relaxed) > 0) + .map(|m| { + let i = m as usize; + let s = BcpackUnpackStats { + requests: self.requests[i].load(Ordering::Relaxed), + destination_bytes: self.bytes[i].load(Ordering::Relaxed), + failed: self.failed[i].load(Ordering::Relaxed), + }; + (bcpack_name(m), s) + }) + .collect() + } +} + +static UNPACKED: BcpackUnpacked = BcpackUnpacked::new(); + +#[derive(Debug, Default, Clone, Serialize, Deserialize)] +pub struct BcpackUnpackStats { + /// requests whose blocks were rebuilt + pub requests: u64, + /// bytes of blocks rebuilt for them (counted before the write to the destination) + pub destination_bytes: u64, + /// requests whose stream the decoder did not take (they fail with E_DECOMPRESSION) + pub failed: u64, +} + +/// The BCPack stage of a request: `packed` to the `n` bytes of blocks of its mode. +fn bcpack_unpack(r: &Request, packed: &[u8], n: usize) -> Result, HRESULT> { + let bc = r.bcpack(); + let i = bc as usize & 0xF; + match super::bcpack::decode(bc, packed, n) { + Ok(blocks) => { + if UNPACKED.requests[i].fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_info!("DirectStorage: BCPack {}: first request unpacked ({} to {n} bytes)", bcpack_name(bc), packed.len()); + } + UNPACKED.bytes[i].fetch_add(n as u64, Ordering::Relaxed); + Ok(blocks) + } + Err(e) => { + let k = UNPACKED.failed[i].fetch_add(1, Ordering::Relaxed) + 1; + // one warning per mode and kind of failure, then a running count + warn_once( + &format!("BCPack {} stream ({})", bcpack_name(bc), e.kind()), + format_args!("{e} (packed={}, dst={n}); the request fails with E_DECOMPRESSION", packed.len()), + ); + if k <= 16 || k.is_power_of_two() { + crate::xlog_info!("DirectStorage: BCPack {} streams not unpacked so far: {k}", bcpack_name(bc)); + } + Err(E_DECOMPRESSION) + } + } } /// Log a refused BCPack request: one warning per mode and zlib stage, then a running count on @@ -674,20 +746,24 @@ impl Request { return Err(E_DESTINATION_SIZE); } } - // Two-stage zlib -> BCPack: validate intermediate bounds when supplied, then refuse BCPack - // (counted and logged at enqueue, `BcpackRefusals`). - (true, _) => { + // Two-stage zlib -> BCPack: validate intermediate bounds when supplied, then refuse the + // BCPack modes without a decoder (counted and logged at enqueue, `BcpackRefusals`). + (true, bc) => { if self.intermediate_size != 0 && (self.intermediate_size <= self.source_size || self.destination_size <= self.intermediate_size) { return Err(E_DESTINATION_SIZE); } - return Err(E_DECOMPRESSION); + if !super::bcpack::can_decode(bc) { + return Err(E_DECOMPRESSION); + } } - // Single-stage BCPack: `intermediate_size` must be 0, then refuse BCPack. - (false, _) => { + // Single-stage BCPack: `intermediate_size` must be 0, then refuse the modes without a decoder. + (false, bc) => { if self.intermediate_size != 0 { return Err(E_DESTINATION_SIZE); } - return Err(E_DECOMPRESSION); + if !super::bcpack::can_decode(bc) { + return Err(E_DECOMPRESSION); + } } } Ok(()) @@ -805,23 +881,31 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us b }; - if r.swizzle() != 0 || r.bcpack() != 0 { + let bc = r.bcpack(); + if r.swizzle() != 0 || (bc != 0 && !super::bcpack::can_decode(bc)) { return Err(E_DECOMPRESSION); } - let payload: Vec = if r.zlib() { + // the stages in the console's order: zlib, then BCPack + let stage1: Vec = if r.zlib() { let stage1_len = if r.intermediate_size != 0 { r.intermediate_size as usize } else { n }; let mut d = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&src, stage1_len).map_err(|_| E_ZLIB_DATA)?; - if d.len() != stage1_len { + // zlib yields `intermediate_size` bytes; when the title names none, the destination's + // size, or before BCPack a stream of any size up to it. That last case is XCL's + // leniency, as is a BCPack stream no smaller than its blocks: the GDK documents + // `IntermediateSize` as the size of the stream BCPack reads, and what the console does + // with a request that leaves it 0 was not tested. + if d.len() != stage1_len && (bc == 0 || r.intermediate_size != 0) { return Err(E_ZLIB_DATA); } - if d.len() < n { + if bc == 0 && d.len() < n { d.resize(n, 0); } d } else { src }; + 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)?; @@ -1411,7 +1495,7 @@ mod tests { let mem = Request::parse(&request(SOURCE_MEMORY_BIT | 1, 0x1000, 64, 0x2000, 0x99, 20)); assert_eq!((mem.offset, mem.check(true)), (0, Ok(())), "a memory source has no offset"); assert_eq!(Request::parse(&request(1, 0x1000, 20, 0x2000, 0, 20)).check(false), Err(E_DESTINATION_SIZE)); - assert_eq!(Request::parse(&request(3, 0x1000, 64, 0x2000, 0, 20)).check(false), Err(E_DECOMPRESSION), "BCPack"); + assert_eq!(Request::parse(&request(15, 0x1000, 64, 0x2000, 0, 20)).check(false), Err(E_DECOMPRESSION), "BCPack BC7"); assert_eq!(Request::parse(&request(0, 0, 64, 0x2000, 0, 64)).check(false), Err(E_ACCESS_VIOLATION)); } @@ -1636,12 +1720,15 @@ mod tests { // Zlib only with invalid intermediate_size (<= src or > dst) assert_eq!(Request::parse(&request_ex(ZLIB_BIT, 0x1000, 0, 128, 0x2000, 0, 20, 20, 0)).check(false), Err(E_DESTINATION_SIZE)); assert_eq!(Request::parse(&request_ex(ZLIB_BIT, 0x1000, 0, 64, 0x2000, 0, 20, 96, 0)).check(false), Err(E_DESTINATION_SIZE)); - // Two-stage zlib + BCPack: valid sizes -> E_DECOMPRESSION, invalid intermediate -> E_DESTINATION_SIZE - assert_eq!(Request::parse(&request_ex(ZLIB_BIT | bc1, 0x1000, 0, 256, 0x2000, 0, 20, 64, 0)).check(false), Err(E_DECOMPRESSION)); + // Two-stage zlib + BCPack: valid sizes -> E_DECOMPRESSION without a decoder for the mode, invalid intermediate -> E_DESTINATION_SIZE + assert_eq!(Request::parse(&request_ex(ZLIB_BIT | bc7, 0x1000, 0, 256, 0x2000, 0, 20, 64, 0)).check(false), Err(E_DECOMPRESSION)); + assert_eq!(Request::parse(&request_ex(ZLIB_BIT | bc1, 0x1000, 0, 256, 0x2000, 0, 20, 64, 0)).check(false), Ok(())); + assert_eq!(Request::parse(&request_ex(ZLIB_BIT | bc1, 0x1000, 0, 256, 0x2000, 0, 20, 20, 0)).check(false), Err(E_DESTINATION_SIZE)); assert_eq!(Request::parse(&request_ex(ZLIB_BIT | bc7, 0x1000, 0, 256, 0x2000, 0, 20, 20, 0)).check(false), Err(E_DESTINATION_SIZE)); assert_eq!(Request::parse(&request_ex(ZLIB_BIT | bc7, 0x1000, 0, 64, 0x2000, 0, 20, 64, 0)).check(false), Err(E_DESTINATION_SIZE)); - // Single-stage BCPack: intermediate must be 0, then E_DECOMPRESSION - assert_eq!(Request::parse(&request_ex(bc1, 0x1000, 0, 256, 0x2000, 0, 20, 0, 0)).check(false), Err(E_DECOMPRESSION)); + // Single-stage BCPack: intermediate must be 0, then E_DECOMPRESSION without a decoder for the mode + assert_eq!(Request::parse(&request_ex(bc7, 0x1000, 0, 256, 0x2000, 0, 20, 0, 0)).check(false), Err(E_DECOMPRESSION)); + assert_eq!(Request::parse(&request_ex(bc1, 0x1000, 0, 256, 0x2000, 0, 20, 0, 0)).check(false), Ok(())); assert_eq!(Request::parse(&request_ex(bc1, 0x1000, 0, 256, 0x2000, 0, 20, 64, 0)).check(false), Err(E_DESTINATION_SIZE)); // Hardware swizzle mode unsupported assert_eq!(Request::parse(&request_ex(swiz, 0x1000, 0, 64, 0x2000, 0, 64, 0, 0)).check(false), Err(E_DECOMPRESSION)); @@ -2122,19 +2209,99 @@ mod tests { let counts = BcpackRefusals::new(); let bc7 = Request::parse(&request(SOURCE_MEMORY_BIT | 7 << BCPACK_SHIFT, 0x1000, 0x10000, 0x2000, 0, 0x4000)); let bc7_zlib = Request::parse(&request(SOURCE_MEMORY_BIT | ZLIB_BIT | 7 << BCPACK_SHIFT, 0x1000, 0x10000, 0x2000, 0, 0x4000)); - let bc1 = Request::parse(&request(SOURCE_MEMORY_BIT | 1 << BCPACK_SHIFT, 0x1000, 0x8000, 0x2000, 0, 0x1000)); - for (i, r) in [&bc7, &bc7_zlib, &bc1, &bc7].into_iter().enumerate() { + let bc3 = Request::parse(&request(SOURCE_MEMORY_BIT | 3 << BCPACK_SHIFT, 0x1000, 0x8000, 0x2000, 0, 0x1000)); + for (i, r) in [&bc7, &bc7_zlib, &bc3, &bc7].into_iter().enumerate() { assert_eq!(r.check(true), Err(E_DECOMPRESSION), "the request fails as before"); assert_eq!(counts.note(r), i as u64 + 1); } let s = counts.stats(); - assert_eq!(s.keys().collect::>(), ["BC1", "BC7"]); + assert_eq!(s.keys().collect::>(), ["BC3", "BC7"]); assert_eq!((s["BC7"].requests, s["BC7"].with_zlib, s["BC7"].destination_bytes), (3, 1, 0x30000)); - assert_eq!((s["BC1"].requests, s["BC1"].with_zlib, s["BC1"].destination_bytes), (1, 0, 0x8000)); - assert_eq!(counts.summary(), "BC1 1 (32768 bytes), BC7 3 (196608 bytes)"); - for m in 1..=7u64 { + 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) + 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), Err(E_DECOMPRESSION)); + assert_eq!(r.check(true), if m == 1 { Ok(()) } else { Err(E_DECOMPRESSION) }, "mode {m}"); + } + } + + /// BC1 requests through a queue: BCPack alone and after zlib, against blocks built + /// independently of the decoder (`tests/data/bcpack`). + #[test] + fn bcpack_bc1_requests_are_unpacked_alone_and_after_zlib() { + use crate::hle::bcpack::tests as fx; + let bc1 = SOURCE_MEMORY_BIT | 1 << BCPACK_SHIFT; + let small = fx::data("bc1-16-1.bin").unwrap(); + let small_blocks = fx::data("bc1-16-1.bc1").unwrap(); + // 64 KiB of blocks; zero padding after the stream (as in a title's files) lets zlib shrink it + let mut large = fx::data("bc1-8192-3.bin").unwrap(); + large.resize(large.len() + 2048, 0); + let large_blocks = crate::hle::bcpack::bc1::assemble(&fx::large_fixture_symbols(1), fx::tables()).unwrap(); + let zipped = miniz_oxide::deflate::compress_to_vec_zlib(&large, 6); + assert!(zipped.len() < large.len() && large_blocks.len() == 0x10000); + unsafe { + 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(&32u16.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, 8, 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)); + let before = stats().bcpack_unpacked.get("BC1").cloned().unwrap_or_default(); + + // (options, source, destination size, intermediate size) → status, destination + let damaged = &small[..small.len() - 1]; + let cases: [(u64, &[u8], usize, usize, HRESULT, Option<&[u8]>); 7] = [ + (bc1, &small, small_blocks.len(), 0, S_OK, Some(&small_blocks)), + (bc1 | ZLIB_BIT, &zipped, 0x10000, large.len(), S_OK, Some(&large_blocks)), + (bc1 | ZLIB_BIT, &zipped, 0x10000, 0, S_OK, Some(&large_blocks)), + // the intermediate size is zlib's output to the byte + (bc1 | ZLIB_BIT, &zipped, 0x10000, large.len() + 1, E_ZLIB_DATA, None), + // a stream that is not whole, and one for another number of blocks + (bc1, damaged, small_blocks.len(), 0, E_DECOMPRESSION, None), + (bc1, &small, small_blocks.len() + 8, 0, E_DECOMPRESSION, None), + // control: the same bytes without the BCPack stage are not the blocks + (SOURCE_MEMORY_BIT, &small[..small_blocks.len()], small_blocks.len(), 0, S_OK, Some(&small[..small_blocks.len()])), + ]; + let mut dsts: Vec> = cases.iter().map(|c| vec![0xCDu8; c.2 + 64]).collect(); + for (i, (c, dst)) in cases.iter().zip(dsts.iter_mut()).enumerate() { + enqueue(q, request_ex(c.0, dst.as_mut_ptr() as u64, 0, c.2 as u32, c.1.as_ptr() as u64, 0, c.1.len() as u32, c.3 as u32, 0).as_ptr()); + status(q, s, i as u32); + } + submit(q); + let t = std::time::Instant::now(); + while !complete(s, cases.len() as u32 - 1) && t.elapsed().as_secs() < 10 { + std::thread::yield_now(); + } + for (i, (c, dst)) in cases.iter().zip(&dsts).enumerate() { + assert_eq!(hresult(s, i as u32), c.4, "request {i}"); + match c.5 { + Some(want) => assert!(&dst[..c.2] == want, "request {i}: the destination has the blocks"), + None => assert!(dst[..c.2].iter().all(|&b| b == 0xCD), "request {i}: a failed request writes nothing"), + } + assert!(dst[c.2..].iter().all(|&b| b == 0xCD), "request {i}: nothing past the destination size"); + } + assert_ne!(small[..small_blocks.len()], small_blocks[..], "the control differs from the blocks"); + 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); + queue_close(q); + queue_release(q); + status_release(s); } } diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 0b8f2a3..0a84078 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -162,6 +162,11 @@ const MEM_WRITE_WATCH: u32 = 0x20_0000; /// The console's MEM_64K_PAGES (MEM_LARGE_PAGES | MEM_PHYSICAL): title memory of 64 KiB /// pages – GPU-visible on the console like all title memory. const MEM_64K_PAGES: u32 = 0x2040_0000; +/// MEM_LARGE_PAGES: the console's 2 MiB pages of title memory (alone, or in MEM_64K_PAGES) +const MEM_LARGE_PAGES_X: u32 = 0x2000_0000; +/// a protection bit of the console's title memory the GPU uses (a newer retail title's index and vertex data: +/// 0x22004; its 2.2 GB block of other data: 0x2404) +const PAGE_GPU_X: u32 = 0x2_0000; /// Commit `[a, a + n)` of a sparse window (the title's reservations there) and give it video /// memory (`d3d12x::sparse`). @@ -185,9 +190,15 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: trace_mem("VirtualAlloc (sparse commit)", addr as usize, size, t as u64, p, q as usize); return q; } - // the title's own reservations of 64 KiB pages: in a sparse window, so the GPU sees them - if addr.is_null() && t & 0x2000 != 0 && t & MEM_64K_PAGES == MEM_64K_PAGES { - if let Some(q) = uma.and_then(|u| u.sparse_reserve(size)) { + // the title's own reservations of 64 KiB or large pages: in a sparse window, so the GPU sees + // them (a newer retail title keeps index and vertex data in a 1.2 GB VirtualAlloc of large pages; outside + // the windows the GPU faulted on it – a driver timeout) + let large = t & MEM_64K_PAGES != MEM_64K_PAGES && t & MEM_LARGE_PAGES_X != 0 && p & PAGE_GPU_X != 0; + if addr.is_null() && t & 0x2000 != 0 && (t & MEM_64K_PAGES == MEM_64K_PAGES || large) { + // (large pages: from the highest window down – the title's physical pages, gigabytes + // in one piece, keep the lower ones) + let top = |u: &crate::gpu::uma::Uma| (1..crate::gpu::uma::MAX_WINDOWS).rev().find_map(|k| u.sparse_alloc_in(k, size, crate::gpu::uma::GRAIN).map(|(q, _)| q)); + if let Some(q) = uma.and_then(|u| if large { top(u).or_else(|| u.sparse_reserve(size)) } else { u.sparse_reserve(size) }) { if t & 0x1000 != 0 && commit_sparse(q, size, p).is_null() { uma.map(|u| u.sparse_release(q)); return std::ptr::null_mut(); @@ -260,6 +271,21 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: } } } + // GPU-visible title memory the windows above had no room for (a retail game: a 24 GB + // reservation of 64 KiB pages, 2.2 GB of large pages with a graphics protection) is plain + // memory here. Textures the title places in it are kept in step with it + // (`d3d12x::title_textures`), which needs its CPU writes to be seen: it is write-watched + // like a graphics reservation. Without that such a texture was uploaded once, empty, and + // never again (the game's glyph atlas: its menus lost their x-height letters). + if addr.is_null() && t & 0x2000 != 0 && (t & (MEM_GRAPHICS | 0x2000_0000) != 0 || p & PAGE_GRAPHICS_ANY != 0) { + let q = mem::VirtualAlloc(addr, size, sanitize_alloc_type(t) | MEM_WRITE_WATCH, sanitize_protect(p)); + if !q.is_null() { + GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size); + GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + trace_mem("VirtualAlloc (GPU-visible, write-watched)", addr as usize, size, t as u64, p, q as usize); + return q; + } + } let q = mem::VirtualAlloc(addr, size, sanitize_alloc_type(t), sanitize_protect(p)); trace_mem("VirtualAlloc", addr as usize, size, t as u64, p, q as usize); q @@ -862,7 +888,7 @@ unsafe fn commit_homes(home: usize, n: usize) -> bool { return true; } let len = n * PHYS_PAGE; - if (0..n).all(|i| committed_page(home + i * PHYS_PAGE)) { + if committed_range(home, len) { return true; } if mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { @@ -875,13 +901,37 @@ unsafe fn commit_homes(home: usize, n: usize) -> bool { true } +/// Whether all of `[a, a + len)` is committed: one VirtualQuery per run of pages in one state +/// (page by page each asked walked the rest of the run). +fn committed_range(a: usize, len: usize) -> bool { + let mut p = a; + while p < a + len { + let mut m: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { mem::VirtualQuery(p as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 || m.State != mem::MEM_COMMIT { + return false; + } + p = m.BaseAddress as usize + m.RegionSize; + } + true +} + fn committed_page(a: usize) -> bool { + // A page in the working set is committed: asking for that is one entry, where VirtualQuery + // walks the page table to the end of the committed range the page is in (gigabytes of + // homes: 0.25 ms a page, and a scatter of pages from their homes grew with its square). + let mut ws = windows_sys::Win32::System::ProcessStatus::PSAPI_WORKING_SET_EX_INFORMATION { VirtualAddress: a as *mut c_void, ..Default::default() }; + if unsafe { windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx(thr::GetCurrentProcess(), &mut ws as *mut _ as *mut c_void, std::mem::size_of_val(&ws) as u32) } != 0 + && unsafe { ws.VirtualAttributes.Flags } & 1 != 0 + { + return true; + } let mut m: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; unsafe { mem::VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 && m.State == mem::MEM_COMMIT } } -/// Copy what is mapped at `at` back home and unmap it (Windows memory is decommitted). -unsafe fn unmap_away(away: &mut Away, at: usize) { +/// Copy what is mapped at `at` back home and unmap it (Windows memory is decommitted); the homes +/// in `committed` the caller has committed. +unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range) { if let Some(page) = away.at.remove(&at) { away.page.remove(&page); // never used where it was mapped: its home still holds the page (zeros) @@ -889,13 +939,15 @@ unsafe fn unmap_away(away: &mut Away, at: usize) { return; } // (a home this call has not given back yet is still committed) + let own = page_home(page); let pending = away.gone.len(); - away.gone.retain(|&h| Some(h) != page_home(page)); - let home = if away.gone.len() < pending { page_home(page) } else { page_home(page).and_then(|h| home_again(h)) }; + away.gone.retain(|&h| Some(h) != own); + let home = if away.gone.len() < pending || own.is_some_and(|h| committed.contains(&h)) { own } else { own.and_then(|h| home_again(h)) }; if let Some(home) = home { std::ptr::copy_nonoverlapping(at as *const u8, home as *mut u8, PHYS_PAGE); } - if !crate::gpu::uma::get().is_some_and(|u| u.is_committed(at)) { + // (an address among the homes the caller maps back is one of them: it stays) + if !committed.contains(&at) && !crate::gpu::uma::get().is_some_and(|u| u.is_committed(at)) { if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { crate::hle::d3d12x::sparse::decommitted(at, PHYS_PAGE); } @@ -1014,7 +1066,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) away.gone.retain(|&h| h < home || h >= home + n * PHYS_PAGE); for &p in &pages { if let Some(&at) = away.page.get(&p) { - unmap_away(away, at); + unmap_away(away, at, &(home..home + n * PHYS_PAGE)); } } return home as *mut c_void; @@ -1027,12 +1079,12 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) let in_uma = |a: usize| crate::gpu::uma::get().is_some_and(|u| u.is_committed(a)); for (i, &p) in pages.iter().enumerate() { let at = base + i * PHYS_PAGE; - unmap_away(away, at); + unmap_away(away, at, &(0..0)); if p == 0 { continue; } if let Some(&old) = away.page.get(&p) { - unmap_away(away, old); + unmap_away(away, old, &(0..0)); } let fresh = !in_uma(at) && !committed_page(at); let home = page_home(p).unwrap(); @@ -1863,6 +1915,206 @@ mod tests { } } + /// `XMemMapPhysicalPagesScatter` against a model of physical pages: random scatters of + /// pages to addresses (page 0: unmap), writes through the addresses and maps of the whole + /// allocation at its home. After each step every page reads what was last written to it + /// wherever it is mapped, a page never written reads zeros, and an address with no page is + /// not committed. + #[test] + fn scatter_matches_a_model_of_physical_pages() { + unsafe { + let Some(_) = crate::gpu::uma::get() else { return }; + const PAGES: usize = 24; + const SLOTS: usize = 32; + for seed in 1..=4u64 { + let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + let mut next = move || { + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + }; + let mut n = PAGES; + let mut pages = [0usize; PAGES]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let r = mem::VirtualAlloc(std::ptr::null(), SLOTS * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert!(r != 0); + let slot = |s: usize| r + s * PHYS_PAGE; + // model: what each page holds (first and last dword), where it is (None: home) + let mut value = [(0u32, 0u32); PAGES]; + let mut at: [Option; PAGES] = [None; PAGES]; + let mut held: [Option; SLOTS] = [None; SLOTS]; + let mut home: Option = None; + let read = |a: usize| ((a as *const u32).read_volatile(), ((a + PHYS_PAGE - 4) as *const u32).read_volatile()); + for step in 0..600 { + match next() % 8 { + // a scatter of 1–4 (slot, page or none) + 0..=3 => { + let k = 1 + (next() % 4) as usize; + let mut addrs = Vec::new(); + let mut ids = Vec::new(); + for _ in 0..k { + let s = (next() % SLOTS as u64) as usize; + let p = if next() % 5 == 0 { None } else { Some((next() % PAGES as u64) as usize) }; + addrs.push(slot(s) as *mut c_void); + ids.push(p.map_or(0, |p| pages[p] as u64)); + // model, in call order: what the slot held goes home; the page leaves + // where it was + if let Some(q) = held[s].take() { + at[q] = None; + } + if let Some(p) = p { + if let Some(old) = at[p].take() { + held[old] = None; + } + at[p] = Some(s); + held[s] = Some(p); + } + } + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), k, ids.as_mut_ptr()), 1, "seed {seed} step {step}"); + } + // a write through a mapped slot + 4..=6 => { + let s = (next() % SLOTS as u64) as usize; + if let Some(p) = held[s] { + let v = ((next() as u32) | 1, (next() as u32) | 1); + (slot(s) as *mut u32).write_volatile(v.0); + ((slot(s) + PHYS_PAGE - 4) as *mut u32).write_volatile(v.1); + value[p] = v; + } + } + // the whole allocation at its home: every page leaves its slot + _ => { + let h = MapTitlePhysicalPages(std::ptr::null_mut(), PAGES, 0, 4, pages.as_mut_ptr()) as usize; + assert!(h != 0); + home = Some(h); + at = [None; PAGES]; + held = [None; SLOTS]; + for (p, &v) in value.iter().enumerate() { + assert_eq!(read(h + p * PHYS_PAGE), v, "seed {seed} step {step}: page {p} at home"); + } + } + } + for s in 0..SLOTS { + match held[s] { + Some(p) => assert_eq!(read(slot(s)), value[p], "seed {seed} step {step}: page {p} at slot {s}"), + None => assert!(!committed_page(slot(s)), "seed {seed} step {step}: slot {s} has no page but is committed"), + } + } + } + let _ = home; + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), PAGES, pages.as_mut_ptr()), 1); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + } + + /// A home a page went back to in a call, then decommitted in the same call because another + /// page was mapped at that address and unmapped again, is not taken as committed: mapping + /// its page away does not read decommitted memory. + #[test] + fn a_home_decommitted_in_the_same_call_is_asked_again() { + unsafe { + let Some(_) = crate::gpu::uma::get() else { return }; + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let (p, q) = (pages[0], pages[1]); + let h = page_home(p).unwrap(); + let r = mem::VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + let (s, t) = (r as *mut c_void, (r + PHYS_PAGE) as *mut c_void); + let mut one = [p as u64]; + assert_eq!(XMemMapPhysicalPagesScatter(&s, 1, one.as_mut_ptr()), 1); + *(s as *mut u32) = 7; + // one call: p home (h holds it), q at h, h unmapped (decommitted), p to t + let at = [s, h as *mut c_void, h as *mut c_void, t]; + let mut ids = [0, q as u64, 0, p as u64]; + assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 4, ids.as_mut_ptr()), 1); + // (t reads: committed, or committed on first use) + let _ = (t as *const u32).read_volatile(); + assert!(!committed_page(s as usize)); + let mut none = [0u64, 0]; + let both = [s, t]; + assert_eq!(XMemMapPhysicalPagesScatter(both.as_ptr(), 2, none.as_mut_ptr()), 1); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// A page mapped at another page's home, then the whole allocation mapped back home: the + /// first page goes home and leaves that address committed, as the second one's home. + #[test] + fn a_page_away_at_another_home_goes_home_with_it() { + unsafe { + let Some(_) = crate::gpu::uma::get() else { return }; + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let (q, p) = (pages[0], pages[1]); + let h = page_home(p).unwrap(); + let r = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + let s = r as *mut c_void; + let mut one = [p as u64]; + assert_eq!(XMemMapPhysicalPagesScatter(&s, 1, one.as_mut_ptr()), 1); + *(s as *mut u32) = 7; + let at = h as *mut c_void; + let mut one = [q as u64]; + assert_eq!(XMemMapPhysicalPagesScatter(&at, 1, one.as_mut_ptr()), 1); + *(h as *mut u32) = 9; + let home = MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, pages.as_mut_ptr()) as usize; + assert_eq!(home, page_home(q).unwrap()); + assert_eq!(*(home as *const u32), 9); + assert_eq!(*(h as *const u32), 7); + assert!(!committed_page(r)); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// Timing (`--ignored --nocapture`; `XCL_SCATTER_PAGES=4096,8192`): pages written at their + /// home, scattered from there into a reservation in one call, scattered again in reverse, + /// and mapped back home. + #[test] + #[ignore] + fn scatter_timing() { + let sizes: Vec = std::env::var("XCL_SCATTER_PAGES").ok().map_or(vec![4096, 8192, 16384], |v| v.split(',').map(|s| s.parse().unwrap()).collect()); + let ms = |t: std::time::Instant| t.elapsed().as_secs_f64() * 1e3; + for n in sizes { + unsafe { + let mut cnt = n; + let mut pages = vec![0usize; n]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut cnt, pages.as_mut_ptr()), 1); + let h = MapTitlePhysicalPages(std::ptr::null_mut(), n, 0, 4, pages.as_mut_ptr()) as usize; + assert!(h != 0); + for i in 0..n { + *((h + i * PHYS_PAGE) as *mut u32) = i as u32 + 1; + } + let r = mem::VirtualAlloc(std::ptr::null(), n * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + let addrs: Vec<*mut c_void> = (0..n).map(|i| (r + i * PHYS_PAGE) as *mut c_void).collect(); + let mut ids: Vec = pages.iter().map(|&p| p as u64).collect(); + let t = std::time::Instant::now(); + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), n, ids.as_mut_ptr()), 1); + let from_home = ms(t); + ids.reverse(); + let t = std::time::Instant::now(); + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), n, ids.as_mut_ptr()), 1); + let reverse = ms(t); + for i in (0..n).step_by(97) { + assert_eq!(*((r + i * PHYS_PAGE) as *const u32), (n - i) as u32); + } + let t = std::time::Instant::now(); + assert_eq!(MapTitlePhysicalPages(std::ptr::null_mut(), n, 0, 4, pages.as_mut_ptr()) as usize, h); + let back = ms(t); + for i in (0..n).step_by(97) { + assert_eq!(*((h + i * PHYS_PAGE) as *const u32), i as u32 + 1); + } + eprintln!("scatter_timing pages={n} from_home={from_home:.1}ms reverse={reverse:.1}ms back_home={back:.1}ms"); + FreeTitlePhysicalPages(std::ptr::null_mut(), n, pages.as_mut_ptr()); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + } + #[test] fn title_memory_status_reports_budget() { let mut s: TitleMemoryStatusT = unsafe { std::mem::zeroed() }; @@ -2002,6 +2254,40 @@ mod tests { } } + /// GPU-visible title memory that falls back to plain memory (64 KiB pages, large pages, a + /// graphics protection) is write-watched: a texture placed there sees the CPU's writes. + #[test] + fn gpu_visible_fallback_memory_is_write_watched() { + unsafe { + // (MEM_64K_PAGES | MEM_RESERVE; MEM_LARGE_PAGES | MEM_RESERVE | MEM_COMMIT with a + // PAGE_GRAPHICS_* protection; MEM_GRAPHICS | MEM_RESERVE | MEM_COMMIT) + for (t, p) in [(0x2040_2000u32, mem::PAGE_READWRITE), (0x2000_3000, 0x2404), (MEM_GRAPHICS | 0x3000, mem::PAGE_READWRITE)] { + let size = 0x40_0000; + let q = VirtualAlloc(std::ptr::null(), size, t, p); + assert!(!q.is_null(), "flags {t:#x}"); + let a = q as usize; + if crate::gpu::uma::get().is_some_and(|u| u.contains(a) || u.is_sparse(a)) { + // a window had room: write-watched there (`uma::watch_regions`) + VirtualFree(q, 0, mem::MEM_RELEASE); + continue; + } + assert!(in_graphics_reservation(a), "flags {t:#x}: a fallback allocation is watched"); + if t & 0x1000 == 0 { + assert!(!VirtualAlloc((a + 0x2_0000) as *const c_void, 0x1_0000, 0x1000, mem::PAGE_READWRITE).is_null()); + } + let mut buf = [std::ptr::null_mut::(); 16]; + let (mut n, mut gran) = (buf.len(), 0u32); + assert_eq!(mem::GetWriteWatch(1, q, size, buf.as_mut_ptr(), &mut n, &mut gran), 0); + ((a + 0x2_1234) as *mut u8).write_volatile(7); + n = buf.len(); + assert_eq!(mem::GetWriteWatch(1, q, size, buf.as_mut_ptr(), &mut n, &mut gran), 0); + assert_eq!(&buf[..n], &[(a + 0x2_1000) as *mut c_void], "flags {t:#x}: the written page is reported"); + assert_eq!(VirtualFree(q, 0, mem::MEM_RELEASE), 1); + assert!(!in_graphics_reservation(a)); + } + } + } + #[test] fn virtual_free_ex_and_sparse_validation() { unsafe { diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index 3376735..fa750b9 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -16,7 +16,10 @@ use std::sync::{Once, RwLock}; use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; -use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, PAGE_READWRITE}; +use windows_sys::Win32::System::Memory::{ + VirtualAlloc, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, + PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, +}; const PAGE: usize = 0x1_0000; const EXCEPTION_CONTINUE_EXECUTION: i32 = -1; @@ -48,13 +51,27 @@ unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { } let page = r.ExceptionInformation[1] & !(PAGE - 1); let lazy = LAZY.read().unwrap_or_else(|e| e.into_inner()).contains(&page); - if lazy && commit(page) { + if lazy && commit(page) || allows(r.ExceptionInformation[0], r.ExceptionInformation[1]) { EXCEPTION_CONTINUE_EXECUTION } else { EXCEPTION_CONTINUE_SEARCH } } +unsafe fn allows(access: usize, at: usize) -> bool { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT || m.Protect & PAGE_GUARD != 0 { + return false; + } + let writes = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; + let reads = writes | PAGE_READONLY | PAGE_EXECUTE_READ; + match access { + 0 => m.Protect & reads != 0, + 1 => m.Protect & writes != 0, + _ => false, + } +} + /// `page` (reserved, 64 KiB aligned) is mapped: committed on first use. pub(crate) fn mark(page: usize) { install(); @@ -106,4 +123,37 @@ mod tests { VirtualFree(r as *mut c_void, 0, MEM_RELEASE); } } + + #[test] + fn threads_first_touching_one_lazy_page_together_all_go_on() { + const THREADS: usize = 8; + const PAGES: usize = 256; + unsafe { + let r = VirtualAlloc(std::ptr::null(), PAGES * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize; + for i in 0..PAGES { + mark(r + i * PAGE); + } + let barrier = std::sync::Arc::new(std::sync::Barrier::new(THREADS)); + let handles: Vec<_> = (0..THREADS) + .map(|t| { + let barrier = barrier.clone(); + std::thread::spawn(move || { + for i in 0..PAGES { + barrier.wait(); + std::ptr::write_volatile((r + i * PAGE + t * 64) as *mut u64, (i * THREADS + t) as u64); + } + }) + }) + .collect(); + for h in handles { + h.join().unwrap(); + } + for i in 0..PAGES { + for t in 0..THREADS { + assert_eq!(std::ptr::read_volatile((r + i * PAGE + t * 64) as *const u64), (i * THREADS + t) as u64); + } + } + VirtualFree(r as *mut c_void, 0, MEM_RELEASE); + } + } } diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index b07db46..10b8ed7 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -11,6 +11,7 @@ use crate::config::Config; use crate::util::glob_match; pub mod acphal; +pub mod bcpack; pub mod d3d12_layout; pub mod d3d12x; pub mod dstorage; diff --git a/crates/xcl/src/hle/xgameruntime/api.rs b/crates/xcl/src/hle/xgameruntime/api.rs index 87d8719..2af27ab 100644 --- a/crates/xcl/src/hle/xgameruntime/api.rs +++ b/crates/xcl/src/hle/xgameruntime/api.rs @@ -155,7 +155,14 @@ fn pc() -> Option<&'static Pc> { .as_ref() } +/// Set when the system runtime is there but refused to initialise (e.g. 0x80073cfc without a working +/// Gaming Services): its objects then fail fast on first use, so XCL's own fallbacks are used instead. +static PC_INIT_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + unsafe fn pc_object(c: &Guid, i: &Guid) -> Option { + if PC_INIT_FAILED.load(Ordering::Acquire) { + return None; + } let mut o: *mut c_void = std::ptr::null_mut(); ((pc()?.query)(c, i, &mut o) >= 0 && !o.is_null()).then_some(o as usize) } @@ -189,7 +196,8 @@ unsafe fn pc_init(gdk: u64, os: u64, flags: u64, options: *mut c_void) { hr = p.init.map(|f| f(gdk >> 32, gdk & 0xFFFF_FFFF)).unwrap_or(-1); } if hr < 0 { - crate::xlog_warn!("XGameRuntime PC: initialization → {:#x}", hr as u32); + crate::xlog_warn!("XGameRuntime PC: initialization → {:#x} – using XCL's own XAsync / fallbacks", hr as u32); + PC_INIT_FAILED.store(true, Ordering::Release); } start_pc_async(); } diff --git a/crates/xcl/src/hle/xgameruntime/mod.rs b/crates/xcl/src/hle/xgameruntime/mod.rs index a521773..c4dac5a 100644 --- a/crates/xcl/src/hle/xgameruntime/mod.rs +++ b/crates/xcl/src/hle/xgameruntime/mod.rs @@ -544,7 +544,7 @@ pub unsafe extern "system" fn XUserDuplicateHandle(h: *mut c_void, out: *mut *mu pub unsafe extern "system" fn XUserCloseHandle(h: *mut c_void) { if valid_user(h) { - let _ = USER.refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |v| Some(v.saturating_sub(1).max(1))); + let _ = USER.refs.try_update(Ordering::AcqRel, Ordering::Acquire, |v| Some(v.saturating_sub(1).max(1))); } } diff --git a/crates/xcl/src/insn.rs b/crates/xcl/src/insn.rs index 5b8488e..71cae7d 100644 --- a/crates/xcl/src/insn.rs +++ b/crates/xcl/src/insn.rs @@ -1,8 +1,22 @@ //! Instructions the console's CPU (Zen 2) has and a PC's may lack – a title raises //! STATUS_ILLEGAL_INSTRUCTION on them on an Intel CPU before Ice Lake / Alder Lake (CLWB, -//! SHA) or on any Intel CPU (CLZERO, RDPRU, MONITORX / MWAITX and SSE4a's EXTRQ / INSERTQ, -//! which are AMD's). The exception handler (`eh`) emulates the ones decoded here and steps over -//! them. +//! SHA) or on any Intel CPU (CLZERO, RDPRU, MONITORX / MWAITX and SSE4a's EXTRQ / INSERTQ / +//! MOVNTSS / MOVNTSD, which are AMD's). The exception handler (`eh`) emulates the ones decoded +//! here and steps over them. + +/// A memory operand (ModRM with its SIB and displacement): `base + index * scale + disp`, or +/// with `rip` the address of the next instruction + disp; with `a32` (an 0x67 prefix) the +/// address is 32 bits. Registers in CONTEXT order (rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi, +/// r8..r15). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Mem { + pub base: Option, + pub index: Option, + pub scale: u8, + pub disp: i32, + pub rip: bool, + pub a32: bool, +} /// A console-only instruction at the faulting address. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -29,6 +43,9 @@ pub enum ConsoleOnly { /// the length and index in xmm2's bits 69:64 and 77:72): the low bits of xmm2 put into a /// bit field of xmm1's low quadword. Insertq { dst: u8, src: u8, reg: bool, len: u8, idx: u8 }, + /// SSE4a `movntss m32, xmm` (F3 0F 2B /r, `bytes` 4) / `movntsd m64, xmm` (F2 0F 2B /r, + /// `bytes` 8): the low dword / quadword of XMM `src` stored without the cache + Movnts { bytes: u8, src: u8, mem: Mem }, /// `ud2`: the title's own trap (not emulated) Ud2, } @@ -61,6 +78,52 @@ pub fn insertq(dst: u64, src: u64, len: u8, idx: u8) -> u64 { (dst & !mask) | ((src & ones).checked_shl(idx).unwrap_or(0) & mask) } +/// The address of a memory operand: `regs` in CONTEXT order, `next` the address of the +/// instruction after it (for a rip-relative operand). +pub fn address(m: &Mem, regs: &[u64; 16], next: u64) -> u64 { + let base = if m.rip { next } else { m.base.map_or(0, |r| regs[r as usize & 15]) }; + let index = m.index.map_or(0, |r| regs[r as usize & 15].wrapping_mul(m.scale as u64)); + let a = base.wrapping_add(index).wrapping_add(m.disp as i64 as u64); + if m.a32 { + a & 0xFFFF_FFFF + } else { + a + } +} + +/// The memory operand of the ModRM byte at `b[0]` (with its SIB and displacement) and its +/// length; None for a register operand or when the bytes run out. REX.B extends the base, REX.X +/// the index. +fn mem_operand(b: &[u8], rex: u8, a32: bool) -> Option<(Mem, usize)> { + let len = modrm_len(b)?; + let (md, rm) = (b[0] >> 6, b[0] & 7); + if md == 3 { + return None; + } + let (rex_b, rex_x) = ((rex & 1) << 3, (rex & 2) << 2); + let mut m = Mem { base: Some(rm | rex_b), index: None, scale: 1, disp: 0, rip: false, a32 }; + let mut at = 1; + if rm == 4 { + let sib = b[1]; + let (index, base) = (((sib >> 3) & 7) | rex_x, sib & 7); + m.scale = 1 << (sib >> 6); + // index 100 is no index (with REX.X it is r12) + m.index = (index != 4).then_some(index); + // base 101 with mod 00 is no base and a disp32 (r13 takes mod 01) + m.base = (md != 0 || base != 5).then_some(base | rex_b); + at = 2; + } else if md == 0 && rm == 5 { + m.base = None; + m.rip = true; + } + m.disp = match len - at { + 0 => 0, + 1 => b[at] as i8 as i32, + _ => i32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]), + }; + Some((m, len)) +} + /// The length of a ModRM-encoded operand (ModRM, SIB and displacement) at `b[0]`, None when the /// bytes run out. fn modrm_len(b: &[u8]) -> Option { @@ -89,6 +152,8 @@ pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { let mut i = 0; // `rep`: the last of F2 / F3, which decides between them (and over 66) for SSE4a let (mut p66, mut pf3, mut rep, mut rex) = (false, false, 0u8, 0u8); + // for a memory operand: an fs / gs override (its base is not in the context), 0x67 + let (mut fs_gs, mut a32) = (false, false); while let Some(&b) = code.get(i) { match b { 0x66 => p66 = true, @@ -97,7 +162,9 @@ pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { pf3 = true; rep = 0xF3; } - 0x2E | 0x3E | 0x26 | 0x36 | 0x64 | 0x65 | 0x67 => {} + 0x64 | 0x65 => fs_gs = true, + 0x67 => a32 = true, + 0x2E | 0x3E | 0x26 | 0x36 => {} // REX counts only right before the opcode: one before a legacy prefix is ignored 0x40..=0x4F => { rex = b; @@ -151,6 +218,14 @@ pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { _ => None, } } + // SSE4a scalar streaming stores, memory operands only: F3 0F 2B movntss, F2 0F 2B + // movntsd (the last of F2 / F3 decides; without them it is movntps, with 66 alone + // movntpd). One through fs / gs is left to fault. + (0x2B, Some(m)) if rep != 0 && m >> 6 != 3 && !fs_gs => { + let (mem, len) = mem_operand(&code[i + 2..], rex, a32)?; + let src = ((m >> 3) & 7) | (rex & 4) << 1; + Some((ConsoleOnly::Movnts { bytes: if rep == 0xF2 { 8 } else { 4 }, src, mem }, i + 2 + len)) + } // 66 0F AE /6 with a memory operand (without 66 it is xsaveopt) (0xAE, Some(m)) if p66 && (m >> 3) & 7 == 6 && m >> 6 != 3 => Some((ConsoleOnly::Clwb, i + 2 + modrm_len(&code[i + 2..])?)), // F3 0F C7 /7 with a register operand @@ -234,4 +309,52 @@ mod tests { assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24]), None); assert_eq!(decode(&[0x0F]), None); } + + #[test] + fn decodes_the_sse4a_streaming_stores() { + let m = |base: Option, index: Option, scale: u8, disp: i32| Mem { base, index, scale, disp, rip: false, a32: false }; + // movntsd [rax], xmm0; movntss [rsp+8], xmm1; movntsd [rip+0x10], xmm2 + assert_eq!(decode(&[0xF2, 0x0F, 0x2B, 0x00]), Some((ConsoleOnly::Movnts { bytes: 8, src: 0, mem: m(Some(0), None, 1, 0) }, 4))); + assert_eq!(decode(&[0xF3, 0x0F, 0x2B, 0x4C, 0x24, 0x08]), Some((ConsoleOnly::Movnts { bytes: 4, src: 1, mem: m(Some(4), None, 1, 8) }, 6))); + assert_eq!( + decode(&[0xF2, 0x0F, 0x2B, 0x15, 0x10, 0, 0, 0]), + Some((ConsoleOnly::Movnts { bytes: 8, src: 2, mem: Mem { rip: true, ..m(None, None, 1, 0x10) } }, 8)) + ); + // movntsd [r8+r12*4-4], xmm9 (REX.RXB); movntsd [r13+0], xmm0; movntsd [0x1000], xmm0 (a SIB + // without base or index); movntss [rbp+rsi*8+0x12345678], xmm3 + assert_eq!(decode(&[0xF2, 0x47, 0x0F, 0x2B, 0x4C, 0xA0, 0xFC]), Some((ConsoleOnly::Movnts { bytes: 8, src: 9, mem: m(Some(8), Some(12), 4, -4) }, 7))); + assert_eq!(decode(&[0xF2, 0x41, 0x0F, 0x2B, 0x45, 0x00]), Some((ConsoleOnly::Movnts { bytes: 8, src: 0, mem: m(Some(13), None, 1, 0) }, 6))); + assert_eq!(decode(&[0xF2, 0x0F, 0x2B, 0x04, 0x25, 0, 0x10, 0, 0]), Some((ConsoleOnly::Movnts { bytes: 8, src: 0, mem: m(None, None, 1, 0x1000) }, 9))); + assert_eq!( + decode(&[0xF3, 0x0F, 0x2B, 0x9C, 0xF5, 0x78, 0x56, 0x34, 0x12]), + Some((ConsoleOnly::Movnts { bytes: 4, src: 3, mem: m(Some(5), Some(6), 8, 0x1234_5678) }, 9)) + ); + // the last of F2 / F3 decides, 66 next to them does not; 0x67 makes the address 32 bits + assert_eq!(decode(&[0xF2, 0xF3, 0x0F, 0x2B, 0x00]).map(|(c, _)| c), Some(ConsoleOnly::Movnts { bytes: 4, src: 0, mem: m(Some(0), None, 1, 0) })); + assert_eq!(decode(&[0x66, 0xF2, 0x0F, 0x2B, 0x00]).map(|(c, _)| c), Some(ConsoleOnly::Movnts { bytes: 8, src: 0, mem: m(Some(0), None, 1, 0) })); + assert_eq!(decode(&[0x67, 0xF2, 0x0F, 0x2B, 0x00]), Some((ConsoleOnly::Movnts { bytes: 8, src: 0, mem: Mem { a32: true, ..m(Some(0), None, 1, 0) } }, 5))); + // not these: movntps (no prefix), movntpd (66), a register operand, through gs, cut short + assert_eq!(decode(&[0x0F, 0x2B, 0x00]), None); + assert_eq!(decode(&[0x66, 0x0F, 0x2B, 0x00]), None); + assert_eq!(decode(&[0xF2, 0x0F, 0x2B, 0xC0]), None); + assert_eq!(decode(&[0x65, 0xF2, 0x0F, 0x2B, 0x04, 0x25, 0, 0x10, 0, 0]), None); + assert_eq!(decode(&[0xF2, 0x0F, 0x2B, 0x44]), None); + assert_eq!(decode(&[0xF2, 0x0F, 0x2B, 0x80, 1, 2, 3]), None); + } + + #[test] + fn memory_operand_addresses() { + let mut regs = [0u64; 16]; + regs[4] = 0x1000; // rsp + regs[8] = 0x2000; // r8 + regs[12] = 3; // r12 + regs[0] = 0x1_FFFF_FFF0; // rax + let m = Mem { base: Some(8), index: Some(12), scale: 4, disp: -4, rip: false, a32: false }; + assert_eq!(address(&m, ®s, 0), 0x2000 + 12 - 4); + assert_eq!(address(&Mem { base: Some(4), index: None, scale: 1, disp: 8, ..m }, ®s, 0), 0x1008); + assert_eq!(address(&Mem { base: None, index: None, disp: -0x10, rip: true, ..m }, ®s, 0x5000), 0x4FF0); + assert_eq!(address(&Mem { base: None, index: None, disp: 0x1000, ..m }, ®s, 0x5000), 0x1000); + // a 32-bit address wraps at 4 GiB + assert_eq!(address(&Mem { base: Some(0), index: None, disp: 0x20, a32: true, ..m }, ®s, 0), 0x10); + } } diff --git a/crates/xcl/src/loader.rs b/crates/xcl/src/loader.rs index 52c49af..5297d15 100644 --- a/crates/xcl/src/loader.rs +++ b/crates/xcl/src/loader.rs @@ -191,7 +191,7 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result, String> let index_ptr = if t.address_of_index == 0 { std::ptr::null_mut() } else { adj(t.address_of_index) as *mut u32 }; unsafe { // game DLLs loaded while its imports were resolved may point into it: its memory stays - tls_install(&module, template, template_len, t.total_len(), index_ptr).inspect_err(|_| modules::unregister_mapped(base))?; + tls_install(&module, template, template_len, t.total_len(), t.characteristics, index_ptr).inspect_err(|_| modules::unregister_mapped(base))?; if t.address_of_callbacks != 0 { let mut cb = adj(t.address_of_callbacks) as *const u64; let mut list = module.tls_callbacks.lock().unwrap(); @@ -234,8 +234,15 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result, String> Ok(module) } -unsafe fn tls_install(m: &MappedModule, template: usize, len: usize, total: u64, index_ptr: *mut u32) -> Result<(), String> { - let k = crate::tls::install(&m.name, template, len, total, index_ptr, &cache_dir())?; +unsafe fn tls_install( + m: &MappedModule, + template: usize, + len: usize, + total: u64, + characteristics: u32, + index_ptr: *mut u32, +) -> Result<(), String> { + let k = crate::tls::install(&m.name, template, len, total, characteristics, index_ptr, &cache_dir())?; // the title's executable: slot 0, as a process's executable has it if !m.is_dll { if let Err(e) = crate::tls::take_slot_zero(&m.name, index_ptr, k) { diff --git a/crates/xcl/src/pe.rs b/crates/xcl/src/pe.rs index 8ff1915..2811640 100644 --- a/crates/xcl/src/pe.rs +++ b/crates/xcl/src/pe.rs @@ -29,6 +29,7 @@ pub const IMAGE_REL_BASED_DIR64: u16 = 10; pub const SCN_MEM_EXECUTE: u32 = 0x2000_0000; pub const SCN_MEM_READ: u32 = 0x4000_0000; pub const SCN_MEM_WRITE: u32 = 0x8000_0000; +pub const SCN_ALIGN_MASK: u32 = 0x00F0_0000; #[derive(Debug, Clone, PartialEq, Eq)] pub enum PeError { @@ -139,6 +140,38 @@ impl TlsDir { pub fn total_len(&self) -> u64 { self.template_len() + self.size_of_zero_fill as u64 } + /// Alignment in bytes encoded in `Characteristics` bits 20..23 + /// (`IMAGE_SCN_ALIGN_*BYTES`, nibble `1..=14` → `1..=8192` bytes), or `1` + /// when unspecified (`0`) or invalid (`15`). + pub fn alignment(&self) -> u32 { + tls_alignment_from_characteristics(self.characteristics) + } + /// `Characteristics` masked down to a valid `IMAGE_SCN_ALIGN_*BYTES` value + /// (nibble `1..=14`), clearing reserved bits and the invalid `0xF` mask value. + pub fn align_characteristics(&self) -> u32 { + sanitize_tls_characteristics(self.characteristics) + } +} + +/// Decode `IMAGE_SCN_ALIGN_*BYTES` (bits 20..23) into a byte alignment (`1..=8192`). +pub fn tls_alignment_from_characteristics(characteristics: u32) -> u32 { + let nibble = (characteristics & SCN_ALIGN_MASK) >> 20; + if (1..=14).contains(&nibble) { + 1u32 << (nibble - 1) + } else { + 1 + } +} + +/// Mask `IMAGE_TLS_DIRECTORY64.Characteristics` to a valid `IMAGE_SCN_ALIGN_*BYTES` +/// value (nibble `1..=14`), clearing reserved bits and the invalid `0xF` mask value. +pub fn sanitize_tls_characteristics(characteristics: u32) -> u32 { + let nibble = (characteristics & SCN_ALIGN_MASK) >> 20; + if (1..=14).contains(&nibble) { + nibble << 20 + } else { + 0 + } } #[derive(Debug, Clone, PartialEq, Eq)] @@ -799,5 +832,50 @@ mod tests { let tls = pe.tls().unwrap().expect("rust binaries have a TLS directory"); assert!(tls.end_raw >= tls.start_raw); assert!(pe.va_to_rva(tls.address_of_index).is_some()); + assert!(tls.alignment().is_power_of_two()); + } + + #[test] + fn tls_characteristics_alignment_decoding() { + assert_eq!(tls_alignment_from_characteristics(0), 1); + assert_eq!(sanitize_tls_characteristics(0), 0); + for nibble in 1..=14u32 { + let expected_align = 1u32 << (nibble - 1); + let raw = (nibble << 20) | (0xDEAD_BEEF & !SCN_ALIGN_MASK); // include reserved noise bits outside mask + let dir = TlsDir { characteristics: raw, ..Default::default() }; + assert_eq!(dir.alignment(), expected_align, "nibble {nibble}"); + assert_eq!(dir.align_characteristics(), nibble << 20, "nibble {nibble}"); + } + // Specific common PE alignment flags: + assert_eq!(tls_alignment_from_characteristics(0x0060_0000), 32); + assert_eq!(tls_alignment_from_characteristics(0x0070_0000), 64); + assert_eq!(tls_alignment_from_characteristics(0x00D0_0000), 4096); + assert_eq!(tls_alignment_from_characteristics(0x00E0_0000), 8192); + // Invalid nibble 0xF (IMAGE_SCN_ALIGN_MASK itself) maps to 1 / 0: + assert_eq!(tls_alignment_from_characteristics(SCN_ALIGN_MASK), 1); + assert_eq!(sanitize_tls_characteristics(SCN_ALIGN_MASK), 0); + } + + #[test] + fn parses_tls_characteristics_from_pe() { + let mut bytes = crate::tls::build_carrier_dll_with( + 0x100, + crate::tls::CarrierOpts { characteristics: 0x0070_0000, ..Default::default() }, + ); + let pe = Pe::parse(&bytes, Layout::File).unwrap(); + let tls = pe.tls().unwrap().unwrap(); + assert_eq!(tls.characteristics, 0x0070_0000); + assert_eq!(tls.alignment(), 64); + assert_eq!(tls.align_characteristics(), 0x0070_0000); + + // Patch raw Characteristics field directly in the PE to verify Pe::tls reads offset +36 verbatim. + let tls_off = pe.rva_to_offset(pe.dir(DIR_TLS).rva).unwrap(); + drop(pe); + bytes[tls_off + 36..tls_off + 40].copy_from_slice(&0x1260_00ABu32.to_le_bytes()); + let pe = Pe::parse(&bytes, Layout::File).unwrap(); + let tls = pe.tls().unwrap().unwrap(); + assert_eq!(tls.characteristics, 0x1260_00AB); + assert_eq!(tls.alignment(), 32); + assert_eq!(tls.align_characteristics(), 0x0060_0000); } } diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index 378f4b3..62b4a8f 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -75,7 +75,7 @@ pub struct Report { /// XCL slots it called that XCL does not implement #[serde(default)] pub xgameruntime: crate::hle::xgameruntime::api::ApiStats, - /// DirectStorage: BCPack requests refused (no decoder) by mode, and bytes filled under + /// DirectStorage: BCPack requests unpacked and refused (no decoder) by mode, and bytes filled under /// `XCL_DSTORAGE_BCPACK_FILL` #[serde(default)] pub dstorage: crate::hle::dstorage::DStorageStats, @@ -132,7 +132,7 @@ pub fn build() -> Report { xcl_version: env!("CARGO_PKG_VERSION").to_string(), title: boot.map(|b| b.title.clone()).unwrap_or_default(), exe: boot.map(|b| b.exe_path.to_string_lossy().into_owned()).unwrap_or_default(), - crash: CRASH.lock().ok().and_then(|g| g.clone()), + crash: CRASH.lock().unwrap_or_else(|p| p.into_inner()).clone(), exit_code: None, environment: Vec::new(), imports_by_source: by_source, @@ -154,14 +154,66 @@ pub fn build() -> Report { } } +thread_local! { + static IN_WRITE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +struct InWriteGuard; +impl InWriteGuard { + fn enter() -> Option { + IN_WRITE.with(|c| { + if c.get() { + None + } else { + c.set(true); + Some(InWriteGuard) + } + }) + } +} +impl Drop for InWriteGuard { + fn drop(&mut self) { + IN_WRITE.with(|c| c.set(false)); + } +} + +/// Fallback report when a full `build()` cannot be completed (e.g. re-entrant crash or lock contention). +fn build_fallback(crash: Option) -> Report { + let boot = crate::state::boot(); + Report { + xcl_version: env!("CARGO_PKG_VERSION").to_string(), + title: boot.map(|b| b.title.clone()).unwrap_or_default(), + exe: boot.map(|b| b.exe_path.to_string_lossy().into_owned()).unwrap_or_default(), + crash, + notes: vec![ + "Fallback crash report written due to lock contention or re-entrant crash during exit.".into(), + ], + ..Default::default() + } +} + +fn write_report_file(path: &std::path::Path, r: &Report) -> bool { + if let Ok(s) = serde_json::to_string_pretty(r) { + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + std::fs::write(path, s).is_ok() + } else { + false + } +} + /// `m.try_lock()`, retried for `wait`: never an endless wait – the holder may be this very -/// thread, crashed inside `build()`. +/// thread, crashed inside `build()`. Recovers from mutex poisoning. fn lock_within(m: &Mutex, wait: Duration) -> Option> { let end = Instant::now() + wait; loop { match m.try_lock() { Ok(g) => return Some(g), - Err(TryLockError::WouldBlock) if Instant::now() < end => std::thread::sleep(Duration::from_millis(10)), + Err(TryLockError::Poisoned(p)) => return Some(p.into_inner()), + Err(TryLockError::WouldBlock) if Instant::now() < end => { + std::thread::sleep(Duration::from_millis(2)); + } Err(_) => return None, } } @@ -171,19 +223,70 @@ fn lock_within(m: &Mutex, wait: Duration) -> Option> { pub fn write_final(crash: Option) { // the process ends: a cursor held in the XCL window is let go crate::hle::kbm::release(); - // a crash is kept even while another thread writes the report, and is written once that - // thread is done – the process ends right after (#106); other calls give way at once + let wait = if crash.is_some() { Duration::from_secs(2) } else { Duration::ZERO }; - if let Some(c) = crash { + + // Record crash in CRASH static first so it is never lost regardless of lock state + if let Some(c) = crash.as_ref() { if let Some(mut g) = lock_within(&CRASH, wait) { - g.get_or_insert(c); + g.get_or_insert_with(|| c.clone()); } } - let Some(_g) = lock_within(&WRITE_LOCK, wait) else { return }; + + // Check re-entrancy on the same thread: if this thread already holds WRITE_LOCK and crashed + // inside build() or write_final(), avoid deadlocking on WRITE_LOCK or re-entering build() + let Some(_in_write_guard) = InWriteGuard::enter() else { + let recorded = CRASH.lock().unwrap_or_else(|p| p.into_inner()).clone(); + if let Some(boot) = crate::state::boot() { + let path = boot.report_path(); + let mut r = load(&path).unwrap_or_else(|| build_fallback(None)); + if recorded.is_some() { + r.crash = recorded; + } + write_report_file(&path, &r); + } + return; + }; + + // A crash is kept even while another thread writes the report, and is written once that + // thread is done – the process ends right after (#106); other calls give way at once + let lock_guard = lock_within(&WRITE_LOCK, wait); + let Some(_g) = lock_guard else { + // WRITE_LOCK had contention or timed out. If there is a crash recorded, + // ensure it is persisted even without the lock so crash info is never dropped. + let recorded = CRASH.lock().unwrap_or_else(|p| p.into_inner()).clone(); + if recorded.is_some() { + if let Some(boot) = crate::state::boot() { + let path = boot.report_path(); + let mut r = load(&path).unwrap_or_else(|| build_fallback(None)); + r.crash = recorded; + write_report_file(&path, &r); + } + } + return; + }; + let Some(boot) = crate::state::boot() else { return }; - let r = build(); - if let Ok(s) = serde_json::to_string_pretty(&r) { - let _ = std::fs::write(boot.report_path(), s); + let mut r = build(); + + // Re-check CRASH in case another thread recorded a crash while build() was running + if r.crash.is_none() { + let current = CRASH.lock().unwrap_or_else(|p| p.into_inner()).clone(); + if current.is_some() { + r.crash = current; + } + } + + let path = boot.report_path(); + write_report_file(&path, &r); + + // If a crash arrived while writing to disk, update the file before releasing WRITE_LOCK + if r.crash.is_none() { + let current = CRASH.lock().unwrap_or_else(|p| p.into_inner()).clone(); + if let Some(c) = current { + r.crash = Some(c); + write_report_file(&path, &r); + } } } @@ -195,8 +298,12 @@ pub fn load(path: &std::path::Path) -> Option { mod tests { use super::*; + static TEST_SERIAL: Mutex<()> = Mutex::new(()); + #[test] fn a_crash_is_kept_while_another_thread_writes_the_report() { + let _lock = TEST_SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + *CRASH.lock().unwrap_or_else(|p| p.into_inner()) = None; let (held, wait_held) = std::sync::mpsc::channel(); let writer = std::thread::spawn(move || { let _g = WRITE_LOCK.lock().unwrap(); @@ -207,7 +314,87 @@ mod tests { // no boot record in unit tests: nothing is written to disk write_final(Some("boom".into())); writer.join().unwrap(); - assert_eq!(CRASH.lock().unwrap().as_deref(), Some("boom")); - *CRASH.lock().unwrap() = None; + assert_eq!(CRASH.lock().unwrap_or_else(|p| p.into_inner()).as_deref(), Some("boom")); + *CRASH.lock().unwrap_or_else(|p| p.into_inner()) = None; + } + + #[test] + fn lock_within_recovers_from_poisoned_mutex() { + let m = Mutex::new(42); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _g = m.lock().unwrap(); + panic!("poisoning mutex"); + })); + assert!(m.is_poisoned()); + let guard = lock_within(&m, Duration::from_millis(50)); + assert!(guard.is_some()); + assert_eq!(*guard.unwrap(), 42); + } + + #[test] + fn write_final_recovers_when_crash_mutex_is_poisoned() { + let _lock = TEST_SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + *CRASH.lock().unwrap_or_else(|p| p.into_inner()) = None; + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _g = CRASH.lock().unwrap_or_else(|p| p.into_inner()); + panic!("poisoning CRASH"); + })); + write_final(Some("recovered".into())); + assert_eq!(CRASH.lock().unwrap_or_else(|p| p.into_inner()).as_deref(), Some("recovered")); + *CRASH.lock().unwrap_or_else(|p| p.into_inner()) = None; + } + + #[test] + fn first_crash_payload_is_preserved_under_contention() { + let _lock = TEST_SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + *CRASH.lock().unwrap_or_else(|p| p.into_inner()) = None; + write_final(Some("first-crash".into())); + write_final(Some("second-crash".into())); + assert_eq!(CRASH.lock().unwrap_or_else(|p| p.into_inner()).as_deref(), Some("first-crash")); + *CRASH.lock().unwrap_or_else(|p| p.into_inner()) = None; + } + + #[test] + fn reentrant_write_final_does_not_deadlock() { + let _lock = TEST_SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + *CRASH.lock().unwrap_or_else(|p| p.into_inner()) = None; + let _guard = InWriteGuard::enter().unwrap(); + // Inside write_final simulated: a crash occurs and write_final is called re-entrantly + write_final(Some("reentrant-crash".into())); + assert_eq!(CRASH.lock().unwrap_or_else(|p| p.into_inner()).as_deref(), Some("reentrant-crash")); + drop(_guard); + *CRASH.lock().unwrap_or_else(|p| p.into_inner()) = None; + } + + #[test] + fn concurrent_exit_and_crash_persists_without_deadlock() { + let _lock = TEST_SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + *CRASH.lock().unwrap_or_else(|p| p.into_inner()) = None; + let mut handles = Vec::new(); + for i in 0..10 { + handles.push(std::thread::spawn(move || { + if i % 2 == 0 { + write_final(Some(format!("concurrent-crash-{i}"))); + } else { + write_final(None); + } + })); + } + for h in handles { + h.join().unwrap(); + } + let recorded = CRASH.lock().unwrap_or_else(|p| p.into_inner()).clone(); + assert!(recorded.is_some()); + assert!(recorded.unwrap().starts_with("concurrent-crash-")); + *CRASH.lock().unwrap_or_else(|p| p.into_inner()) = None; + } + + #[test] + fn fallback_report_structure_is_valid() { + let r = build_fallback(Some("test-fallback-crash".into())); + assert_eq!(r.crash.as_deref(), Some("test-fallback-crash")); + let json = serde_json::to_string_pretty(&r).expect("fallback report must serialize to valid JSON"); + let parsed: Report = serde_json::from_str(&json).expect("fallback report must deserialize"); + assert_eq!(parsed.crash.as_deref(), Some("test-fallback-crash")); } } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 5c3027d..9baf1d1 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -737,20 +737,133 @@ pub fn run(path: &Path, args: &[String]) -> i32 { /// ABI root signature with its static samplers): the driver keeps what it compiled in its own /// cache, which the title then finds – a retail game's 1 MB-DXIL programs kept its loading /// waiting for the driver's compiler for minutes. Nothing runs on the GPU. +/// +/// The driver's compiles run on threads of their own (`drain`), fed by `BiggestFirst`. The +/// translating threads used to make each pipeline themselves: with four driver slots taken by +/// programs of several minutes each, every one of them waited for a slot and translation +/// stopped (a retail pack sat at 22 800 / 26 503 for many minutes); and in file order the +/// biggest program could come last and run alone. +/// Each driver thread takes the biggest program whose compile fits in the memory that is free +/// (`driver_fits`): the biggest ones start first, and while they fill the memory the threads +/// left over make the small ones instead of waiting – taken strictly biggest first, seven +/// programs of minutes each held all the memory and nothing else was made meanwhile. struct Pipelines { dev: windows::Win32::Graphics::Direct3D12::ID3D12Device, signatures: Mutex, windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, made: AtomicUsize, refused: AtomicUsize, - /// driver compiles running and the most at once (`XCL_PIPELINE_THREADS`, 4): each of the - /// biggest takes ~1.5 GB in the driver – fifteen at once took 24 GB - running: (Mutex, std::sync::Condvar), - most: usize, + /// the driver compiles running now: when each started and its DXIL bytes + running: Mutex>, + /// driver threads: `XCL_PIPELINE_THREADS` (that many at once, memory not watched), or half + /// the cores (at most 16) with `driver_fits` watching memory + threads: usize, + fixed: bool, } // D3D12 devices and root signatures are free-threaded unsafe impl Sync for Pipelines {} +/// Memory kept free besides the driver's compiles. +const DRIVER_RESERVE: u64 = 2 << 30; +/// What the driver's compile of a program is taken to need: 1536 bytes for each byte of DXIL, +/// between 64 MB and 1.5 GB (a 1 MB program took ~1.5 GB, and seven of 1 – 25 MB at once +/// 8.7 GB; fifteen at once took 24 GB). +const DRIVER_PER_BYTE: u64 = 1536; +const DRIVER_LEAST: u64 = 64 << 20; +const DRIVER_MOST: u64 = 3 << 29; + +fn driver_memory(dxil: usize) -> u64 { + (dxil as u64).saturating_mul(DRIVER_PER_BYTE).clamp(DRIVER_LEAST, DRIVER_MOST) +} + +/// The most DXIL bytes a program may have for its driver compile to start now, with those of +/// `running` (DXIL bytes each) going and `avail` bytes free (the smaller of physical memory +/// and commit). None: nothing may start. With nothing running anything may. +fn driver_fits(running: &[usize], avail: u64) -> Option { + if running.is_empty() { + return Some(usize::MAX); + } + // the running ones are counted in full: `avail` shows what they took only once they have + let held = running.iter().fold(DRIVER_RESERVE, |sum, &n| sum.saturating_add(driver_memory(n))); + let room = avail.checked_sub(held).filter(|&r| r >= DRIVER_LEAST)?; + Some(if room >= DRIVER_MOST { usize::MAX } else { (room / DRIVER_PER_BYTE) as usize }) +} + +/// Work waiting for a slow consumer, handed out biggest first; `push` waits while more than +/// `max_bytes` are waiting (otherwise a whole pack's compute DXIL could pile up in memory). +struct BiggestFirst { + state: Mutex>, + cv: std::sync::Condvar, + max_bytes: usize, +} + +struct BiggestState { + /// by (size, usize::MAX - the order queued): the last is the biggest, queued first + items: std::collections::BTreeMap<(usize, usize), T>, + bytes: usize, + seq: usize, + closed: bool, +} + +impl BiggestFirst { + fn new(max_bytes: usize) -> Self { + BiggestFirst { state: Mutex::new(BiggestState { items: Default::default(), bytes: 0, seq: 0, closed: false }), cv: Default::default(), max_bytes } + } + + fn push(&self, size: usize, item: T) { + let mut g = self.state.lock().unwrap(); + while !g.items.is_empty() && g.bytes + size > self.max_bytes { + g = self.cv.wait(g).unwrap(); + } + let key = (size, usize::MAX - g.seq); + g.seq += 1; + g.bytes += size; + g.items.insert(key, item); + self.cv.notify_all(); + } + + /// The biggest waiting item; None once closed and empty. + #[cfg(test)] + fn pop(&self) -> Option { + self.pop_fitting(|| Some(usize::MAX), |_| ()) + } + + /// The biggest waiting item no bigger than `limit()` says (None: none may be taken now), + /// asked again every 200 ms while nothing fits; `taken(size)` is called for the item + /// before another taker is asked for its limit. None once closed and empty. + fn pop_fitting(&self, mut limit: impl FnMut() -> Option, taken: impl FnOnce(usize)) -> Option { + let mut g = self.state.lock().unwrap(); + loop { + if g.items.is_empty() { + if g.closed { + return None; + } + g = self.cv.wait(g).unwrap(); + continue; + } + let key = limit().and_then(|most| g.items.range(..=(most, usize::MAX)).next_back().map(|(&k, _)| k)); + if let Some(key) = key { + let item = g.items.remove(&key)?; + g.bytes -= key.0; + taken(key.0); + self.cv.notify_all(); + return Some(item); + } + g = self.cv.wait_timeout(g, std::time::Duration::from_millis(200)).unwrap().0; + } + } + + /// No more pushes: a pop returns None once the rest is taken. + fn close(&self) { + self.state.lock().unwrap().closed = true; + self.cv.notify_all(); + } + + fn len(&self) -> usize { + self.state.lock().unwrap().items.len() + } +} + impl Pipelines { fn new() -> Result { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; @@ -760,9 +873,68 @@ impl Pipelines { let sel = crate::gpu::adapter::Selector::from_env_or("auto"); let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?; - let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1); - Ok(Pipelines { dev, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), most }) + let fixed = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse::().ok()); + let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); + Ok(Pipelines { + dev, + signatures: Mutex::new(Default::default()), + made: AtomicUsize::new(0), + refused: AtomicUsize::new(0), + running: Mutex::new(Vec::new()), + threads: fixed.unwrap_or((cores / 2).clamp(1, 16)).max(1), + fixed: fixed.is_some(), + }) + } + } + + /// The most DXIL bytes of a program whose driver compile may start now (`driver_fits`). + fn fits(&self) -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + if self.fixed { + return Some(usize::MAX); + } + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + if unsafe { GlobalMemoryStatusEx(&mut m) } == 0 { + return Some(usize::MAX); + } + let running: Vec = self.running.lock().unwrap().iter().map(|r| r.1).collect(); + driver_fits(&running, m.ullAvailPhys.min(m.ullAvailPageFile)) + } + + /// A driver thread: pipelines from `queue`, the biggest that fits in memory first, until it + /// is closed and empty. + fn drain(&self, queue: &BiggestFirst) { + loop { + let started = std::time::Instant::now(); + let Some(c) = queue.pop_fitting(|| self.fits(), |size| self.running.lock().unwrap().push((started, size))) else { return }; + // (from when it was taken: `started` is its mark in `running`) + let t = std::time::Instant::now(); + self.make(&c); + let mut g = self.running.lock().unwrap(); + if let Some(k) = g.iter().position(|r| *r == (started, c.dxil.len())) { + g.swap_remove(k); + } + drop(g); + if t.elapsed().as_secs() >= 60 { + eprintln!(" pipeline of a {} KB DXIL program: {:.0} s in the driver", c.dxil.len() / 1024, t.elapsed().as_secs_f64()); + } + } + } + + /// Where the driver's compiles are, for a line every few seconds (None: nothing to say). + fn status(&self, waiting: usize) -> Option { + let g = self.running.lock().unwrap(); + if g.is_empty() && waiting == 0 { + return None; } + let longest = g.iter().min_by_key(|r| r.0).map_or(String::new(), |r| format!(" (the longest for {:.0} s, {} KB DXIL)", r.0.elapsed().as_secs_f64(), r.1 / 1024)); + Some(format!( + "pipelines: {} made, {} refused, {} in the driver{longest}, {waiting} waiting", + self.made.load(Ordering::Relaxed), + self.refused.load(Ordering::Relaxed), + g.len() + )) } /// The compute pipeline of `c` (made and released). @@ -790,24 +962,12 @@ impl Pipelines { CS: D3D12_SHADER_BYTECODE { pShaderBytecode: c.dxil.as_ptr() as *const _, BytecodeLength: c.dxil.len() }, ..Default::default() }; - { - let mut n = self.running.0.lock().unwrap(); - while *n >= self.most { - n = self.running.1.wait(n).unwrap(); - } - *n += 1; - } let r: windows::core::Result = unsafe { self.dev.CreateComputePipelineState(&desc) }; - *self.running.0.lock().unwrap() -= 1; - self.running.1.notify_one(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - let done = match r { - Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1, - Err(_) => self.refused.fetch_add(1, Ordering::Relaxed) + 1, + match r { + Ok(_) => self.made.fetch_add(1, Ordering::Relaxed), + Err(_) => self.refused.fetch_add(1, Ordering::Relaxed), }; - if done % 25 == 0 { - eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); - } } } @@ -824,6 +984,8 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on None }; let pipelines = pipelines.as_ref(); + // translated compute programs waiting for the driver (at most 2 GB of DXIL held) + let queue: BiggestFirst = BiggestFirst::new(2 << 30); let n = input.len().min(limit); let next = AtomicUsize::new(0); let (done, compiled, cached, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); @@ -842,9 +1004,38 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on recomp::dxc::compile_threads(), if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } ); + if let Some(p) = pipelines { + println!( + "pipelines: {} driver threads{}", + p.threads, + if p.fixed { " (XCL_PIPELINE_THREADS), biggest program first" } else { ", the biggest program that fits in free memory first" } + ); + } + let drivers_done = std::sync::atomic::AtomicBool::new(false); std::thread::scope(|s| { + let (queue, drivers_done) = (&queue, &drivers_done); + let mut drivers = Vec::new(); + if let Some(p) = pipelines { + for _ in 0..p.threads { + drivers.push(s.spawn(move || p.drain(queue))); + } + // the driver says nothing while it compiles: a line every 15 s + s.spawn(move || { + let mut last = std::time::Instant::now(); + while !drivers_done.load(Ordering::Acquire) { + std::thread::sleep(std::time::Duration::from_millis(250)); + if last.elapsed().as_secs() >= 15 { + last = std::time::Instant::now(); + if let Some(line) = p.status(queue.len()) { + eprintln!(" {line} ({:.0} s)", t0.elapsed().as_secs_f64()); + } + } + } + }); + } + let mut workers = Vec::new(); for _ in 0..threads { - s.spawn(|| loop { + workers.push(s.spawn(|| loop { let i = next.fetch_add(1, Ordering::Relaxed); if i >= n { break; @@ -861,8 +1052,8 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) { match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { - if let Some(p) = pipelines { - p.make(&c); + if pipelines.is_some() { + queue.push(c.dxil.len(), c); } compiled.fetch_add(1, Ordering::Relaxed) } @@ -921,8 +1112,22 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if d % 200 == 0 { eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); } - }); + })); + } + for w in workers { + let _ = w.join(); + } + queue.close(); + if let Some(p) = pipelines { + let left = queue.len() + p.running.lock().unwrap().len(); + if left > 0 { + eprintln!(" shaders done ({:.0} s); {left} pipelines left for the driver", t0.elapsed().as_secs_f64()); + } + } + for d in drivers { + let _ = d.join(); } + drivers_done.store(true, Ordering::Release); }); println!( "compiled {}, already cached {}, errors {}, skipped (GS – paired at pipeline creation) {}, time {:.1} s", @@ -1232,6 +1437,90 @@ mod tests { use super::*; use crate::gpu::xbox::tests::{fssm, sample, CODE}; + /// `--pipelines`: the driver gets the biggest program waiting (the earlier of two the same + /// size), and the drained queue ends once closed. + #[test] + fn driver_queue_hands_out_the_biggest_first() { + let q = BiggestFirst::new(usize::MAX); + for (size, name) in [(10, "a"), (300, "b"), (50, "c"), (300, "d"), (1, "e")] { + q.push(size, name); + } + q.close(); + let order: Vec<_> = std::iter::from_fn(|| q.pop()).collect(); + assert_eq!(order, ["b", "d", "c", "a", "e"]); + assert_eq!(q.len(), 0); + } + + /// A push past `max_bytes` waits for a pop; one item bigger than the limit still goes in. + #[test] + fn driver_queue_holds_back_past_its_limit() { + let q = BiggestFirst::new(100); + q.push(500, 0); + std::thread::scope(|s| { + let pushed = s.spawn(|| q.push(60, 1)); + std::thread::sleep(std::time::Duration::from_millis(50)); + assert!(!pushed.is_finished(), "pushed past the limit"); + assert_eq!(q.pop(), Some(0)); + pushed.join().unwrap(); + }); + q.close(); + assert_eq!((q.pop(), q.pop()), (Some(1), None)); + } + + /// A pop waits for a push while the queue is open, and the drivers stop once it is closed. + #[test] + fn driver_queue_waits_until_closed() { + let q = BiggestFirst::new(usize::MAX); + std::thread::scope(|s| { + let got = s.spawn(|| std::iter::from_fn(|| q.pop()).collect::>()); + std::thread::sleep(std::time::Duration::from_millis(20)); + q.push(1, 7); + q.close(); + assert_eq!(got.join().unwrap(), [7]); + }); + } + + /// With a limit, the biggest item that fits is taken and bigger ones stay for later; with + /// none fitting the taker waits and asks again. + #[test] + fn driver_queue_hands_out_the_biggest_that_fits() { + let q = BiggestFirst::new(usize::MAX); + for (size, name) in [(10, "a"), (300, "b"), (50, "c"), (1, "d")] { + q.push(size, name); + } + q.close(); + let taken = std::cell::Cell::new(0); + assert_eq!(q.pop_fitting(|| Some(60), |size| taken.set(size)), Some("c")); + assert_eq!(taken.get(), 50); + assert_eq!(q.pop_fitting(|| Some(usize::MAX), |_| ()), Some("b")); + // nothing fits twice, then room for the smallest only + let mut asked = 0; + let limit = || { + asked += 1; + (asked > 2).then_some(5) + }; + assert_eq!(q.pop_fitting(limit, |_| ()), Some("d")); + assert_eq!(asked, 3); + assert_eq!((q.pop(), q.pop()), (Some("a"), None)); + } + + #[test] + fn driver_compiles_start_while_memory_allows() { + const GB: u64 = 1 << 30; + const MB: usize = 1 << 20; + assert_eq!(driver_memory(1000), 64 << 20); + assert_eq!(driver_memory(MB / 2), 768 << 20); + assert_eq!((driver_memory(MB), driver_memory(25 * MB)), (3 << 29, 3 << 29)); + assert_eq!(driver_fits(&[], 0), Some(usize::MAX), "the first one always"); + // one 1 MB program running holds 2 + 1.5 GB: with 5 GB free another big one may start + assert_eq!(driver_fits(&[MB], 5 * GB), Some(usize::MAX)); + // with 4 GB free, 0.5 GB is left: programs up to a third of a MB + assert_eq!(driver_fits(&[MB], 4 * GB), Some((GB / 2 / 1536) as usize)); + // seven big ones hold 12.5 GB: with 13 GB free only small ones, with 12.5 GB none + assert!(driver_fits(&[25 * MB; 7], 13 * GB).is_some_and(|most| most < MB && most > 100_000)); + assert_eq!(driver_fits(&[25 * MB; 7], 12 * GB + GB / 2), None); + } + #[test] fn aggregates_console_shaders() { let mut a = Agg::default(); diff --git a/crates/xcl/src/tls.rs b/crates/xcl/src/tls.rs index c09e1e2..2e49365 100644 --- a/crates/xcl/src/tls.rs +++ b/crates/xcl/src/tls.rs @@ -54,11 +54,14 @@ const OFF_TEMPLATE: u32 = 0x100; pub struct CarrierOpts { pub entry_point: bool, pub with_import: bool, + /// `IMAGE_TLS_DIRECTORY64.Characteristics`; only valid `IMAGE_SCN_ALIGN_*` + /// bits (20..23, nibble `1..=14`) are preserved. + pub characteristics: u32, } impl Default for CarrierOpts { fn default() -> Self { - CarrierOpts { entry_point: true, with_import: true } + CarrierOpts { entry_point: true, with_import: true, characteristics: 0 } } } @@ -72,10 +75,12 @@ fn put64(b: &mut [u8], o: usize, v: u64) { b[o..o + 8].copy_from_slice(&v.to_le_bytes()); } +const MAX_CARRIER_TEMPLATE: u64 = (u32::MAX as u64 - 0x10000) & !15; + /// TLS block size the carrier must provide for a game template of `total_len` bytes. pub fn carrier_template_size_for(total_len: u64) -> u32 { - let n = total_len.max(16); - (((n + 15) & !15).min(u32::MAX as u64 - 0x10000)) as u32 + let n = total_len.clamp(16, MAX_CARRIER_TEMPLATE); + ((n + 15) & !15) as u32 } pub fn build_carrier_dll(template_size: u32) -> Vec { @@ -84,8 +89,17 @@ pub fn build_carrier_dll(template_size: u32) -> Vec { /// Build a minimal x64 DLL whose TLS block is exactly `template_size` bytes. pub fn build_carrier_dll_with(template_size: u32, opts: CarrierOpts) -> Vec { - let template_size = template_size.max(16); - let data_vsize = OFF_TEMPLATE + template_size; + let align_ch = crate::pe::sanitize_tls_characteristics(opts.characteristics); + let align = crate::pe::tls_alignment_from_characteristics(align_ch); + // Align template start RVA to the requested TLS alignment. Because DLL load + // addresses are 64 KiB aligned, aligning the RVA guarantees StartAddressOfRawData + // meets every valid IMAGE_SCN_ALIGN_* alignment (up to 8192 bytes). + let min_rva = DATA_RVA + OFF_TEMPLATE; + let template_rva = (min_rva + align - 1) & !(align - 1); + let off_template = template_rva - DATA_RVA; + let max_template = (u32::MAX - DATA_RVA - off_template - 0xFFF) & !15; + let template_size = template_size.clamp(16, max_template); + let data_vsize = off_template + template_size; let size_of_image = (DATA_RVA + data_vsize + 0xFFF) & !0xFFF; let mut f = vec![0u8; FILE_ALIGN * 4]; // DOS header @@ -160,11 +174,12 @@ pub fn build_carrier_dll_with(template_size: u32, opts: CarrierOpts) -> Vec // .data: IMAGE_TLS_DIRECTORY64 let d = FILE_ALIGN * 3; let va = |off: u32| CARRIER_BASE + (DATA_RVA + off) as u64; - put64(&mut f, d + OFF_TLS_DIR as usize, va(OFF_TEMPLATE)); - put64(&mut f, d + OFF_TLS_DIR as usize + 8, va(OFF_TEMPLATE + template_size)); + put64(&mut f, d + OFF_TLS_DIR as usize, va(off_template)); + put64(&mut f, d + OFF_TLS_DIR as usize + 8, va(off_template + template_size)); put64(&mut f, d + OFF_TLS_DIR as usize + 16, va(OFF_INDEX)); put64(&mut f, d + OFF_TLS_DIR as usize + 24, va(OFF_CALLBACKS)); - // SizeOfZeroFill = 0, Characteristics = 0 + // SizeOfZeroFill = 0; preserve valid IMAGE_SCN_ALIGN_* bits in Characteristics. + put32(&mut f, d + OFF_TLS_DIR as usize + 36, align_ch); put32(&mut f, d + OFF_INDEX as usize, NO_INDEX); // sentinel: was a slot assigned? if opts.with_import { let desc = d + OFF_IMPORT_DESC as usize; @@ -382,10 +397,14 @@ pub fn on_thread_detach() { } /// Called for every new thread from xcl.exe's TLS callback (DLL_THREAD_ATTACH). +/// +/// Lock order: OS loader lock → `MOVED` → `IMAGES`. `IMAGES.write()` is only held for a +/// bare `Vec::push` (never across `LoadLibraryW` or any loader call), so blocking on +/// `IMAGES.read()` here cannot deadlock and avoids dropping TLS init under contention. pub unsafe fn on_thread_attach() { let teb = current_teb(); exchange_for_new_thread(teb); - let Ok(images) = IMAGES.try_read() else { return }; + let images = IMAGES.read().unwrap_or_else(|e| e.into_inner()); for img in images.iter() { let idx = img.index.load(Ordering::Acquire); if idx != NO_INDEX { @@ -447,26 +466,31 @@ static SEQ: AtomicU32 = AtomicU32::new(0); /// /// * `template`/`template_len` – the image's initialised TLS data (already relocated), /// * `total_len` – template + zero fill, +/// * `characteristics` – raw `IMAGE_TLS_DIRECTORY64.Characteristics` (alignment bits preserved), /// * `index_ptr` – the image's `_tls_index` variable. pub unsafe fn install( img_name: &str, template: usize, template_len: usize, total_len: u64, + characteristics: u32, index_ptr: *mut u32, cache_dir: &Path, ) -> Result { use windows_sys::Win32::System::LibraryLoader::LoadLibraryW; - let img = Arc::new(TlsImage { - name: img_name.to_string(), - template, - template_len, - index: AtomicU32::new(NO_INDEX), - }); - IMAGES.write().map_err(|_| "TLS lock poisoned")?.push(img.clone()); + let align_ch = crate::pe::sanitize_tls_characteristics(characteristics); + let align = crate::pe::tls_alignment_from_characteristics(align_ch); let size = carrier_template_size_for(total_len); - let bytes = build_carrier_dll(size); + if total_len > size as u64 || (template_len as u64) > size as u64 { + return Err(format!( + "TLS block too large for {img_name}: template {template_len} B, total {total_len} B (carrier max {size} B)" + )); + } + let bytes = build_carrier_dll_with( + size, + CarrierOpts { characteristics: align_ch, ..CarrierOpts::default() }, + ); std::fs::create_dir_all(cache_dir).map_err(|e| format!("cache dir: {e}"))?; let safe: String = img_name .chars() @@ -490,13 +514,24 @@ pub unsafe fn install( if index == NO_INDEX { return Err("Windows did not allocate a TLS slot for the carrier (TLS directory ignored)".into()); } + + let img = Arc::new(TlsImage { + name: img_name.to_string(), + template, + template_len, + index: AtomicU32::new(index), + }); + // Publish after LoadLibraryW (never hold IMAGES across OS loader calls) and before + // fill_existing_threads so every thread is covered either by the snapshot below or by + // on_thread_attach(). + IMAGES.write().map_err(|_| "TLS lock poisoned")?.push(img.clone()); if !index_ptr.is_null() { *index_ptr = index; } - img.index.store(index, Ordering::Release); + let n = fill_existing_threads(&img, index); crate::xlog_info!( - "TLS: {img_name}: template {template_len} B, block {size} B, index {index}, threads initialized: {n}" + "TLS: {img_name}: template {template_len} B, block {size} B, align {align} B, index {index}, threads initialized: {n}" ); Ok(index) } @@ -542,6 +577,50 @@ mod tests { assert_eq!(carrier_template_size_for(0), 16); assert_eq!(carrier_template_size_for(17), 32); assert_eq!(carrier_template_size_for(0x1000), 0x1000); + assert_eq!(carrier_template_size_for(MAX_CARRIER_TEMPLATE), MAX_CARRIER_TEMPLATE as u32); + assert_eq!(carrier_template_size_for(u64::MAX - 15), MAX_CARRIER_TEMPLATE as u32); + let max_sz = carrier_template_size_for(u64::MAX); + assert_eq!(max_sz, MAX_CARRIER_TEMPLATE as u32); + assert_eq!(max_sz % 16, 0); + + // Extreme template_size + max alignment must clamp without u32 overflow/wrap. + let bytes = build_carrier_dll_with( + u32::MAX, + CarrierOpts { characteristics: 0x00E0_0000, ..CarrierOpts::default() }, + ); + let pe = Pe::parse(&bytes, Layout::File).unwrap(); + let tls = pe.tls().unwrap().unwrap(); + assert_eq!(tls.characteristics, 0x00E0_0000); + assert_eq!(tls.alignment(), 8192); + let start_rva = pe.va_to_rva(tls.start_raw).unwrap(); + let end_rva = pe.va_to_rva(tls.end_raw).unwrap(); + assert!(start_rva >= DATA_RVA + OFF_TEMPLATE); + assert_eq!(start_rva % 8192, 0); + assert!(end_rva > start_rva); + assert_eq!(tls.template_len(), (end_rva - start_rva) as u64); + assert_eq!(tls.template_len() % 16, 0); + let data_sec = pe.sections.iter().find(|s| s.name == ".data").expect(".data section"); + let data_end = data_sec.va.checked_add(data_sec.vsize).unwrap(); + assert_eq!(data_end, end_rva); + assert!(data_end <= pe.size_of_image); + assert_eq!(pe.size_of_image % pe.section_alignment, 0); + } + + #[test] + fn install_rejects_oversized_requests() { + let dir = std::env::temp_dir().join(format!("xcl_tls_oversize_{}", std::process::id())); + let mut index_var: u32 = 0xDEAD; + let err = unsafe { + install("too_big_total", 0, 64, MAX_CARRIER_TEMPLATE + 1, 0, &mut index_var, &dir) + }; + assert!(err.is_err()); + assert_eq!(index_var, 0xDEAD); + let err = unsafe { install("u64_max_total", 0, 64, u64::MAX, 0, &mut index_var, &dir) }; + assert!(err.is_err()); + assert_eq!(index_var, 0xDEAD); + let err = unsafe { install("template_exceeds_total", 0, 64, 16, 0, &mut index_var, &dir) }; + assert!(err.is_err()); + assert_eq!(index_var, 0xDEAD); } /// Diagnostic: which carrier variants does this Windows build honour? @@ -553,7 +632,7 @@ mod tests { let dir = std::env::temp_dir().join(format!("xcl_tls_probe_{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); for (i, (entry, imp)) in [(false, false), (true, false), (false, true), (true, true)].into_iter().enumerate() { - let bytes = build_carrier_dll_with(0x1000, CarrierOpts { entry_point: entry, with_import: imp }); + let bytes = build_carrier_dll_with(0x1000, CarrierOpts { entry_point: entry, with_import: imp, characteristics: 0 }); let p = dir.join(format!("probe{i}.dll")); std::fs::write(&p, bytes).unwrap(); let h = unsafe { LoadLibraryW(wide(&p.to_string_lossy()).as_ptr()) }; @@ -563,6 +642,61 @@ mod tests { } } + #[test] + fn carrier_preserves_tls_characteristics_and_template_alignment() { + use crate::pe::Reloc; + + let mut cases: Vec<(u32, u32, u32)> = vec![ + (0x0000_0000, 0x0000_0000, 1), // unspecified + (0xFF00_00FF, 0x0000_0000, 1), // reserved bits with nibble 0 + (0x00F0_0000, 0x0000_0000, 1), // invalid 0xF mask cleared + (0xFFFF_FFFF, 0x0000_0000, 1), // invalid 0xF mask + reserved bits cleared + ]; + for nibble in 1..=14u32 { + let ch = nibble << 20; + let align = 1u32 << (nibble - 1); + cases.push((ch, ch, align)); + cases.push((ch | 0xFF00_00FF, ch, align)); // reserved bits stripped + } + + let expected_relocs = vec![ + Reloc { rva: DATA_RVA, kind: IMAGE_REL_BASED_DIR64 }, + Reloc { rva: DATA_RVA + 8, kind: IMAGE_REL_BASED_DIR64 }, + Reloc { rva: DATA_RVA + 16, kind: IMAGE_REL_BASED_DIR64 }, + Reloc { rva: DATA_RVA + 24, kind: IMAGE_REL_BASED_DIR64 }, + ]; + + for (raw_ch, expected_ch, expected_align) in cases { + let bytes = build_carrier_dll_with( + 0x200, + CarrierOpts { characteristics: raw_ch, ..CarrierOpts::default() }, + ); + let pe = Pe::parse(&bytes, Layout::File).unwrap(); + let tls = pe.tls().unwrap().unwrap(); + assert_eq!(tls.characteristics, expected_ch, "raw_ch={raw_ch:#x}"); + assert_eq!(tls.alignment(), expected_align, "raw_ch={raw_ch:#x}"); + assert_eq!(tls.template_len(), 0x200); + let start_rva = pe.va_to_rva(tls.start_raw).unwrap(); + assert!( + start_rva >= DATA_RVA + OFF_TEMPLATE, + "raw_ch={raw_ch:#x}: start_rva {start_rva:#x} < {:#x}", + DATA_RVA + OFF_TEMPLATE + ); + assert_eq!( + start_rva % expected_align, + 0, + "StartAddressOfRawData RVA {start_rva:#x} not aligned to {expected_align}" + ); + assert_eq!(pe.va_to_rva(tls.end_raw), Some(start_rva + 0x200), "raw_ch={raw_ch:#x}"); + let data_sec = pe.sections.iter().find(|s| s.name == ".data").expect(".data section"); + let data_end = data_sec.va.checked_add(data_sec.vsize).unwrap(); + assert!(data_end >= start_rva + 0x200, "raw_ch={raw_ch:#x}"); + assert!(data_end <= pe.size_of_image, "raw_ch={raw_ch:#x}"); + assert_eq!(pe.size_of_image % pe.section_alignment, 0, "raw_ch={raw_ch:#x}"); + assert_eq!(pe.relocations().unwrap(), expected_relocs, "raw_ch={raw_ch:#x}"); + } + } + #[test] fn windows_loads_carrier_and_allocates_full_block_for_all_threads() { use windows_sys::Win32::System::Memory::{GetProcessHeap, HeapValidate}; @@ -575,7 +709,7 @@ mod tests { let mut index_var: u32 = 0xDEAD; let total = 0x2000u64; let idx = unsafe { - install("unit", template.as_ptr() as usize, 64, total, &mut index_var, &dir).unwrap() + install("unit", template.as_ptr() as usize, 64, total, 0, &mut index_var, &dir).unwrap() }; assert_eq!(index_var, idx); unsafe { @@ -602,7 +736,7 @@ mod tests { let dir = std::env::temp_dir().join(format!("xcl_tls_test_noidx_{}", std::process::id())); let template: &'static [u8; 16] = Box::leak(Box::new([0xA5u8; 16])); let idx = unsafe { - install("unit-noidx", template.as_ptr() as usize, 16, 0x1000, std::ptr::null_mut(), &dir).unwrap() + install("unit-noidx", template.as_ptr() as usize, 16, 0x1000, 0, std::ptr::null_mut(), &dir).unwrap() }; assert_ne!(idx, NO_INDEX); unsafe { @@ -611,4 +745,289 @@ mod tests { assert_eq!(std::slice::from_raw_parts(b, 16), &template[..]); } } + + fn is_wine() -> bool { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + unsafe { + GetProcAddress( + GetModuleHandleA(c"ntdll.dll".as_ptr() as *const u8), + c"wine_get_version".as_ptr() as *const u8, + ) + .is_some() + } + } + + #[test] + fn carrier_respects_tls_block_alignment_on_all_threads() { + use std::sync::Barrier; + use windows_sys::Win32::Foundation::FreeLibrary; + use windows_sys::Win32::System::LibraryLoader::{ + LoadLibraryExW, DONT_RESOLVE_DLL_REFERENCES, + }; + let wine = is_wine(); + let dir = std::env::temp_dir().join(format!("xcl_tls_align_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + + for (name, ch, align) in [ + ("align32", 0x0060_0000u32, 32usize), + ("align64", 0x0070_0000u32, 64usize), + ("align128", 0x0080_0000u32, 128usize), + ("align512", 0x00A0_0000u32, 512usize), + ("align4096", 0x00D0_0000u32, 4096usize), + ("align8192", 0x00E0_0000u32, 8192usize), + ] { + // Verify mapped carrier image in memory preserves Characteristics and has an + // aligned StartAddressOfRawData VA after relocation. Load with + // DONT_RESOLVE_DLL_REFERENCES so no permanent static TLS slot is allocated, then + // unload and remove the temporary DLL. + let mapped_tpl_len = align.max(64) as u64; + let raw = build_carrier_dll_with( + mapped_tpl_len as u32, + CarrierOpts { characteristics: ch, ..CarrierOpts::default() }, + ); + let mapped_path = dir.join(format!("mapped_{name}.dll")); + std::fs::write(&mapped_path, &raw).unwrap(); + let h = unsafe { + LoadLibraryExW( + wide(&mapped_path.to_string_lossy()).as_ptr(), + std::ptr::null_mut(), + DONT_RESOLVE_DLL_REFERENCES, + ) + }; + assert!(!h.is_null(), "{name}: LoadLibraryExW failed"); + let pe_file = Pe::parse(&raw, Layout::File).unwrap(); + let mapped_slice = unsafe { + std::slice::from_raw_parts(h as *const u8, pe_file.size_of_image as usize) + }; + let pe_mapped = Pe::parse(mapped_slice, Layout::Mapped).unwrap(); + let tls_mapped = pe_mapped.tls().unwrap().unwrap(); + assert_eq!(tls_mapped.characteristics, ch, "{name}: mapped Characteristics"); + assert_eq!( + (tls_mapped.start_raw as usize) % align, + 0, + "{name}: mapped StartAddressOfRawData {:#x} not {align}-byte aligned", + tls_mapped.start_raw + ); + assert!( + tls_mapped.start_raw >= h as u64, + "{name}: mapped StartAddressOfRawData {:#x} < image base {:#x}", + tls_mapped.start_raw, + h as u64 + ); + assert!( + tls_mapped.end_raw <= h as u64 + pe_file.size_of_image as u64, + "{name}: mapped EndAddressOfRawData {:#x} > image end {:#x}", + tls_mapped.end_raw, + h as u64 + pe_file.size_of_image as u64 + ); + assert_eq!( + tls_mapped.template_len(), + mapped_tpl_len, + "{name}: mapped template_len" + ); + assert_ne!(unsafe { FreeLibrary(h) }, 0, "{name}: FreeLibrary failed"); + let _ = std::fs::remove_file(&mapped_path); + + // Install via tls::install() and verify TLS block initialization and alignment + // on a pre-existing thread (populated by fill_existing_threads()), the calling + // thread, and newly spawned threads (populated by on_thread_attach()). + let tpl_len = align.min(256).max(64); + let mut template = vec![0u8; tpl_len]; + for (i, b) in template.iter_mut().enumerate() { + *b = (i as u8).wrapping_mul(3).wrapping_add(align as u8); + } + let template: &'static [u8] = Box::leak(template.into_boxed_slice()); + + let check_block = move |b: *mut u8, who: &str| unsafe { + assert!(!b.is_null(), "{name} ({who}): null TLS block"); + assert_eq!(std::slice::from_raw_parts(b, template.len()), template); + // Native Windows ntdll honours IMAGE_TLS_DIRECTORY64.Characteristics alignment. + // Wine's ntdll!alloc_thread_tls currently allocates via RtlAllocateHeap(size + 16) + // and ignores Characteristics beyond 16-byte heap alignment. + if !wine { + assert_eq!( + (b as usize) % align, + 0, + "{name} ({who}): TLS block {b:p} not {align}-byte aligned" + ); + } else { + assert_eq!( + (b as usize) % 16, + 0, + "{name} ({who}): TLS block {b:p} not 16-byte aligned" + ); + } + }; + + let pre_ready = Arc::new(Barrier::new(2)); + let post_install = Arc::new(Barrier::new(2)); + let pre_slot = Arc::new(AtomicU32::new(NO_INDEX)); + let pre_thread = { + let pre_ready = pre_ready.clone(); + let post_install = post_install.clone(); + let pre_slot = pre_slot.clone(); + std::thread::spawn(move || { + pre_ready.wait(); + post_install.wait(); + let idx = pre_slot.load(Ordering::Acquire); + assert_ne!(idx, NO_INDEX); + let b = unsafe { tls_block_of(current_teb(), idx) }; + check_block(b, "pre-existing"); + }) + }; + pre_ready.wait(); + + let mut index_var: u32 = NO_INDEX; + let idx = unsafe { + install( + name, + template.as_ptr() as usize, + template.len(), + template.len() as u64, + ch, + &mut index_var, + &dir, + ) + .unwrap() + }; + assert_eq!(index_var, idx); + pre_slot.store(idx, Ordering::Release); + post_install.wait(); + pre_thread.join().unwrap(); + + let main_b = unsafe { tls_block_of(current_teb(), idx) }; + check_block(main_b, "main"); + + let handles: Vec<_> = (0..8) + .map(|t| { + std::thread::spawn(move || unsafe { + on_thread_attach(); + let b = tls_block_of(current_teb(), idx); + check_block(b, &format!("thread {t}")); + }) + }) + .collect(); + for h in handles { + h.join().unwrap(); + } + } + } + + #[test] + fn on_thread_attach_never_skips_init_under_images_write_contention() { + use std::sync::atomic::AtomicBool; + use std::sync::{Barrier, Condvar, Mutex}; + + let dir = std::env::temp_dir().join(format!("xcl_tls_race_{}", std::process::id())); + let template: &'static [u8; 64] = Box::leak(Box::new([0xA5u8; 64])); + let mut base_index: u32 = NO_INDEX; + let base_idx = unsafe { + install("race_base", template.as_ptr() as usize, 64, 64, 0, &mut base_index, &dir).unwrap() + }; + + // 1. Direct write-lock contention: hold IMAGES.write() while newly spawned threads call + // on_thread_attach(). With the old try_read(), they returned immediately with zeroed blocks. + let gate = Arc::new(Barrier::new(5)); + let write_guard = IMAGES.write().unwrap(); + let workers: Vec<_> = (0..4) + .map(|_| { + let g = gate.clone(); + std::thread::spawn(move || unsafe { + // Signal we are about to call on_thread_attach() while write_guard is held. + g.wait(); + on_thread_attach(); + let b = tls_block_of(current_teb(), base_idx); + assert!(!b.is_null()); + assert_eq!(std::slice::from_raw_parts(b, 64), &template[..]); + }) + }) + .collect(); + gate.wait(); + // Keep write_guard held briefly so all 4 workers actually contend on IMAGES.read(). + std::thread::sleep(std::time::Duration::from_millis(15)); + drop(write_guard); + for w in workers { + w.join().unwrap(); + } + + // 2. Concurrent install() + thread spawning stress test: verify every thread sees + // both the base image and every dynamically installed image whose install() completed. + // Keep all spawned workers alive until installer.join() completes so no thread exits + // and unmaps its TEB while fill_existing_threads() walks process threads. + let installed: Arc> = Arc::new( + (0..3u8) + .map(|i| (AtomicU32::new(NO_INDEX), Box::leak(Box::new([i + 1; 32])) as &'static [u8; 32])) + .collect(), + ); + let stop = Arc::new(AtomicBool::new(false)); + let release = Arc::new((Mutex::new(false), Condvar::new())); + let stop_installer = stop.clone(); + let installed_writer = installed.clone(); + let dir_installer = dir.clone(); + let installer = std::thread::spawn(move || { + for (i, (slot, tpl)) in installed_writer.iter().enumerate() { + let mut idx_var = NO_INDEX; + let name = format!("race_dyn_{i}"); + let idx = unsafe { + install(&name, tpl.as_ptr() as usize, 32, 32, 0x0060_0000, &mut idx_var, &dir_installer) + .unwrap() + }; + assert_eq!(idx_var, idx); + slot.store(idx, Ordering::Release); + } + stop_installer.store(true, Ordering::Release); + }); + + let mut workers = Vec::new(); + while (!stop.load(Ordering::Acquire) && workers.len() < 32) || workers.len() < 16 { + let batch_done = Arc::new(Barrier::new(5)); + for _ in 0..4 { + let installed_reader = installed.clone(); + let batch_done = batch_done.clone(); + let release = release.clone(); + let stop_reader = stop.clone(); + workers.push(std::thread::spawn(move || unsafe { + on_thread_attach(); + let b = tls_block_of(current_teb(), base_idx); + assert!(!b.is_null()); + assert_eq!(std::slice::from_raw_parts(b, 64), &template[..]); + for (slot, tpl) in installed_reader.iter() { + let idx = slot.load(Ordering::Acquire); + if idx != NO_INDEX { + let db = tls_block_of(current_teb(), idx); + assert!(!db.is_null()); + assert_eq!(std::slice::from_raw_parts(db, 32), &tpl[..]); + } + } + batch_done.wait(); + let (lock, cvar) = &*release; + let mut done = lock.lock().unwrap(); + while !*done { + done = cvar.wait(done).unwrap(); + } + drop(done); + if stop_reader.load(Ordering::Acquire) { + for (slot, tpl) in installed_reader.iter() { + let idx = slot.load(Ordering::Acquire); + assert_ne!(idx, NO_INDEX); + let db = tls_block_of(current_teb(), idx); + assert!(!db.is_null()); + assert_eq!(std::slice::from_raw_parts(db, 32), &tpl[..]); + } + } + })); + } + batch_done.wait(); + } + let installer_res = installer.join(); + { + let (lock, cvar) = &*release; + *lock.lock().unwrap() = true; + cvar.notify_all(); + } + for w in workers { + w.join().unwrap(); + } + installer_res.unwrap(); + } } diff --git a/scripts/gen_bcpack_bc1_tables.py b/scripts/gen_bcpack_bc1_tables.py new file mode 100644 index 0000000..f23536b --- /dev/null +++ b/scripts/gen_bcpack_bc1_tables.py @@ -0,0 +1,84 @@ +"""Generate crates/xcl/src/hle/bcpack/bc1_fitted.rs from the two BC1 tables bcpack-rs publishes +(Ahmet Dedeler, MIT): the endpoint history a BCPack BC1 stream starts with and the order of +its 256 selector quadrants. Neither is in a stream or in a public specification; bcpack-rs +estimated them from retail streams (see its README for how, and how sure each entry is). + +usage: python scripts/gen_bcpack_bc1_tables.py /data/bc1_window.json /data/bc1_quad_table.json +(https://github.com/Ahmet-Dedeler/bcpack-rs, commit c51ec52)""" +import io, json, os, sys + +window = json.load(io.open(sys.argv[1], encoding='utf-8'))['slots'] +quads = json.load(io.open(sys.argv[2], encoding='utf-8'))['entries'] +OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'crates', 'xcl', 'src', 'hle', 'bcpack', 'bc1_fitted.rs') + +assert len(window) == 256 and len(quads) == 256 +RANGE = [32, 64, 32, 32, 64, 32] +history = [] +for s in window: + if s is None: + history.append(None) + continue + v = s['value'] + assert len(v) == 6 and all(0 <= c < r for c, r in zip(v, RANGE)) + history.append(v) +# a symbol's four selectors: top-left, top-right, bottom-left, bottom-right texel of the quadrant +codes = [None] * 256 +for e in quads: + c = e['codes'] + assert len(c) == 4 and all(0 <= x < 4 for x in c) and codes[e['sym']] is None + codes[e['sym']] = c[0] | c[1] << 2 | c[2] << 4 | c[3] << 6 +assert sorted(codes) == list(range(256)) +unsure_h = [i for i, s in enumerate(window) if s is not None and not s.get('halves_agree', True)] +unsure_q = sorted(e['sym'] for e in quads if not e.get('stable_halves', True)) + +out = io.open(OUT, 'w', encoding='utf-8', newline='\n') +out.write(f'''// Generated by scripts/gen_bcpack_bc1_tables.py from the tables of +// bcpack-rs by Ahmet Dedeler (https://github.com/Ahmet-Dedeler/bcpack-rs, commit c51ec52, +// data/bc1_window.json and data/bc1_quad_table.json), used under its MIT license: +// +// MIT License +// +// Copyright (c) 2026 Ahmet Dedeler +// +// 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 BC1 block rebuild that no stream carries. They were estimated by +// bcpack-rs from retail data (decoded blocks against the next smaller mip level, which is +// stored unpacked); they are constants of the codec, not game content. Being estimates, they +// make the BC1 output of XCL an approximation wherever one of them is wrong: +// * history: {sum(h is not None for h in history)} of the 255 entries that can be read; the `None` ones were never referred to +// in the data of the fit. Fits on two halves of that data differ, by a step or so, in +// {len(unsure_h)} entries ({', '.join(map(str, unsure_h))}). +// * quadrants: all 256. Fits on two halves of the data swap {len(unsure_q)} entries +// ({', '.join(map(str, unsure_q))}; rare mirror pairs). +// A block rebuilt from a history entry carries its error, and so do the blocks that refer to it. + +use super::bc1::Tables; + +pub static TABLES: Tables = Tables {{ + history: [ +''') +for i in range(0, 256, 4): + out.write(' ' + ' '.join('None,' if h is None else 'Some([' + ', '.join(str(c) for c in h) + ']),' for h in history[i:i + 4]) + '\n') +out.write(' ],\n quadrants: [\n') +for i in range(0, 256, 16): + out.write(' ' + ', '.join(str(c) for c in codes[i:i + 16]) + ',\n') +out.write(' ],\n};\n') +out.close() +print('wrote', os.path.normpath(OUT)) diff --git a/scripts/gen_bcpack_tables.py b/scripts/gen_bcpack_tables.py new file mode 100644 index 0000000..01874f7 --- /dev/null +++ b/scripts/gen_bcpack_tables.py @@ -0,0 +1,63 @@ +"""Generate crates/xcl/src/hle/bcpack/rans_tables.rs from Microsoft's silicon-rans sample +(MIT): the per-segment symbol frequencies of the 16 static models, for alphabets of 1 to 8 +bits. The cumulative bases are not stored: base[k + 1] = base[k] + freq[k] * symbols(k), which +this script checks against the sample's own `base_table`, and so are not the reciprocal tables +(`rf`, `rs`, `rn`): the decoder divides, and this script checks that the sample's reciprocal +path gives the same symbol for every slot of every model. + +usage: python scripts/gen_bcpack_tables.py +(https://github.com/microsoft/silicon-rans/blob/main/mdu_minirans.v, commit 2f6827d)""" +import io, os, re, sys + +src = io.open(sys.argv[1], encoding='utf-8').read() +OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'crates', 'xcl', 'src', 'hle', 'bcpack', 'rans_tables.rs') +WIDTHS, MODELS, SEGS = 8, 16, 9 # the sample has a 9-bit alphabet and a 10th segment as well; no BCPack lane is that wide + + +def table(name): + m = re.search(r'assign\s+' + name + r'\s*=\s*\'\{(.*?)\};\s*//\s*end\s+' + name, src, re.S) + rows = [[int(v) for v in r.split(',')] for r in re.findall(r"'\{\s*([0-9,\s]+?)\s*\}", m.group(1))] + assert len(rows) == 9 * 16 and all(len(r) == 10 for r in rows), name + return [rows[w * 16:(w + 1) * 16] for w in range(9)] + + +base, freq, rf, rs, rn = (table(n + '_table') for n in ('base', 'freq', 'rf', 'rs', 'rn')) + + +def symbols(seg): + return 1 if seg < 2 else 1 << (seg - 1) + + +for w in range(WIDTHS): + for q in range(MODELS): + b, f = base[w][q], freq[w][q] + nseg = w + 2 # segment 0 is symbol 0, segment k >= 1 is symbols [2^(k-1), 2^k) + acc = 0 + for k in range(nseg): + assert b[k] == acc and f[k] >= 1, (w, q, k) + acc += f[k] * symbols(k) + assert acc == 65536 and not any(f[nseg:]), (w, q) + # the sample's inverse (comparator chain, then a reciprocal multiply) is a division + for cf in range(65536): + seg = max((k for k in range(1, nseg) if cf >= b[k]), default=0) + steps = ((((cf - b[seg] + rn[w][q][seg]) & 0xFFFF) * rf[w][q][seg]) >> 15) >> rs[w][q][seg] + assert steps == (cf - b[seg]) // f[seg], (w, q, cf) + +out = io.open(OUT, 'w', encoding='utf-8', newline='\n') +out.write('''// Generated by scripts/gen_bcpack_tables.py from Microsoft's silicon-rans sample (mdu_minirans.v, +// https://github.com/microsoft/silicon-rans commit 2f6827d): Copyright (c) Microsoft Corporation, MIT. +// `FREQ[bits - 1][q][segment]`: the frequency of each symbol of a segment, out of 65536. Segment 0 +// is symbol 0, segment k >= 1 is the symbols 2^(k-1) .. 2^k - 1. + +#![allow(clippy::unreadable_literal)] + +''') +out.write(f'pub static FREQ: [[[u16; {SEGS}]; {MODELS}]; {WIDTHS}] = [\n') +for w in range(WIDTHS): + out.write(f' // {w + 1}-bit alphabet\n [\n') + for q in range(MODELS): + out.write(' [' + ', '.join(str(v) for v in freq[w][q][:SEGS]) + '],\n') + out.write(' ],\n') +out.write('];\n') +out.close() +print('wrote', os.path.normpath(OUT)) diff --git a/tests/data/bcpack/.gitattributes b/tests/data/bcpack/.gitattributes new file mode 100644 index 0000000..eb1e525 --- /dev/null +++ b/tests/data/bcpack/.gitattributes @@ -0,0 +1,3 @@ +*.bin binary +*.lanes binary +*.bc1 binary diff --git a/tests/data/bcpack/bc1-1-8.bc1 b/tests/data/bcpack/bc1-1-8.bc1 new file mode 100644 index 0000000..902d3ff --- /dev/null +++ b/tests/data/bcpack/bc1-1-8.bc1 @@ -0,0 +1 @@ +ê·o”¾gý \ No newline at end of file diff --git a/tests/data/bcpack/bc1-1-8.bin b/tests/data/bcpack/bc1-1-8.bin new file mode 100644 index 0000000..9505075 Binary files /dev/null and b/tests/data/bcpack/bc1-1-8.bin differ diff --git a/tests/data/bcpack/bc1-1-8.lanes b/tests/data/bcpack/bc1-1-8.lanes new file mode 100644 index 0000000..ccac41a Binary files /dev/null and b/tests/data/bcpack/bc1-1-8.lanes differ diff --git a/tests/data/bcpack/bc1-16-1.bc1 b/tests/data/bcpack/bc1-16-1.bc1 new file mode 100644 index 0000000..224f45b Binary files /dev/null and b/tests/data/bcpack/bc1-16-1.bc1 differ diff --git a/tests/data/bcpack/bc1-16-1.bin b/tests/data/bcpack/bc1-16-1.bin new file mode 100644 index 0000000..8201430 Binary files /dev/null and b/tests/data/bcpack/bc1-16-1.bin differ diff --git a/tests/data/bcpack/bc1-16-1.lanes b/tests/data/bcpack/bc1-16-1.lanes new file mode 100644 index 0000000..92a74dd Binary files /dev/null and b/tests/data/bcpack/bc1-16-1.lanes differ diff --git a/tests/data/bcpack/bc1-16-9.bc1 b/tests/data/bcpack/bc1-16-9.bc1 new file mode 100644 index 0000000..1f4321f --- /dev/null +++ b/tests/data/bcpack/bc1-16-9.bc1 @@ -0,0 +1 @@ +5Àöåvî'vâäüàŠFjEŠš—GÌB?‘5ªÑfY9>Ág’ËÇ€¶ü¢öz¼ÕûŠâ&Këò!¹èˆð1p(4¦ÿßæ“†¶+ëb”ÞˆâÚ¼ûÃDþ°áöÃ3ŒRÏ}µÉî·)®éˆå= count << 16: + emitted.append(state & 255) + state >>= 8 + counts.append(len(emitted) - start) + whole, remainder = divmod(state, count) + state = (whole << 16) + lo + remainder + mode = 16 | model | (reduction << 6) + size = 4 + len(emitted) + state_bytes = state.to_bytes(4, 'big') + self.continuation = None + if carry and emitted: + # First record ends immediately after the initial state. Its first + # unfulfilled normalisation request starts the continuation header. + self.header = deque(bytes((mode & ~16, 3)) + state_bytes) + self.payload = deque() + self.continuation = (deque(record_header(mode, len(emitted))), + deque(reversed(emitted))) + elif trim: + assert len(symbols) == 1 and not any(emitted) + state_bytes = state_bytes.rstrip(b'\x00') + self.header = deque(record_header(mode, len(state_bytes)) + state_bytes) + self.payload = deque() + counts = [0] + else: + self.header = deque(record_header(mode, size) + state_bytes) + self.payload = deque(reversed(emitted)) + self.counts = deque(reversed(counts)) + self.buffered = False + self.owed = 0 + self.ahead = False + + def wants(self): + return self.header or (self.payload and not self.buffered + and (self.owed or not self.ahead)) + + def tick(self, served, stalled, out): + if self.header: + if served: + out.append(self.header.popleft()) + return + if served: + out.append(self.payload.popleft()) + self.buffered = True + if self.owed: + if self.buffered: + self.owed -= 1 + self.buffered = False + return + if self.counts and not (self.ahead or stalled): + self.owed = self.counts.popleft() + self.ahead = True + if self.buffered and self.owed: + self.buffered = False + self.owed -= 1 + + +def encode(symbols, widths, reductions, model=0, carry=False, trim=False): + lanes = [EncoderLane(*spec, model, carry, trim) for spec in zip(symbols, widths, reductions)] + out = bytearray() + while any(lane.header or lane.counts or lane.owed for lane in lanes): + wanted = [i for i, lane in enumerate(lanes) if lane.wants()] + for i, lane in enumerate(lanes): + lane.tick(i in wanted[:8], i in wanted[8:], out) + if lane.owed and lane.continuation: + lane.header, lane.payload = lane.continuation + lane.continuation = None + if all(lane.ahead for lane in lanes): + for lane in lanes: + lane.ahead = False + assert all(not lane.payload and not lane.buffered for lane in lanes) + return bytes(out) + + +def generate(mode, units, seed, reduced, **options): + widths = WIDTHS[mode] + rng = random.Random(seed) + reductions = [rng.randrange(4) if reduced else 0 for width in widths] + symbols = [[rng.randrange(1 << (width - reduction)) for _ in range(units)] + for width, reduction in zip(widths, reductions)] + if mode == 1: + symbols[1] = [0] * units + path = ROOT / f'bc{mode}-{units}-{seed}' + path.with_suffix('.bin').write_bytes(encode(symbols, widths, reductions, **options)) + path.with_suffix('.lanes').write_bytes(b''.join(map(bytes, symbols))) + return symbols, path + + +def seed_channels(slot): + return [(7 * slot + 13 * k) % (1 << w) for k, w in enumerate(BC1[2:8])] + + +def assemble(symbols): + blocks = [] + raw = bytearray() + for i, (ref, _, *fields) in enumerate(zip(*symbols)): + d = 255 - ref // 2 if ref & 1 else ref // 2 + predictor = ([0] * 6 if d == 0 else + blocks[i-d] if i >= d else seed_channels((i-d) % 256)) + channels = [] + for v, base, w in zip(fields, predictor, BC1[2:8]): + delta = ~(v >> 1) if v & 1 else v >> 1 + channels.append((base + delta) % (1 << w)) + blocks.append(channels) + for r, g, b in (channels[:3], channels[3:]): + raw.extend(struct.pack('> (2 * (2*(y%2) + x%2))) & 3 + indices |= px << (2 * (4*y + x)) + raw.extend(struct.pack('