From 6e06665d79c8473e08fd29b8dcfd38316bf89ed6 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:07 -0700 Subject: [PATCH 01/37] D3D12.X: R9G9B9E5 render targets and UAVs are half floats From ivall/xcl#242 by @mrp1no (head ecdfa5bfa), squashed. --- crates/xcl/src/hle/d3d12x/device_x.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) 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); From c842289579cbfdfaf0fae0f6089f530fc538460c Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:07 -0700 Subject: [PATCH 02/37] Lazy physical pages: a thread that loses the race to commit a page retries From ivall/xcl#244 by @Cattn (head 77905f6b5), squashed. --- crates/xcl/src/hle/kernelx/lazy.rs | 54 ++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) 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); + } + } } From 4bbb90d5efd00dc717d50429e4a01bf0762ce05e Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:07 -0700 Subject: [PATCH 03/37] KernelX: GPU-visible title memory outside the windows is write-watched (retail menu text complete) From ivall/xcl#252 by @jessenic (head 862a0d488), squashed. --- crates/xcl/src/hle/kernelx.rs | 49 +++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 0b8f2a3..920bdad 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -260,6 +260,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 @@ -2002,6 +2017,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 { From 2d2a4ce3d5bb936c98f974b0127ecf86755a7ab6 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:07 -0700 Subject: [PATCH 04/37] =?UTF-8?q?Physical=20pages:=20a=20scatter=20or=20ma?= =?UTF-8?q?p=20home=20of=20n=20pages=20costs=20O(n),=20not=20O(n=C2=B2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From ivall/xcl#254 by @Kalmarv (head 097fab4fa), squashed. --- crates/xcl/src/hle/kernelx.rs | 244 ++++++++++++++++++++++++++++++++-- 1 file changed, 235 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 920bdad..d971829 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -877,7 +877,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() { @@ -890,13 +890,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) @@ -904,13 +928,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); } @@ -1029,7 +1055,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; @@ -1042,12 +1068,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(); @@ -1878,6 +1904,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() }; From 0bc116f8618e6ec9331bfaaa1fbca2b6e35c7475 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:07 -0700 Subject: [PATCH 05/37] Shaders: O(1) LRU shader cache, compile coalescing, and mesh CS caching From ivall/xcl#255 by @RandomGithub12309 (head e336d8214), squashed. --- crates/xcl/src/gpu/recomp/pso.rs | 388 +++++++++++++++++++++++++------ 1 file changed, 320 insertions(+), 68 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 68c7b09..ff0267f 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,18 +500,36 @@ 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 { @@ -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,12 +976,12 @@ 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()); } @@ -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)] From 06c912542c63374d7d309206f2aa9aed1889a879 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:07 -0700 Subject: [PATCH 06/37] =?UTF-8?q?Precompile=20--pipelines:=20driver=20comp?= =?UTF-8?q?iles=20on=20threads=20of=20their=20own,=20the=20=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From ivall/xcl#256 by @1984742628 (head ed5322fb4), squashed. --- crates/xcl/src/shaders.rs | 339 +++++++++++++++++++++++++++++++++++--- 1 file changed, 314 insertions(+), 25 deletions(-) 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(); From 473b632fe6c0294c03396d4a4cfc7531dc0710ff Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:07 -0700 Subject: [PATCH 07/37] XGameRuntime: XCL's own XAsync when the system runtime refuses to initialise From ivall/xcl#235 by @ofc0urse (head 44425d0f9), squashed. --- crates/xcl/src/hle/xgameruntime/api.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) 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(); } From f3dcd226047b268849195f02b71b50ece3279bc1 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:08 -0700 Subject: [PATCH 08/37] Compute groups that are not whole waves: padded where the program can tell From ivall/xcl#245 by @Kalmarv (head 887ae29c2), squashed. --- crates/xcl/src/gpu/recomp/emit.rs | 34 +- crates/xcl/src/gpu/recomp/mod.rs | 39 ++- crates/xcl/src/gpu/recomp/partial_waves.rs | 359 +++++++++++++++++++++ crates/xcl/src/gpu/recomp/pso.rs | 4 +- crates/xcl/src/gpu/recomp/tests.rs | 258 ++++++++++++++- crates/xcl/src/gpu/recomp/upper_lanes.rs | 6 +- 6 files changed, 687 insertions(+), 13 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/partial_waves.rs diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 5a63c3c..adfa5bf 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(), @@ -4024,10 +4028,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 +4242,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 +4256,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 +4291,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", 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 ff0267f..9d02109 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -533,7 +533,7 @@ fn cached_shader_status( } 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 @@ -987,7 +987,7 @@ mod shader_cache_tests { #[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)); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 37f443b..2c2814b 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 @@ -7141,3 +7141,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() From a8ffa013a9eb044cc540ac18c8aaa9f57039076f Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:08 -0700 Subject: [PATCH 09/37] Recompiler: image_sample_b_o / d_o / cd_o / c_o move the offset by the mip they read From ivall/xcl#247 by @Kalmarv (head fd45f2062), squashed. --- crates/xcl/src/gpu/recomp/emit.rs | 32 +++++- crates/xcl/src/gpu/recomp/tests.rs | 150 +++++++++++++++++++++++++++++ 2 files changed, 177 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index adfa5bf..29a0de2 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -2179,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, ""); } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 2c2814b..77c647c 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1953,6 +1953,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. From b82c6c149724508a893a69eaba3eb66d44f5b1ef Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:08 -0700 Subject: [PATCH 10/37] Diagnostics: thread dumps unwind a copy of the stopped thread's stack From ivall/xcl#253 by @Kalmarv (head 5c77a39cf), squashed. --- crates/xcl/src/eh.rs | 106 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 95 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index fca2999..b116a4e 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -556,14 +556,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 +603,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 +637,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 +652,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 +955,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 { From f38044a83fe1a969180b869eb1418f94d1641b41 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:08 -0700 Subject: [PATCH 11/37] XGameRuntime: try_update instead of the deprecated fetch_update From ivall/xcl#251 by @mmmharius (head 8e091d774), squashed. --- crates/xcl/src/hle/xgameruntime/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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))); } } From 5d48cf6efc89663ee49b94226129ea558f770052 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:08 -0700 Subject: [PATCH 12/37] SSE4a on Intel CPUs: MOVNTSS and MOVNTSD emulated From ivall/xcl#234 by @philip-sudowicki (head 099f1abe0), squashed. --- HANDOFF.md | 4 +- crates/xcl/src/eh.rs | 70 ++++++++++++++++++++++ crates/xcl/src/insn.rs | 131 +++++++++++++++++++++++++++++++++++++++-- 3 files changed, 200 insertions(+), 5 deletions(-) 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/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index b116a4e..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 @@ -1055,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/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); + } } From a4e30e3df977ba1624ff734c7dc233153e8822bb Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:08 -0700 Subject: [PATCH 13/37] TLS: preserve Characteristics alignment and fix on_thread_attach contention (#106) From ivall/xcl#196 by @JGonzalezRodriguez (head 49d28fc52), squashed. --- crates/xcl/src/loader.rs | 13 +- crates/xcl/src/pe.rs | 78 +++++++ crates/xcl/src/tls.rs | 463 +++++++++++++++++++++++++++++++++++++-- 3 files changed, 529 insertions(+), 25 deletions(-) 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/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(); + } } From 05d026ddb1b6951db95781776db74863cad36e69 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:08 -0700 Subject: [PATCH 14/37] Recompiler: complete remaining RDNA2 integer CLAMP=1 saturation (#105) From ivall/xcl#202 by @JGonzalezRodriguez (head 6c6b00070), squashed. --- crates/xcl/src/gpu/recomp/emit.rs | 120 +++++-- crates/xcl/src/gpu/recomp/tests.rs | 523 +++++++++++++++++++++++++++++ 2 files changed, 619 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 29a0de2..954d6d4 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -2708,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)), @@ -2929,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))"), @@ -2946,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"), @@ -3031,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(()); } _ => { @@ -3207,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)") }; @@ -3295,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}))"), @@ -3334,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}"), @@ -3344,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})", @@ -3351,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 @@ -3463,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" => { @@ -3480,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"), @@ -5406,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/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 77c647c..c1c5a7d 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -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() { From 6ff7ee8e18268466fa4f848279f82a31cee27edd Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:08 -0700 Subject: [PATCH 15/37] DirectStorage: BCPack entropy stage for all modes, BC1 blocks rebuilt From ivall/xcl#208 by @Kalmarv (head a7ffb2f27), squashed. --- THIRD_PARTY.md | 3 + crates/xcl/src/hle/bcpack/bc1.rs | 94 ++++++ crates/xcl/src/hle/bcpack/bc1_fitted.rs | 125 ++++++++ crates/xcl/src/hle/bcpack/lanes.rs | 350 +++++++++++++++++++++ crates/xcl/src/hle/bcpack/mod.rs | 145 +++++++++ crates/xcl/src/hle/bcpack/rans_tables.rs | 161 ++++++++++ crates/xcl/src/hle/bcpack/tests.rs | 373 +++++++++++++++++++++++ crates/xcl/src/hle/dstorage.rs | 223 ++++++++++++-- crates/xcl/src/hle/mod.rs | 1 + crates/xcl/src/report.rs | 2 +- scripts/gen_bcpack_bc1_tables.py | 84 +++++ scripts/gen_bcpack_tables.py | 63 ++++ tests/data/bcpack/.gitattributes | 3 + tests/data/bcpack/bc1-1-8.bc1 | 1 + tests/data/bcpack/bc1-1-8.bin | Bin 0 -> 61 bytes tests/data/bcpack/bc1-1-8.lanes | Bin 0 -> 12 bytes tests/data/bcpack/bc1-16-1.bc1 | Bin 0 -> 128 bytes tests/data/bcpack/bc1-16-1.bin | Bin 0 -> 194 bytes tests/data/bcpack/bc1-16-1.lanes | Bin 0 -> 192 bytes tests/data/bcpack/bc1-16-9.bc1 | 1 + tests/data/bcpack/bc1-16-9.bin | Bin 0 -> 256 bytes tests/data/bcpack/bc1-16-9.lanes | Bin 0 -> 192 bytes tests/data/bcpack/bc1-2-0.bc1 | 1 + tests/data/bcpack/bc1-2-0.bin | Bin 0 -> 90 bytes tests/data/bcpack/bc1-2-0.lanes | Bin 0 -> 24 bytes tests/data/bcpack/bc1-700-2.bc1 | Bin 0 -> 5600 bytes tests/data/bcpack/bc1-700-2.bin | Bin 0 -> 7082 bytes tests/data/bcpack/bc1-700-2.lanes | Bin 0 -> 8400 bytes tests/data/bcpack/bc1-8192-3.bin | 3 + tests/data/bcpack/bc3-16-1.bin | Bin 0 -> 178 bytes tests/data/bcpack/bc3-16-1.lanes | Bin 0 -> 192 bytes tests/data/bcpack/bc4-16-1.bin | Bin 0 -> 194 bytes tests/data/bcpack/bc4-16-1.lanes | Bin 0 -> 192 bytes tests/data/bcpack/bc5-16-1.bin | Bin 0 -> 178 bytes tests/data/bcpack/bc5-16-1.lanes | Bin 0 -> 192 bytes tests/data/bcpack/bc6-16-1.bin | Bin 0 -> 244 bytes tests/data/bcpack/bc6-16-1.lanes | Bin 0 -> 256 bytes tests/data/bcpack/bc7-16-1.bin | Bin 0 -> 260 bytes tests/data/bcpack/bc7-16-1.lanes | Bin 0 -> 256 bytes tests/data/bcpack/bc7-2-0.bin | Bin 0 -> 121 bytes tests/data/bcpack/bc7-2-0.lanes | Bin 0 -> 32 bytes tests/data/bcpack/bc7-700-2.bin | Bin 0 -> 9735 bytes tests/data/bcpack/bc7-700-2.lanes | Bin 0 -> 11200 bytes tests/data/bcpack/bc7-8192-3.bin | 1 + tests/data/bcpack/generate.py | 186 +++++++++++ 45 files changed, 1791 insertions(+), 29 deletions(-) create mode 100644 crates/xcl/src/hle/bcpack/bc1.rs create mode 100644 crates/xcl/src/hle/bcpack/bc1_fitted.rs create mode 100644 crates/xcl/src/hle/bcpack/lanes.rs create mode 100644 crates/xcl/src/hle/bcpack/mod.rs create mode 100644 crates/xcl/src/hle/bcpack/rans_tables.rs create mode 100644 crates/xcl/src/hle/bcpack/tests.rs create mode 100644 scripts/gen_bcpack_bc1_tables.py create mode 100644 scripts/gen_bcpack_tables.py create mode 100644 tests/data/bcpack/.gitattributes create mode 100644 tests/data/bcpack/bc1-1-8.bc1 create mode 100644 tests/data/bcpack/bc1-1-8.bin create mode 100644 tests/data/bcpack/bc1-1-8.lanes create mode 100644 tests/data/bcpack/bc1-16-1.bc1 create mode 100644 tests/data/bcpack/bc1-16-1.bin create mode 100644 tests/data/bcpack/bc1-16-1.lanes create mode 100644 tests/data/bcpack/bc1-16-9.bc1 create mode 100644 tests/data/bcpack/bc1-16-9.bin create mode 100644 tests/data/bcpack/bc1-16-9.lanes create mode 100644 tests/data/bcpack/bc1-2-0.bc1 create mode 100644 tests/data/bcpack/bc1-2-0.bin create mode 100644 tests/data/bcpack/bc1-2-0.lanes create mode 100644 tests/data/bcpack/bc1-700-2.bc1 create mode 100644 tests/data/bcpack/bc1-700-2.bin create mode 100644 tests/data/bcpack/bc1-700-2.lanes create mode 100644 tests/data/bcpack/bc1-8192-3.bin create mode 100644 tests/data/bcpack/bc3-16-1.bin create mode 100644 tests/data/bcpack/bc3-16-1.lanes create mode 100644 tests/data/bcpack/bc4-16-1.bin create mode 100644 tests/data/bcpack/bc4-16-1.lanes create mode 100644 tests/data/bcpack/bc5-16-1.bin create mode 100644 tests/data/bcpack/bc5-16-1.lanes create mode 100644 tests/data/bcpack/bc6-16-1.bin create mode 100644 tests/data/bcpack/bc6-16-1.lanes create mode 100644 tests/data/bcpack/bc7-16-1.bin create mode 100644 tests/data/bcpack/bc7-16-1.lanes create mode 100644 tests/data/bcpack/bc7-2-0.bin create mode 100644 tests/data/bcpack/bc7-2-0.lanes create mode 100644 tests/data/bcpack/bc7-700-2.bin create mode 100644 tests/data/bcpack/bc7-700-2.lanes create mode 100644 tests/data/bcpack/bc7-8192-3.bin create mode 100644 tests/data/bcpack/generate.py 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/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/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/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/report.rs b/crates/xcl/src/report.rs index 378f4b3..d54f98b 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, 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 0000000000000000000000000000000000000000..95050750104bba3b8a87fbfd3152de5cdbca3c2f GIT binary patch literal 61 vcmWd-fB+_DCNN-RRB%uLA_hhVFeqU-;E*7o;lKn^22#NY1R$BZ?6dp;k8B0> literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-1-8.lanes b/tests/data/bcpack/bc1-1-8.lanes new file mode 100644 index 0000000000000000000000000000000000000000..ccac41a29d0822dd0d55fb83f5815b29ab4fe629 GIT binary patch literal 12 TcmXS6kPzTu;^L^wKFbdP46p)% literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-16-1.bc1 b/tests/data/bcpack/bc1-16-1.bc1 new file mode 100644 index 0000000000000000000000000000000000000000..224f45bab89ccf7a42e2948bb2e6c62c1a878ed2 GIT binary patch literal 128 zcmV-`0Du3M4Bav15RCw#BS>F~lWn0P6J7`eK-$25M+I-iW&)5&Q;)QT5|{yU+|mR&$hzw^+DliQ)`c}}nsSG>@NfN!{2)8Anx iMJ$vTfQEp0<$*FKMi?;wJ;-}P1tP(H2xMnH77wuyQ#X(R literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-16-1.bin b/tests/data/bcpack/bc1-16-1.bin new file mode 100644 index 0000000000000000000000000000000000000000..8201430b29f3438adf986120394b582a5cde33d5 GIT binary patch literal 194 zcmWF#m>_Tg2n2;W`Ptby*%_gLL4W}ajx*dbf4AuC`8$H;!82~~Y+w**Jf(BHnkzuy zf`FhfuP{hCNFlde21oIXSIamY!p=VD=iB!q!s*}XoMRI@`FOo0QaMX`-+wj{niF8k z6RcvKwuoEQN22kG`u*ixT<)h`3g)@;aE3mck+ha0@HPv(LI?v(14GeOqufJmEPRaz hI`UWX5k_u#JWn)S-&tYdk18mGJEbMFy?96OzOsuSo?7SjI`gY7Vtm;OhqOy#V zvdm0O%uEc-jEu|-%uI~T%pe{UGXo0#VPatcDqv;+s$gPf z1S(`?X0>EVRprzy%C#uAWKRvsm7C#^BQZxsecp_~tBp=9!o0FvOcFd|Y`oGu@@x`9 W@*K;~PT&kkTkg8{c5a8^p$!1gBp6@- literal 0 HcmV?d00001 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Ï}µÉî·)®éˆå7iD=wxw-K(vwJ0&2ZFTl1HthlpG>BOy)=&Jd*ld9R+c>KNDrE0*10v9wsAqgXg|UjQ?M2Lr24?m;@*HNeJjUYU z970?IjLh5uT}>pPSBf8^!C-J&uI+{M}?E(d!tY9bCwk9`)(v iF|CMiZAyIi=PAxqC~`9~{{2Gkmo(r0npb7}{sI90K`xa5 literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-2-0.bc1 b/tests/data/bcpack/bc1-2-0.bc1 new file mode 100644 index 0000000..62df471 --- /dev/null +++ b/tests/data/bcpack/bc1-2-0.bc1 @@ -0,0 +1 @@ +º*^)Q¿.u·^’£ãÓ \ No newline at end of file diff --git a/tests/data/bcpack/bc1-2-0.bin b/tests/data/bcpack/bc1-2-0.bin new file mode 100644 index 0000000000000000000000000000000000000000..9583e4063373e40259f736e8622928308c97e60c GIT binary patch literal 90 zcmWd-fB;rj7BFCBWD#HiA_gV~FgVKaW5xytmxk-iC%$A%Fz|qhgLJV10V5EA6wXuq OxYcN-@jZwx5D5S%Kn;}u literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-2-0.lanes b/tests/data/bcpack/bc1-2-0.lanes new file mode 100644 index 0000000000000000000000000000000000000000..7067007a8691df02d8cff548c7a872e808990d60 GIT binary patch literal 24 gcmX?loq<7KQq5M3mqSR9M}Tvlk?P8i##`?J07tzC00000 literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-700-2.bc1 b/tests/data/bcpack/bc1-700-2.bc1 new file mode 100644 index 0000000000000000000000000000000000000000..51f294c7d3e666c76dd20eabee5a4da8b556166d GIT binary patch literal 5600 zcmV<66(8zdb}+&bEZz%xk0UAnXo6M#FB&kiJQnmF7>wisRiVPAp*>EXi4G~He(dA- zMBaU*zxebR&lDhk0rd~jJ z&IIt*L{V*I0yu4D66#;m^Dw4Zq8VmhH6GtYWm!mF&8miZ&Kp z8c*`t8Po61w}EPVK^kOr02gFL=(*h~R5M;+LQOGLK=a((g)m-G1UD;p3MW&w>A>D^ zvs@fJk^h0Xv`~#EwxeKHf;eZ|UgcL$>(o$uBknt93g<*i3*U0NxjoMs7{G6OXoSlO za)Mt^%TTp;HOfcK!T0t-vb+*Y-D@-p$qi)i;!vGMdELXY= zyM5x7*+1LYG!Si@2>H7OawOzME_BYOCU?@4YDfHU1^rh3ZxAabf3Mzs_OII!MTjv% zU~w`QBxD?y2FrkrTUmg%sjaG~4DZ0AOW%<95F-qO`jI@Fr0$b}L`}pMiV0Onitxa&PP=ao=KJ)^#xK-}2u@*Rmn)#z^bMm{yjy*nIMoX2VB8Rh2 z-RcXocCdi{%$o%HC*ST>jakT~B+o?m?2?K`#Df|6KC!GT2kVSX!L(8qj3{ z1#gtg4#5pxxU(EfAV8?weW%mEi}=d6szkdgyj#$A;cYLXk#eRW%*a=nL_<yyas-Yt`G#!>fzNx8RCNWsn-))P+6MuHQPtzi?LJ*2JT*aOQRWMmq}~q(@lIL1G7fj$Ewxjrw^mha(0zfkeh^7mo_l9AaVSXh=Gku@rVh{coCBTW~Qi$!68 z`;n=B?hgN3_cI}Suzjtb)upRVua*bVO>phoK`<(cX5k@PzFiZkTsjhu(Eq$o(jJbl zTczl-F5&AbCY2?D0~xDbS|S%vl>mbuArU~tk{i&(e@kVsF!WVKq#wK%#C;^}BJK}u z6QjfmUB-hdP?%vAl@G$~gs-66J1T*PS0^0`(Q)VXM>8^SKxTV8NmiW1ijQLzfDs~m zls~g9L=81r7|beYFln7;EP^fS6QPb1jyExAIBbtdo8L(uYuR?A%bzU7cv$@M$Y`GU z#KRtOGU#=}+C_$VKdP+wwy5l_?oCOkf&=7zSo0?Jjn76057Rgu*H%uK7jFT#lsBqP zPdDRsoKM(EreQ$UTOokRc1%|+3FgfI6CRj&*P?8j_nq?1YkFrfBd^_<#NVh)E!1wl zQ?*aFC5>|?GehuP`igtKfixRj$Gmr3?^!3cXJWf{4_<^v1V^~*h9|7>uX3UltRDsL zq@WB6ODE_<$|w+q-;Zryeq?oHc>Kl4sO=*>f6ev_ejx}+z_eoh8*=TpsiXWEAwV@o+As3857lD)fN{Rx z3`)hIYPr&DS}KIr=+S@o5%c za+&?5xik<0Tn2`4?@|aqyv$x?uiKtfW3*DO*bYQNEq!Uj;bQM@4n^s~uUqoDWzulx zvVt0F3HFC$PzbwjzgeVUtpyjTwpBpAp=Kj? zyAISh9yfn6GS3=C)jy99 zoJ6E6=K_Lqtigd$=qn|X1&Wl4}XK123wqY9D*J1O7o1olN3I249ij3!_Uc$DON zS6-YZ(@%#+H+irNb5Ad@m1=&P5IY@t4<0b&2{+17SUZj(Aa-H{s#mNWz z9e*Hr6H-o%M;oQU^Q4q2`}fYQKwPuO@~lZ1v)ocPOfKBYkA1>LtohG#&}1C-iGA9J zb4;`k(r3n0diJGH_Tl}d7#^9ryX0~c96N93eO&1~T$nUX+h0vNdA%XbtkX+QVB~E# z5-F}F_Sl|nBOv(WAVzeI|F+hY9m?o(FdaRKZ|nrTlwv03+zO)@MQq{zAWienK^Elp z*k-iwlK5anf$;Iiqb*1tN)KH7)@7LqOozvwhE{BX;26aLLxtbI*xkN-@7{F_bu=?$ zi-YCS9GN1}$M+S528|j~H5B8i9i64E7Gk*Y0KRRtYuJ(2t$go%eGdfK&jMzqVM-Z? zxY|?e6Hm^WfHHC># zmZAYcOaKvcD#}gM_QxdseGaU``GVIU;)zVziWf~Kv$%#Z!7(SO;!bB8;Q5ENQ8;*6 zW3MW|52THZ1$}lCvsAwiqtp*E`>)$8>vfVe9L- z8OFc5*Jp3TK;t9xK8X>hCjm}-{u(2PE8}Xf)q12Roj?%Sy+M{qO4Da{cISvBpK&eb zQ7%RS-_DDSzds8I=9L{9UQb^0@omPXQ}CDr9pYdXOxbPCK0KI=X@OyK!w?|bs29ibtUmqR z?{6IU;;#2hhaZX(Q2^sOiMCj#Pt_J_4H_2~_r4kF-ks5Adf^h=_wgrof*s0nX@~HM za)5TNt-%^+_+^5X?2Wo80IV~?-rco}jOP7u4fShQYA0WUC`8X*N*%%1kzu_S{gG^; zh?#Z62HYhjJ#BSaLVAE`mOcp_9SwkCxRwQW5P?$!_e}qeItEjTy%iJ=>z!3=KmQ9h ze&gOb;6t8@NX}{&7`F7ZBFBGotzQj-LSsoG(N+%;drzf`tnktLQYDs@vT&`-#d|in z{t+>-oT(q}>&GF(I^p;?1-%Lxq1$*2?%J2wYftfW386;SH(wgZtO?QKl()QT!`KX{ zm^ur(F`B3>^{!I!45F(=QKSM3(FBX$fck_R;-IBQicIFt1lFgjVi5=5x12=#Fn?*{ z$a<1P!94@6r-NDX3kk=!$LEb+HaJ4+O3NW}qAjO*flQoFnHAMFZWg3tD=p--4ReWG~OIW)h{ zz@ta^Mn-70bx4BoX59W;K1^W0(~KR*TI48LDcqvE3-%SXsi{Eu<@2ueDO-k`zTy;- z`KV~;9smIflb}jwsnuMQL`u((i)YND%$sVVPxh`V7dTHCaj>l|HQtRd(j_m5p~IEO z%n-*?r~n@u&i}I5??2}h#GkQ$R#3-Qp82!U6RfyPWfaced46|p>nX8hGXVDVMnNn?$T! zk%kQSs~ONu>3((SszD|a>Np-f&JEG)y3&<>eVL+}u)sK}DD0#BaAGjx#Z?oHh7t-iacf1ecom;)Ok zQ_zViUwof<#am=^?`KgIiQYstmf90h^LV_UZn{xJnB6OZp?<77`=rp;I^M{s`yB75 zYogs>OGhfs=&o)aNAfs|cD8}r*G7SHfJ)HTs6QHhNDr7iD>&Z$9d=!~32LUwsbY(t zqPG~!AK}eEL3Abwh1x*|h|GIENZI5CIX)3-V!oo31(6V}*53m}1`q1^v8oSwFL~hw zM6p;Oq*k@e3o^;tBh3mk|9_eSmi%?Zl>}U&3{vZxU-u{`gDwpdw94RrG^spiHcBvF zEPZqps0shtf^>d>b}iphM?`Flu1s*!Rpr;>#Eg^4`6X@bdo_!dnqvU9!osLM7CxT9 z9NO-ujwS8m5iHj#UnG4}nlTTPvpy52kBZfX{2AI2Zs^Ky?8I)G@fJVQU=_+%?A2=+ zcUxbV*kxaLZV@fsQG!yG^YS`F)e%$+WWq(;0rmBA&yw@ zuSumyN~9kmbjMKC-_8X1xsJYlR{lGPHLNAySY| z@XN6r{B#XSu9+=j@Q;xfPq6y%u>d+x05@3P-Rl0r3(;r?zFU_ljVnd+G_G+CT?c;( zBF&9f9rQx0;9{PDJVk7PjI_|K!sE85wmYp*TgSxJw3d&H_Ixt&WMx0}0N(O{QfjxPq(bHP%>J;dj3o~YJQ0sog1Hfp-0uLpQ#W~S50mk2_t$s-{McqX1DA9p6qKlVP15)y zuD)VW4hnCH01Z}y@cRk*0glRAX)GlO2&~U$U_$^-^yy?!r zV0Hmk^jcj=Ow;qG=Yzh)HZugKHT;TFlMJKBk*u;5suek2%J>_bM76p^b~cGt5rn5y zb25r8hRFG|Z%u2HSBq>_^basZF0S=L`uhij=eRpL=&`1UmQ}(5pd2<0_-CmxjCPXf z*<9^4*Yd+5L9~c%HdGFipdK@{sDY^cS2c5A?_7d7RyHJgQ-$@;&$t$j`i=53j6Y2r zn0;p^J%8Xb^Hjy&Ua1h8cQrQ&x5<6dOBl2=v94l}BZVk0GzEi`3YX6Nv4pDXb`_As6O0&k) zDW_?SIvOgpx|Ec&ey^$w2|qWqixwWWh$#bWHGB+IqGrw}i!^KwFh>n6ITt)2by4e^ zOW})xFJJ-g{8{cHijR$4V+Od5aHQn6Fe{i-@U7C?CdLwczFaTbF*T-rkIJ!eVWQ~V z4@$SAHEn_1KVvPttUQZN1t7+}#$xw1vRWPKtp<*9J!mgX>ur22WOLn=+f zULTytp>-iWUwR0NlE=woTP`A^P_K%%wgd$CTQ*o9lV672x9t@f7cKSCxGm9@Fq$-B u4Sc1HV&cF2sVE{Z--^pYvMp+pS*6W}j&E-T<}Zo}hRq)7e6OZKbOdLqQqsKu literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-700-2.bin b/tests/data/bcpack/bc1-700-2.bin new file mode 100644 index 0000000000000000000000000000000000000000..b3470659eaf67b97f40fe98d47f2f0be8133b666 GIT binary patch literal 7082 zcmV;b8&%{mFfcGMFfcH`zqk;%xDdDj0RRC2009622@nAg5CISaIV1y69t1xe0R1{w z$p!5$Ioesvua&<946x)dUpPo}xi?kj>CR&3v5A+7^b^{gg zVt9M&o--NchMfB9R(5mO98}(QMht6If3&=mRn|OOW1pYg^v^i&I$C(9Td@BY6n(Q; zQ%Z=?+ijJ_`t~$MOHi1szPLkOZj8{ppR5%x^j$j%S9(6?`+mHkXyh}ObOi@TVbm)f zJFOr|QsYy)Bgo)_nv3mlUlk5U66&E$zA zkY=(2YRvn5zWpARtar#cE4D_AY2piW(GSTw-m&5PGnnL$xhmWh(o z2Ts#DSzbYI2lb05x1$YxmkmtBS)PO_q!X104V!&Z?}k(cPOF&Eb}%W%mK4x!9KeO2 zZ*z3KL=YuvXok}M3l#7efjy1-VJp0lR=ZlMj=b2CA*9ulq$X4S)4nl5nQ^6&ldeo0 zxrnjZ(ga26Rbm(**_7#FKB!Xw1=sGT#~3X(H+TTN)&U+KFaevezu)RN!2l2$DZH>R z=ZhkL--|U0vQ1r4fQW>ANKvqS&# z+JUlZX0mZ~%Mz!9Ej4uK%XVb(PSVvh-)v1oTH1Z)C(|KSE}HX`qv;X-8ls z4h zMNIToHIwX*Xag3kKiO)rS<#jHIW$nBV4h$}7HxtLGmpI6KAkPiEXNG;VAeF_y5%SF zZYWK`KP>*8ffpghW@k@cGlv_~j;u1qm6vSI73SiC^paZt63RSI53LT!bs@L%364iD zy-43j2HkOU0|SvL2QU2(AO=8`cbRC!JfZmf&!E3Neb`=I1~l`E7!;|vs0{AbiEF0Z z*}4wp=_^f)V+-?pj>>^SS}mygv)dvJ2G- zx66+QDBTqjnqsF%vPnrJR2{9@;ckmP+(Fiv*ny~tc}JT=fjemH9TB6;3q!-RxI>=G zhnECDa65=nnFEZ)_u$bZcI1Fplxme2fWLe(kBY(9{=|H|o7Ix&ib&VhICh1Uq|J%? z+4H<$R}g>%m^+h2-~fA8etvuT*H58`RCjhqu!UjnhqL?Raao2V#PG7FJXnh*Y}mp% zii$jdXQPt#?Zf)rqDF2hVqu*h?sQ#XlUT64gCqSXZ@5^g4{;X#jDb>Um4j1&8H0#5 zoY+o592(`ai4|myNgs%W*rg-fx80{rKR3%8M^VlFq;?4sIvY)(Bg8e( zV&hq<-RiYH711y_(3o+wjStw*zfvoq_rF?&>NqBw>8U_zB2_6YA&EXHE|zDlRdN!0 z9K9GHApt=&7h^r2G9=3Md|PBQ5=5lWu?h_mq~81>7A!9Q4qXV;e!^F7iP}&$jCKP@ zk5!Q`z%~A_|If)glEW+l_(vI;ByT&HcC~V^KgyVr1Gi%t%{F?u}Pt zFEGMVdiMZ>J@vlwgg-fV8y^O{x(LyP{^=EZu6y|{`M##3u&uP6axo*{+MS~N!rUa}Z3&*yiG|NrD?NDAnkxn& zFTsDT^}2X7mTAv?#e91;k~SJIW!jB(YqGYSjzBxA3nbrwE3uej^Y& z98Rvl3g?2j+oQw?5*~hXLO^!!byRlJdLSFMv~X95tUWIHc9FyDaDf8tay2S!S)k;- zAJXS)ZW$qD#3gFsxgU5+4gnwU1_EZTTBy;)DX%;Vg^^-UqSK$k+6-P}Xm$|EJwfcg zT0b`P69Hw8Y(6WTR(YUrry?RJQl4_oQ2DgoY75_RPW2j^DEmtF;ls#E|1HH5KVnAd zvF`RLhE1s{1Uo`vr|2S|qQ5?ruwfsh-Y@dVI_Vpj%V32JkKwoNHl^_7J2P`fGU2@1 zpK;~lHnAbFE?KR|^vWvRsT_)`)7(S|eLg14w$DJh+`X9VG=d`dv6rn$ggzc~8kMeM ziEBST8q{45ROk(#P4e_97Mji`YkSD&P7)b1>uDTKv2)CCfmA~n^Ma}wg1&QW} zw9ZO0zB^L)%K=koyyezYCzx*8W;r!l6KM0(g=h-6Hv})e=V3%rcW69%OeJ)KExd%Gp`(k$P;hR zkVK@~#j5|$)$lw($R?62!n=|gcQL=qTpg;dQ0Fsa^d!7o>@FApB(*U4(zdzAKZr48 zfm*iIvy-Qba75`#vrY6TNaE}^(tm{2uy2YxaQ`GCtp$Gd%=d>18QT*qs+10=!xN`4 zsf!$J^+DoUKS89&Z`jLLjV5?~`In(n!`mMZC&!*yR5v1hNL!(Hn>}=0sa%Y@^5@T} zn4LE#{G3YQmFO^r&?f@ML(bAzlEtL?&ytU=L5%_mk(H0F*Ex)HO{ARHV=vHW#!ra@ z$#3-0{@8|_YrcxQyCi-wgEJ0=is-P`ew^i~fO#Rk)ZayaeT}ze_xoJrDOg$!m@=$a%gUW-A?ELs<+w5^>+5$J-F?epr5Vqb-n_?!;Yu5EO$xJp_ zK^*3{XkXnQOh(~KWqGXkSf0rsp9pX6VmGXfLg8O%$Twxg2w1kH8kOj zN^Kf~w$DfLixfS%lC^6Xoqc8jEV88ZZ}=6^1AVAn4EKpa>L4{pQOw+OnG)m(CH{1CMPH>TV7PJp-ycw(Baz z3kxV7IDEGAJDQhn2wR*u*@Fr*1wobaP_zkSoe~Pi0;4C|OlJS7c86eNKiz-Mpp5-D zEXvL@voGPvNMieX1U0f~i~9M`?0eiO>V9NK_ZR+z!5SbGTZnT6^?tVh3)G6<^VI3V z4@;{vvGld}@ih0KtAX#uz3ix&ezdB(saWkT(Z{fn1yb%F0PpMHWq0*@oM`F&;?Pj@ z(skG+=ksm`>yk1dX?yK9+MS9!!X6xCbxMVKlKN%Q^*McrTJZhNh_c|f#)#(>s+DfMm z)9p)afh!=`yo zS#d^aS?#^mhi7`rE$YoG+m^fEDvfg7%TKw_hLGi-XAx)xw^;RbV=gy~t#`qYwRf}p z?avnPv!+1ZKfnfjgs*`Bv6zE~TfVPB8@!tw4cP{I5fQBegEyhQRO#Lw*~6<8q8-f`qg1 zb;{Zpl7cAo#G0Ko=>>+hM;D#ZwkMmS9)XHkd4!o*4yR+)GF^6{mv5}r-LF|_mYxHf zmFE0`wpIzMlVQtwTuy*=@ci_jk=eLK5y_9QZLD-|4*NF04=;@p^2`^br?J##bDr{4ukhf1X#yi0o#()I-{h4UuLs1V^x$NM2osM~XP!7_Q2VqJdcj3{SL#S-W ztQpWbb%8B8#>fpha~xK1a|ja}JBq2oalsF=s=9BQGGH=9eH+lUfNgF6sqX#Yh%4bx zs-tUs)=ms|t+r`c^N}8Zy-Z0bXDONIq8v7Y&MKFyWy7+5s*_miW4ENxLbBgdY)!Jc zVf9=O$yHzT?B(|)ZQ?tS|NdPLH-xMMKuw4?^x|8x=)?7cNR?STm0qhP7J{klSH_}m z&=%Qg%LJ-KRV)R190jW4Q?GBdmE$S_`WhH+QI20rHH%L*s-f0#sUzQ?O3ujM;WVSt|J`00E%VBTq{YN|EYCqfD7)3equ2tulB`mFX zH=2GHJ#;{ns|iYpH8jSQFKdOtGeEXfV_+PS`G{)FF*=Z-O0O^c@=<5r>O)ET#E&hR zA};=6RKm)uX{0NS!g><;L(C~MSdflgGTx1qC)`i0ee_rus8gIJCDTcQrSK5EBRs^C zU>q*^?SJE)A#Yc3#mXNUW0Q3kS}`4ry7wKKkvW|e%Ab9HcUc?MZZtMv@Prv@BYpFW zNW$B-7qK(Vhz$4{&ujAG70=2@e#C_I6SN{}jNYpI72_l<5ql4a+FuVZ3}4jq!V9~k zV4)3(kWcQZDm<=L0o}}*)wlm^s%2hbO#zFv7bpG|^p)YNNjinpP2c^r$sqsmVg&rR zo9`lM-k3L}`<-w5oa-wyJp`9|`UPLzuD-j+`T4T+=cmJtpR*8=`1w-&m+<#jt4m#? z!Sm-AR!#O8$&&6e#ATB@9k}(|Fz;y^TcPyJ4~I+)s9Dxkbv!-$K4;+ zS4ixh#tZ+Ntg?pJ>m~9$9{Lsg9MR6W>i=0;fErDJ=_Bw!tqm28LrLu|=qY9{tFPzr zII2f?hHTnD4PfQ~vlC!pgc!g23V!8sTtz^ETYBUcQKOH%43fha`C8Dwc8!->1Q?yG+N%U6&$`1K82zA@F3lg z?qGQR(%jsL#(z=ls0?)D+kq%S^b~b%Yv+=*uWg> z?K{`eK#81IpDb{r8Gm*mTs!4rT!1VW`d<)3j?iPKyv4 z`Svl$(t|F><+W|{(bKaFJNmVU*_P(|&>sbdZKBVI7ia6-R=EU%iZ0HhCCQ)Xr+?kb zQvJ;_)9p^BM$OC+ZfE5CijI=#%gls)?}yu9S!<;NEgQUQ{?uc!3FPGXE((<%8FU?$mhgc;)Nz=H(1P#sF{B+ zvz;TJ^PLJ5H_dXavNHG$>YFg`u}WC@6E&~@u34lRu)E%T3iGe(_{jvBP6Q<}=XPir~&byFBqqJ3snwYy*@3La%QH3@xOBcGrfG*!ULs?s57EUtE{9CRAkUb zEeZ{Kqo{nOlBBKt0R;3%qBFAN8$JcTp@4p>66~hC=}*Y}pyD|4y8xf&e#55LH?nRe zC`FzIVNcz@M;;&ol{=jvm(20h2Y#IVLr9VW_8*uxn}ZM>%!N7-zo0Pgnmp;=-Rk~q znFNWwwpqRBuzQsom_k1udTy893mG_pZYm(%jKY@8fDoeV=L_oMmaLT}Qox7=+sTxC zqMvtXy4#~ulR0-ySl{##oQyMAV|< z{Fk!5Nx_b++J_)r5FOQUmS>F@YBYTzT$qgJ_dql5mT20pi;>cnIf7?%G4c7_ig`f8 z0?I2%iK2)n%TaiPT+Srgh(kyHbV7$qJ>mLiAZ+W3P|JqNm4s4-QSpGgq@aaJT(2fw zWSN8>M*30MU;NE7gQ8nm`D#&ahBHJnf)aaJ@q|#klsoRHS5HSfY|TxbCG{g zO}+6)Tdh&?uljx|{%`rEXwCEsOOJg(v*1Xladmv0wF~#i$P%^Jd%OkS(Hr#NE>M0( zdT0du*s+5(dHUB~NOS+GeC5awc+~J9rDu17ZXGdb2Xo&~aBOzzbCPPBGfzsI#bb4% z0Owt5O2~9LI5OMF+Yb&DbDpH>+reY~1{3*4a+_n%|7dLtaWp942@AGF5`?LSaO0vb zYx8f>!c~c>_z4JYP#A6%LMo({e%AwM*>Y`xT-xp{l}T*Z2G|dyWh?ujYo#*bOQJkX z|A0FaYRTuw+j=KtX=eUfuoJSE&#pa$jcYCYo>hd3JN{ z(=TPWQ$x^BV(nzSh;EmH_x)0pW3IQLGl%#OYZeD;V*516L^J(RVFf!q>5-^pJVOJf zU^10Fpp9RnyXv25;iRFJF(O{|$ft}U+e=BMyVG6C#TFHGsMK8L#Vdhrf|&dfTRAM0 zS32c$S<7hYT4=@OBwqTMS;-~+f9eBt=(syRSZA0e#fw+Ufjh*>g^lo+rU+KVU;~3{ zrkLK`lG|?n z%xD{CP{M=XL)=fBxfQdLmDVy3=Rr;%uRn(xXYO4I8dptI>v^!*eC13us@fG2vo31r zOMpXAyQOtcGBtp)O07N}l8dLrNs?u;p>K7p^81YPNLH@eUV=vx2eegeLWr$QgJDLh zA($lJ&_E}MZu3Qq6uO^l@8d+dL9~7D2vK!nL&nm1G$_!aN@L6LLY1DZII1D6LEpC) z?&VD5d#|dVK(veI5hOoPuh$opnOio@2Uk85^8U^`qPBv>W4%4rs+=;%G4VX-h~(zG zNwJP`J7(17dh7Vk{^{jGIwoyAWrnbwIoLfp=>ixAJByNPIBG2>9GN#9trMbH)*3x! zqcS!#9g{oND-mac>IO9t{8Ks|h7L5^=$3rUtGt6{GuhlI>DD2ClFt^DMYJ)FjVYp>wr1^%@Q?D-EDxgXSd(U806yYrjU0^xlI3z4R z*ybm~II+^!D+Mvwj^>%eegb{)Do7HT9uT1kDeCxb&N~GU4p**_D6?s{!9yq16Cj1( zwoN`8$808A(9a`ByLz`C&P^rZDc$Ozn^PpRr#5~``lETkBk?@nO~}Do6sLzFB5u%6 z85?BeA;RQeiQ6~%lkq-|AeWeicq$(N|4V_azy%wMn*APXy749eZL``-_Vpbc$7L#a zS9u)x_VF?HUUgbc8%BBK0%+!Y5B}9>7)D0gf2$YT z3;O%&sGLp6MaUMq;sO01F>zz%`p^|5=ABoW^LP|wh1;r~MH4n{6U(?&&|jDpGUU)7 z5{d?AQLM;?5z(DZp7*pLaXQ3*5N4SMK1L7Jn4VJCggHvuLdXu+M)R;#_ZO@cC*KVa z{3@82%smXr1A6-cTCa-f3q)F~*h!_gUxri23fy{qykcb#)fbAS|0{{#F0N4OQ UbaY?<0ssI2000000000009dupE&u=k literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc1-700-2.lanes b/tests/data/bcpack/bc1-700-2.lanes new file mode 100644 index 0000000000000000000000000000000000000000..6eac67a555fcbc19d88a01cfbd6fa580241059a5 GIT binary patch literal 8400 zcmeI0^_x}o_x5*pckhWabEdmfY6wA6N=Xrh6p&E5L68tB5hNuCkVaZ^Kw3c zln{CL=g)Yq>wA7Y`@Hwr>t1W!ueG+5lDMt;{1H8*#+Q!lzVU^`ZGW(2-}z>(KO4Zb zUe>bKwl;tKx_$GHe>6FEZ}_VzZ#Un%xAFGNKFi+!;`w*qo?6iD)sEP;NQWHHoYXI; z)`X$mz4L)wv9eN1!^E2INc;KX>e91)n-8UC(Qj@ z-|g$s{mKQ(I`?7P^BrW-jv2e>lfPtU&-<9T>799TzgrCS6|;L@xcBRhg?lRR*Z$#X z$*7W&_|=s?vYAKPe>1k;sk7&cf1aItJ^Sc@Mz6+HC8meAw0`$&RFYh6_Td35es4KF zzv21x6~jk2Z*=do6I<&&xW*s&@QD4-mnTR5@_5_I_)puP*pDu}|DbgmaiZ73UYUnG zf7$U>8FJ&M7~&kcfwsRZhgy>qiWer-|oLZt06k=A+ST-f4zME+nWE( z4Ubv)?WzSwQoC2yPoA#~yfa{mpP#>Pd(S0X!mIE6`2K&_XWpxMz1O7WjWa%f)L~EC zEwyV6{Nkr$>!vO}HZx}D{GXbWnnX|EXOXl6G)QSh@)4`E{*XGMSqcdDFsP^vHK#js-xet2Sz4lccX`0=jd&{4? z%vpP>ZdLW47k-nG`DD^pucr3@tt^}G(&M8_rHmQ()aYAxq1-9AcDvO3GrKifHaY5- zU&Y&VN+uCK&#f9;+4)kn7JuGaf8fce4o`1%d{psWsKu_weX7mx_Du%HeZ0_JGJ4&$ z(78wCv>H7cG~FBd$CQLO&p&VQO}{RyD^Gpa(;qv$tnzB{?aHH1_kGoCa9`m6KL4k{ z|ECK08fsIRCGh|&!W`@Q4hYE>Yh$iU(K3nCpbCqoLLfY;DliK(It=(G30sIl@t7c} zzUZuT?0c>%k*)*UCe109*bP^L>O1_6MkMFxsuIL)#Qu0p&Dkt!td1kXFLDf_`$R0BQG#yLavFy2Kt z67(F!@f?|ud>O%lOA0K5EU9TED&h#q0}=%p8Y=rP1@oq$(yoe1GK(Op2N1e0c>t+V zq9BlDqV~8!=LEdc?X8;GaXhgF-LkzOy!G!7AI>kt)1zQ$l z>V(gzs19+0QW%xTaB)CMIMOm=@^vFU0#ATb!`b1&q$oR0jmb;p3p2&kQrHY303px- zWa?mYGDQ_RS3aDWu!Y6n^nRgj9;SrQVN~~#Q0`NgCmNHwH$>; z?DRY;Q6$2dQ8JgVCCdpJl)^{n`Cdk}Zl%SOu_cjUPAC)wM?@8283vsd$492}@iD$g z(>bytXBDNAxd{YWpk#T8Ii-G52^ei*aj||1mKUN@ax|H>Jtr?V$-uPu)P$_$65WW+ zNiw4B{6eQBA(WT`MJ;!;w8L`9$zO)#5?&dQ2OP7D`iXBUus zB8emUs*qw(6vS9k2_j_W@#%JcDUpJEdD#@?=8-9RQQ=rpL^LATfFtrFVT#6W90VK* zQ*qJNX@QggPPRc0LwMM>9Fa$G$&(DnXHb+jb%3=T4`fkN(OlZ_JzZBQ50C(Xg+bZG zI8K65gCH?kgg6%r{D1%rT2={97X*w_Gy~N|fJZri!9-I;87!y=P6jNMkOkkcToZRS z8}VS86JSz+5l6ON0hI~c@OTOg3{R8+$>&Lekp)##5mz-u7ePt>e@3FQDy-rx;hC`E z%32Ud&}TS|2Pm)znxOzvcXUFN2pz-%k_d|Fz^JQvi06woO%b$!ii*lQg5a{I2vL}a znu?FIvX4RngF_(X87?YYDr5)_hhwnE38wB!f`PaOx1}Ts+U5zj#oKRE3{oa^Sa)EER0tAQErIcP z3Gp1kBpliobyn4Uo91AN#jSvI6p8|#9ArY4L`lH`NAV3@@)}UASqInJr2NS(F06KGI^0O zB?~h#4G$QCA~voD`SJk(^?A=`0%iv#;`1U*28GHa0)RP;OY;^83u+*&jTwvxXe>se z1gDrR2?&B_njS^qlE!c%=j%AGv66_hq<}FlNFplg=?I|{tj{>Mq>whuqp&E$672cD zD2ak?xQqr7uxAG@&zUNTVw_JY94>H7@TFz?1cHeeZW*KrX|AB4439!QVQ4hMTLcFN zX)`^5mP}a|2}>d51^(2_z>kVCcr}mD5{!a5iS8UW`JN^utA5U5mkUS z9+Myjhh@b^10n;qASj$oyBvoE(#Vd*Lm)$NGUi*7st}Z?>NH|Wg5`0N31R_^gJ5um z4J=U7cn0NUlt;xNDj&f--Dhb>b4}TCXx9}y*Y*Ji1|?Ya2!>Y(k#J!hQ|WPnjPABB|gnOPWBSelP#hDzpmDcK^Bp+w_mMxLUE(<8D|U_?fvQ$<0>5(TlSxY$k?O*mN#u~xXKAk7TL!ct5e zk3m2Tlo5}UrVHir$pVz;$E24aVs=qDEiIKU#S&0UNnn$UV`PjZBJ60O&}EGzIFd!Q zOhIJ4RL(B+3W6WUX6B@LT#nD;;U`kR!Or{5uvgZP{n34yVSNM1G$B_)v*kb{||8)NACS?MK(A*2x1 zLisYLmqrB;&n?K$isTFE{Peht_*f~`Pl+hZj`j&VNLv^xVPi!&(G=2nJsSwet4W2~ zL~2ZAVu2Q+7AUzM%jT8pRzz$7tjI{+%JOo>l=vhp7j&%5SRkBdKnbZadYqDvS;-|z zq|Jt`bRwNo(+e_Utqj7{b3)NrL3|=_+jcHWG2#3el1nI{Y=Dc+F3k)TmYV6Ho*zv5 zxrri`QJj^N2m@(WhT;~Wc)p$j7H1c#rBa$FIA&~mj*Gjr1zIQ~*^~e)Ot4r58x%)y z0;Y4g6!6(cWZpw12cQ96vBzG@h} z1Y?3Hkfe)R4DjXnwgc0KMVY?N zNDxZ}*L>ACO&AQ;N6k~rAXFVgEn8JkjL;<>*Cp2BINsBIA7TR1@;(yW&ZS6@W@S$Z zHhcgH3X;)mpBF$5R~?GyB{O(V#|8!20Z>lyRZL|;iBX|oc47&O;th)=WF;tk9~LYW z<7FKTgkXZD4G?*q;cWvG4b})=8<3QW0V*nMfZ)kKu7Iwgo%L3qGs?Bsd-znNLF`;?nw<#MY>@}`eYs<=5&z(l% z(moR+mhH^lSv#h4yXTF|b{)pw{hoYp%asH8(v=M#jVNG8&My14Q_T1GXO(rCy1wqz zb4gtey{)Vbe{){BG z<;avzEHlu*-MHuGOIqQi7N>iU)|e;R ziZJQchN*>5^FCT~IW;>@d7GKFsmZ{nkxPF6X|Oox#@%-3J8S>m$v#vxWOAQ7lNU_- zcgUOzw+DZ9`QWwFqx6wy%SZOR@R}U=i+D72dsmBlUmwo5ezFta8$N1SljqkP><@Jv z1Wvg;r|s^&kL?*uP~XR^Y+-GNliLnS3{j}lD$~Px#-XMRgT2jCAMf%DC zHAeB3oidibtM&Z!kA7Vy&k^CF<^SzF_uzA>p!aLg^EULJ%>4PovcAO}}x>;h= zV?8cR-um)n`+fW8@EaQpx?Hz)!Y}M}#wC_7{?`*V;1)loq%KHV%t2ydUyh$ze?$;aIgb}fK?xwvv z_U(#JJl?ok{h9AMHAn6|`~CV0htK`=Lvil}tZ%i*mXyD8WY^@Z-!nRF+}=xCK6KRv zcr8-Ochm=-DlTuO?acbG;Y_JN_EmY?l^3QQY~7&5XF`)U%&mK_e1Go&BfkA@=io)- zizY6f|E9@=FK%vK+FvD#_N(1Z zmaRTj8y&MOb6Vx}%(V30XL_65_0Rk|PyVg3bn2;RJBIyQA;-SR{kB^D1r=Anc<1K0 zX4i>TJw7a)@Lc=ZdDSj@nVmJ(Usc@jlZ!E{Q(sQ2dsNC;@%{Z4?$De%Cx@y0 zj<46P-9Iql*rc&#dweYqm{&e|(6?Y4ERbMnaJ z98 ztM%Gk#NJAa3HZUsZ!eA=Bz$`6pYAn_W-h9$j%pRUHRsWl>MPqdJvKU{%?}$hraxJ` zCcJ>Cmp6D)&ZvyK|9xDTT->E#_0MbLj*M%cpEu0ox|VFc^GY$lo?}-fwC%owFKh5o zi&`0t`+QTcVovLJyLMsgHcc4OZ+DZj$nUNod%UI&QPdxhd@Uw?IBh5-V}r)q|KJ~R%H z{Qic)9E3#uUbhIJy(ifka{h1{bAy6 z-R@6{mb$aMBBSoU_at#~xKH7>{yEEw@ZyH+YQ~x$z3fzT_}h!iTMgwuxH<2{%Qan2 zhvr?~czZx^aWtKKPI-f-aE$E}`RIw>~qxj)eu8NRb= zK*Y+G-yHw8)sXZTcKuC<>nxo0TRjRXY4{`t`qf`}XRvqqI&$&Bd)?;j>K$4B_~?l@ z6L+-vH*@se$B*gdQls^MMl_t;jhD;Er1b2Pm^fmP3r5|4?~RsOqiE*${pS4Kc3aHs zOJhp1%gV3v-P!lAd;FPZ*VjWri!HXd zaLID}@wkca4($IU_Fq-ypWn!TR1{!U>g;vn+PELat$BODAKUWr(TJguv!+dM`TNIh zJG@^$?aPN}o5pr*URLzk#;o1X$~!c@8hvSMx3(oid$g=?w?6})_#pYWS$HdU&e)jA z&6j?C=613t-0X1uw{}%|+Sn7&ckRza7aYH~eAW2xJM<29?%I1e_vPMEHwTn&Op42F5I<|!s+y_A*p0GgU%jmA`PpZKw`^KYNdr=#n+LG5 zRreC3uEv!ji=S-$H1gTdtTCm}8kYTDtjXy7cm8^A%tV{~AjHm@KV3GQrPBvKJ2Ue3 zn2@}`^ksO_$$Do_{&wiUVSm@~4=4v7FW%S}9=xyl z4B>^faQ2;q*%VcOVVy~xKApIE^-5sw`S4#qrTy}tvk|#`#+2%CvjsilkG|jP;?Lzj zX(K-nFQmS3w(a`lz?RPkz~nQLpYa++uP#qdqUYB;#jad6V%3_uvs-RB^7dJsm8(`6 z*~hy7raa(gZ0z*LSW|Cow|WP<)|fm`xN&g%z(*IKj0sh>UwS%pYUSFqdV`L+vv&xy zo4X$@KVH>s(y!B6j62cb{%V%`VE^n!srRxTo#{7cbjAHM@c9$zJ^$)Cu}RtV@5$1b zI$bKc4GsVPab@jSMd)dE2W;IP-ZyP2byIl$u!w%0+IQb-_8D5aBW@->C+)wPgT9<~ zaY?Hgy${u$^)!3NdD!U6?|UDt$Gz;ivU{ToGhY{mf9u)z zmyS*FH}Jyr9V`AVe^q#J*`JfrKaI9)+_Z*t8?pS$wxfGJ?EiD*DiQxEeafFdOm~*t z88`ax5kGfps^py+x@hfBhfjR_`S?yHpUwTdMe7}zXNT8%^)%;H<$;pw;bRk_Tg2spX<`8hc`*%_gL0SZpk-!?zG_3QZquakq99OT*XynOblKcdxK0Rk5U zczJn+LCQf&`DHUW3g^CB#_JGvR;zO2zLU;Q|GZ?5O*qXfJUf+>{hjdVgK;JS50#D6 zSigxjmd(1qoag-MmlIrEovwvG3P@Ue`}Kr~kONu`3_J}+xqDbnxE$zUT%eP}z{p^D RL-5BTh6g1;OE!RP0suRTK#~9e literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc3-16-1.lanes b/tests/data/bcpack/bc3-16-1.lanes new file mode 100644 index 0000000000000000000000000000000000000000..21f601d7437039d16955def9df1091723115036f GIT binary patch literal 192 zcmWlQI}QO+7={1$of+;BgA8LbjnEMzMB!2CtwLuXN~@rfScBdQY{qqxlka@RF#{)z z3L(Zp(w1vDm&V{(V@}rjWPGS)S1nil*}Spw-Fm*~txoG+uf#!Vs!qV@e^oZ8rl1a( z2n7(qfv_NHC<%!$F#}Kl5)d+`IEX1373nCfZoygPITOjUWY~^?e3?+*?3*u|mF1l( Sx_@r*>HIi8znAOc{rUm$u@Gti literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc4-16-1.bin b/tests/data/bcpack/bc4-16-1.bin new file mode 100644 index 0000000000000000000000000000000000000000..1801a52bbe43c260f759735187f97f6d9b4f381b GIT binary patch literal 194 zcmWF#m>_Tg2n2=sg*kzM5egWf;CSI}^P^k8e!ue|Ie5uIo`np5XP^8dTKyqF;DP`z zKPNv(IY=qLOcqDs%tuRjog~jaFQ2&gq_b16SKhgaof}U75}q4SS|-eYFwW$l`o&b! zf)5WDz5XUvrnZc0%K5o3C%ClDc)o^*``XDz0k^J(vlvH&9nfk>;JMO}b0~gK$q5I8 cyy-e@3_x307!KU9O}oLj>OmQUzy_EL0Rp~BkpKVy literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc4-16-1.lanes b/tests/data/bcpack/bc4-16-1.lanes new file mode 100644 index 0000000000000000000000000000000000000000..d10778ce73b3e5b24019d43065a3ef7259392687 GIT binary patch literal 192 zcmYe!V<>X5k_u#JWn)S-&tWfo@V9(JS;6Zm+*gg`r`xVFlTcH!H)64sH#Qa1)91D@ z4?el~7yk#bxhKQJO4!oM*jQQFSs2)unAsTES(({@#;`K5vNJF_Tg2spXW7D{ z-^9w)mhqgQ`*MOy+l=RHoUWaG6mTp2^@ND916mCUJXacW_LQ7(FkoDu!^QwKn}y*( P+6{&WWefrvz-|HnAXGws literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc5-16-1.lanes b/tests/data/bcpack/bc5-16-1.lanes new file mode 100644 index 0000000000000000000000000000000000000000..b99826baf8ef04b5dff6739eca1cd47166971221 GIT binary patch literal 192 zcmWkoZ3+Ql7<|5;UdvjwiFS*$twe}?{EHPviyz>v5H_Tg2spXY7iF5Sd#X;IzofCRklRElBXybS2hrV%Z91eRtGymgg$= z&N@H$e&Gz){-fqQovxh>II&hd{B!Z`28Zc$Bf`?18v;*X&0TN9#=x?_#OX^1`$}E5 zOAFZzS0B<#J9Jqg;X&Cp4h9wpfnyt{7g})#oWC;T#g7UN5rzpTHiR%#By3^GP;}T) R#jxi!D}#Ut1H*Ngp8)1xR7(H= literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc6-16-1.lanes b/tests/data/bcpack/bc6-16-1.lanes new file mode 100644 index 0000000000000000000000000000000000000000..02e458dacd8308cee9aa2605ff3d5f88d1af8d96 GIT binary patch literal 256 zcmWlTEl&eM5QgVtclP$mUVE_j!Ck|Fp{@-j4dfDn!lS^V>TrY*egOtug+`H7@C$G# z1OmZ7pr(?b*n5*n-b|j%Jc?06h_C<~!#!gX3y!tr*on2LQ+3iD&hqi3ckKLh^4DMI zPw$r(H!{EdSiY`OC?i+%PO(und6fe(ARx3R4l}dKU;rw{}o<#e$1UtaQg?1svlMW literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc7-16-1.bin b/tests/data/bcpack/bc7-16-1.bin new file mode 100644 index 0000000000000000000000000000000000000000..43e4a405cff81216b6b3b912ce21f39271615f7e GIT binary patch literal 260 zcmWF#m>_Tg2spXw|!z!;UJ3J+E1TKFeVcVPLop^CJNF0$&^e literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc7-16-1.lanes b/tests/data/bcpack/bc7-16-1.lanes new file mode 100644 index 0000000000000000000000000000000000000000..850bc0d027be6e36941ec475ca428c3a06a28547 GIT binary patch literal 256 zcmWN}FHgfj7=ZEj?!CMB?%G>>{hzK~gCW6ep@hMf5ELE-7Bz<>gzyP4=qWUcWP(qC zLm?0dz5y5{LD5J2+wmAvA=1>=u?Fs1%N0t73W+H}AeAtutH+b4&&#{rm(B0ZRwlKz&gXHN q=afX9RvE8FWpqxJ7)f8QmtXe>8I<{@AW1AFk$bcv=RO~2yg={*Yj@!mv7rMtDUo*!WB9KbXvlDJ|~C2LT1%h;~ozUF!~l*JxR zWFC(Iq@pMW{vJuda|&TZGRkB z#B+uLQ?$7nGQ65!?s@dbQ8+p3tD6X$WwDM6Q7P_;zQX2Pg!pA*Jfa+|VIm)YniWoL zQy!AQsx! z5vQNq3nN4aSH9dVKWCzc zlnAFaDgev0yG+(vgzTG)UV+qA%2z_yN>qvjO`NGVb53sTq(XNdilt~5JP_6{ezN9w zZ&0hWjKfDML)%=h%i%JR?*2&Mn;548PxTQ#_lAU_4qVnOfeVVeZBF`8TAWz&F0w9E z=h?aagV?EYEyW%Jrr9juYw<5Te{NLj0^KBM96`y@-yD*@Gn2B)R&1DSWp%@4oU&1T zMk{lkB-@7j1c}R^P(&XdJfUfoosf`7)PQZP^+)KGg|2DQ!YSjiI6nA@+0jU;Ut;W3!D>H8aCG}50NQLXAD z2v5pAlHP2bie4C>PiA@S$x94zQ8zMdIwpXo%M{_dv|+K3Z4Yjj6IiD;!Y~)qG1-1- zI$7pMjo={9_`M!F1y6b?44cE$3j9#n1Ouy|Kpss55B!$V&R?fkfOWzRTV*e`H2mAU zaN-)PV#N^n7YmMad%^combQ_jzX=(yt&e>1WuF4WeoFBX z&PXxoHZwQJBPRQ>g~`4wdFMzAYJp0;Ep+2|`Au94I-z_zFjBa?x5TxoR1B}yACp@m zzrsGE|F#{xLkRcXJyBRhz7(^R{uZBvOaHP>0Vzn_=npfvU{75Dq6y9xkEgfeBpXb1 zmdv+nEk%*hw6ebL-Te9va^It#o2r&6&|0l(F+QVdWDQ^WZ^<;wfsU%#+~opICwgflZndHtXe6=$VU z%NGYGseXR*RJKy{2HKG>GBcPFEZZxSB!c(N#r@c-6ozl8abDJkpy6rS9}Jl~;@fS> z>}w>xCpBJAD7z4?^iIfDHdv7ojJ=XDCE14@L@#8nROw5ZIwQOg0>Py4c~IiT9%~it z&?N*(Z4Y2yGlo69zL=dA zqb}=8&O{!@XvWJZX>!tD1$+fw2-uQRWaUGDtKTOR!05JAc^4Tlul)B`h1pqv-1P3 zxF0-?HKNn7fGJc{(dawizeD}Q3BS}1t|78`Q^ijr8&$32Xw2TP6PDqw1wLRb$vI*s z5h9vHZ_UffwPN(GN8imL*LL%px5RlFEt&k9^*70f2fq!oiR@kV3WUp&pHBO(lP3HF z)#4M0%zG5cl&BpVx>WIuV)Ppr1B2o@(rWrv?1TMlkX^AqV}r4C{kjiELqf%I^P3J# z89(f0m6ipgiE%5AuFJk}N$Jx~5bk83u_HcR%Q-Pz2VZeGq`3`rxZJTJC*F|{r@Wfz!EwAnXNbVGZ|jval-D|i>Po!Sz5RnL{>><4~t zPCnXNDbl{eT}gNuG`^6(Ht|mZ>D!+nn45{ru~s`Gs17EpenZN(aca1I zeW@pl;`b#9t({B3p|q@uOW%MxUTRDVUUaE)7fg+~FSL(&25^V8dK3 zWz%^rV>v=kPUOAZIGg2oksK)=-1Up)eL6pHW68>sG0kl> zGX0pn8Wl!h;RoIzy;dsg{HOptxJ9aHXN0QB9S{C%J~uV)jCYF7dvz|j;$lu7QTV(} znp-f*rhD3>ej43#Kjv^rNXMv>8tVs+aY@Wi;5Pz8*lFzz3WunX0Qtwkot30gJzxTt z(9Q;_lP7DqzHBJ7xdUM`tZ@#V)HOOaE2B({f*UuGp3?H%LPfxFo6DRwZf~kiLv{yO zFsuYiUV28mhi^AK2^0m3ZFn-_8k~2uBIpa?A=Vl47F^>Y4ukcAFVom_18n3 zJZWZzYJkATqafZ>_TUWWrz~{=WGgJ#?4-wO{pAx~#2G`;Lu^j1aVBIbZ%N#}T%P!t z$Y~;8o0c&yBJi+nnoFo$R?9sxHsqkug#lPTIDA%~H+6ra^=E|CRCg=>uzM@lC44QObvl!K%=&0t; zM5u(;{iZ5_(Rn=SOMSXuy)8yaTE2Fq(X$t9HZ=k+ z$lbz{x;M;t;8c+kLE4|xSwrV4tl%-LX93*9vJ}iqPi<*?8k_`vp>P+V@KV@^A;=r} zO^Q^I0fCf)EwxNkP#RJ>dd*JV6=cBU)Z?I(%xN~sb@k_vt)ZZowg6{hR2V#W0)E{C z6*1D=88eNgTgrgl&a6iKrVe#Po`RaP4t4*9-}CPi5a!OInVzc>hdxE8(9!JAuMlSc z06~4`_>mcD@wmFYb>4i<_QF&wAH%REcMCJ zI`k+ozF*Au^CJQ&3h-R#&I+Y5tA-BLUxzBVG!WIPV?}>G{ew=Ujonal&uzQTVpnSN zj%-K^0eE-^nr#hJjbb#v;xtZJyu#whVW_aquNdeb%dG0NOzlqntc!C9&bkZst9j7Q6D}-q9D;ow zqlrXqwTVqjpJdxOad4g(#eKFHdNM=EkDnZqpp-0X#LoiittE+&iL1P_6$*U@`JE;N z{e5Mp&1Fu)B5&kSI?Vza^LDz}W)$8lu@m?FJ)Na6xy;+yy0OIx*}v!qTe6S%3>j^$ zIN083ZH=O}Xh&#q!O644Dp-AR$L7mP-LlID<8DzYZJTSG3l24X$G*azQbI`RHK}3& z@U#t8uZiU`_=$OSKCvb=)&*+CG{sTv4P~uKXEn+{ee7elllCF|4v1ICM1+f=~whG~s%7Ifo_w}IIb>7o$$Y1tE#h_+AqpUX~* zD}}qE`33j4)^R)(x4@Llz|36?qR3P?^k-jCeRfesD z%Dzv0>{wVPP<_t{eU+=zHx%4I*PxY(eYPV^1zZj>`}3d)<4kO);$!i)s0u;F9q@5^YMDAzJWDFwJDW+ax=*X&s^9He0*k4NKEkX35WKr+Z_s{l&RCin)bYto7Df; zE^G-18>}>U&7^$SV76;C@QgeI6FeBZ(@q!( z?y+Yz4+YMz9i(;%5f3K}sSqY&{PAxp{~}OTyj5D}2wplJ$SzjE10_eLPiAC(tEq-P zs<~ztc=IJ@JEuh%E#XH+OSK0+WNKTsQft8&S35BQ{l{>X!YuXn;yCPO@%hEi?lwUaR%J8#}SmgZ&I5v_&jX&#Mh7>(}qq zAOf|eRChqFzT17%N;SQQ$DeQn{Ms?1fY?PKezTu*0`L zl9~d&bBrl{I2Tu;=2H8r^W|#Fc^##IfbM6gigC(iOas7Yh7ZNU?mdo^XQJ#K?q8~t zvoG{=(?96fRcuc=<}B?J&Mw#J5SEAeYu(`33{?LL&y#rBmo8~F&^;0QP3HCqIDET) zd$|-|8s|};CW@3c13Jo*JEd=eQA0SPz2;SrsuxDMap%@S_D9}TJ0_}@_)$oOuJN6i zdx6%MHC#`|CaElf>I;Ly@PkJP`Dp`6? z7<#j}sw>c8yn<|Pn(ZaPA9`i=GGI(f0LI|^ra~|4Dv1~;*nuYF@=z1UI}y7Mo?S&j zbC`@rOOtlsq_lqLNfW6N-kzboseDnSe*AL}>R%MfWrs3_`C)Y8H!2Ou^pnf+J)O1O zL*V1?VNTAm9~?(S?GN#RAjw%6f$e(cj45VB-lAkZ>?+Go=&BhabWT@p zQqs>YaJ;ImpqG%hAqKk@Xy$ZHNgRt>Jl!h$=9GO7B2Gwy;oEA@5XZ6YGX1HmgU)C6 z__F1Ky-a*#8xFHcKA&-4TJ9G>roPN-WZcNrIlL2RK~E4y#Ua|H%{E1dNos;meVX1{3t|jdD%VS@l;hu7Bp$Y(22Ie2OOlmO`X68FHWs#F zrigEw4SVqEr0;Ep+dH6t`7cqv$iI1EgM_CAm~i5EviJ7d09K8ewYAx|>`-H8kNy>E z?nh~F@Y1k37J#D*y(~?M#OSaqicRjItr=5CN`Q_)}s0lgCbIt2P<;oPP;p=uZWH1v>wTj6XR&rRme!J1|7zg-HZL|DyYv`>tl z*u=CZfq18|VxjUxyv4<~xgTa+MwMGYWZwMx*b6nj$5g#&of(grtoBBZqJY=L9&I4E zjo;dE52hKSmPEP`yB|eJD>0mZcaCCy(_Ww%===j;lI2JE1f>_5DEY}6&}KZZV-Uh` z=}TUjTromHUUSgYMnHmk00iJ)(h|=hv3#e>!gIgu1xE2zDvN2?WBX?HbO+vVO=kU( zo1c?~(4hPJSdR3_Sj$bR{%L0t2p-ak{Qw}0RuVDQ&sC5IJ;)7ciy2m_1D+F4s$@uW zjNKaxhFUI~$4)JIex8La=M8x_*%w@2kg(-KW)O5ys4)c6Oq$cgH+AA@&%Jx*Lw;u) z48Ey<0SlOfkN~kZHjN?ERg?+m7v-%)6>@dy$FMg}9Z%t%+ofHH0FtlN0QO^jwP0!> zjz}OpG+f*bYCCiTx`kn=Sdz{$|ADYGw!fZJ*X>~2K;KNuen+cP$#KkseqBbIcq@Ac zPqxrPmo`QnvaV5)dQ^l*|$D?IZKbFTEmOn~UyW%Th1O$B6&_1PuJq7Q zsfb&K5Tr!OsvSld5;E#V`|~X#MdBebzmM>=rr~hLPDbBv;pj?Y^zQQR!uZcoYZ~#0uJ-cYfDQu1o(8 zntwnGwKk17FAr^SVAgupBuTXwjsPOSGGHVxUCB zhhPIEUn_b)#>+Xsm4vOr*rnhm29D}M8r)eB*;%9rTR$otz7!6}Y>gTGHj&_ZryiTn zK}J^ks_)c7(8JtoELWHAnQCN!#th_pD{9PnJylmgvuf>wo0qw@knBbtv438l0=0zS z&II*zNR`R_i|tR%==C@M88=wD*-vPQFvd&JnG%qUCvg_S5yGJNBkzoErjyY;uK(+65BkGF20@^O+wz{=IUZ7X6IY41YMP}-3I%%&^>g*x zDf@!E&dLw$?&$AyEPKHH_9DWGwJ$1?UcoeG&8+hbC#nv~D(Gzxe z*m(^?Y{->+YF)QZfq^%vd4`m{NyTaTCxQ7AfN5^}yJotLS5P}to0^aeMGzZB3gPTV z3Ey3gwmY}~8T|J5$A8{3iSM5%K77pIGy{;(cnH2Nx(%X!sm?u|FVq2X8t^OKUF9+Z z2dJrPF@k}2?H*v9tO(VtZ_qI@G|xp$63|E|fk4O>XINi#i_#Sk2jrvQZF@29HV=-* zf7XC946ueNsRNd#)t4R!+>XuLY-fl0*8#3O6*lceO$L0)u~(U!s3>T>)*v7Ee~p%r zvk^b6r^Tlq^|1uNn8@ySOH32Nc$3C7kmNUKbV77xGOvrq*tRyHi%W+k1DcD0{U!dp zj*0CRwR|VuU;hk@Y;}Y9iO0@*g}DjR5}(*!U}Cx&w7l08E{Y8aVE4&_ljv@?W3MkT zMC)OQxYcdoBO%ij;;z`#GiL*_O3wHCH#a3Il3^)jLY3Vu&WpRyJIiGmyj@GPw%x@1 zue8i!K|@C)66)R$Ha4l^_3m0(e8Do>9Ib)}nT{O)DSb{Ih&DJ!Kw`FbS+Ek-gZp3U z3%yc^kw_6IA9KIIzX&`@(#H_^k7|jlHXq_d}?b>nSVzZ|U1E z!lTBaH^~Zd(c-YRclUL4{_U&k=YQ|ob*E*@W$@CTKjy?}z8${HtoHy;xLK&;!nG)k z`Q!90(GW(oKcRCV8{zR@c72rntt!mQXN|v+w;w8xLP9-j?dCgeHkP5@mmbK*q7&gP zKucP(PNm&YuBIST2d8n%LuVN|M=Kv|+i-at)>#Mz9qVBsQ~f$zk!zQ9s~oBmWNB!u zA1Q^_NZ_91kjP;ahl1eNd}Um$c^e=O)VK4oD(|Sy1@r?8v2Z)^VwJDjtjzOu!Ul$a|(-~EGeRF z)@#aahYwHTPvc~w_lmYOK1IJ^Yvrg=IZx$`p4LdKh$IwVEEvG%&B82W61V-UnJ@_U z3?lBN>a~QO{SR9*9|V#UY6c`X*JW}c(S81o(S18up7mgfWEx8?XaLFQ^E7MtP#VLn zQ~bQ5AD!Z9tT2Ie2Ro;NL&4s3^4)tB!B*!pJVCW85#k^7Fbz+*^Yx_V$f4PZ)i7_N z#(`VMJ6e)%`~sIvs>U#kMLsnTANVxR7}clO*>HZ&jn%wti1FJvee8BxS)V`$#3VG| zNRE4!aOjcvJhXfnWS=p3h)oHAFXpwWUioe3Xae*@mqnjQ6Evhf?%^&%Qt3Ox?&1!< zl~XE|tYcRDWl8=9gxax$E`AI#a2N>Q!6$Szr5*W8lDsZ*p<<^)zSKTnoQ$%nk9-o= zyBeMcf!P|Da?`kmmz0toe-lOY=T|t6i5HWvC?{gJGGp#}B^s+WN$P&sh%%>0&1M<4 z!V_oUzu@&DU#8BE8kd^aa-J{hc*BS~K+8WT_H5K{GH|rK^{+1xpxInQiPtCeFDtCGO;C_n*^Tzw;VcJa0}x%bi`7h<`uh z>7R}XQo@gxqmNGaX9doW#;Hr5bAqkh>$Ob>lk|+Kj{NNLtm!C{0kh`v+x%QN z-~@g7I|$6TwKQnIBJj;Disw`dl!+-Z%W_sx`H0RPAx%;2B7wwd+^h7;-QoUbVH5xZ zjc?YeiI84V=psDsoqwlkGXZuqPS4X+3X5{p!bR$q=4lKpSYOa%09TVoP^l=vOcDY%OuVIgnIz0jrsiQJzN&ng>tUpgcuP zqjL7U&)M6eg<|_5%qJ0R9{K~Ym`j5qb@Ly19tYSp2H(IjbX24}p5n@EKfW}#PyzIWqI!;UTRIXbVYUT=fng&j S$F1QAg1H)!IMjjtpZph>n%K_( literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc7-700-2.lanes b/tests/data/bcpack/bc7-700-2.lanes new file mode 100644 index 0000000000000000000000000000000000000000..e16eece098525b8d9b1a95ce598a7db8ff605417 GIT binary patch literal 11200 zcmW++bwCu|7oDB%+3ujbyF&z&5CKI(8bOd0B&2NpP*hN{<5TSJ?k-F$?C!usMSt`C z{@Gn-cHVpUoOAE;&btB-q!0o}1qee^EG_^jmZTX3!7uIf`W| zmcvK{=Lmu!P>upg0EGks9D`sSLj{aLKv4(=fDj1qW8pA@0JH#u`OgqRasa^!a2n%K|h)3pkv{8IB@B45ev+WLX3PXp|q6Msbvb0fxg7 zer^ijK#pW_7T`yvaae$GG)usI&;TW%S(M;ljsS6zAPE{oX&58~7>nTo2%;&JK6(AU+5RptBh5$SYBrD*V;p2e?0+b&X zrZ@nGFo;D3C{5A`KRiOC1j)b*Op^ozaX7)@7z0B9ilVdt25^q&niQZAKQBw52#JFX zBVY*#2T+E@X_SExUP3g-!^WZo5Op!c@|1p5E{2u^MngAea z4&YEeqj*hle7q=y{g*%(%IgnD`Q+g!1VwlrP!s@J6v1iWzf=-X91Vdi0`tiNb09$g zD9B?=@Ko_E!WczBD2xFlFMkT;17J`B07#hEImb|Z?t(mL|6M0wK5i037?k0m;pc(` zFby+2q#%NVB+O?c&GHE$pdcE6a0(+C9$bVc2ZjiS1t1211SkXW`hXFf2ZS#R9M2Ao zFa*nxAb>M0$Y%#iK^RXyN+TezZ$3RRzEsczhR_&_@z4ENB?KHw5(1V)SOH4mERG9E zfTxM(V20O;fB|7Xbd+QG(gC6Xz~>dttA@fMelh?<5k`PRyeLp!%m{>H1PSsGKop1Y z+9UuF<7)*WAb5RK1j9fG27@dJ^T^VC8RG$hNRnXqWaCJ_azQA+5`JkQ|B>gF0scQE zh~p4KpdbPO5MLSq9yuN<9w-LqAU?}zo;Qw#IGPmj<%q@j5OIj*A;I|a1>n4R1^=a% zfG;n9w%Oi`ck7&04;D<(l^1{e^#YeHxmlKUiSr`@)7kZ!spnVrF=_0#sa;d3 z%G_%}f1Hm}cAB)u*Sk*|yZKM^`@*#X!1eN-o3Cedg5y{`ep_*|^$>m!5C9`_GXxO~B;TSHy3$z$gIThghr zaY`GqxwSmU!fo7(4G|fm{1*K9`f}sUs8>(eTNhF*+po7g>D#>jhA{SE$-RvwP2o$b zEwCR@E@HAd;oQ*q*H^~C@5y6>QyctV7H%GCwMgy!&wXd7++*1{>%Wzlhgt8>F5dNd z_l%)Wo9&s%HFecxbyx1s3R@z0@Fsl8TKA|+hs2kEpLDSM`@UO|*tq@d%Jwm@uip%b z%q%Q)S14~-Tzs3j>}Vg5?zk3}KEI!vclwB;9N*2-(Hmq@>m)68AvL2PsxB?;5vGo| z-p+j`?)g=mSohJb?wwhA4DX!csm#RmzR%Q z-YZ^oZlO0+V%@;U%jd3Y8ql#wJ$3nw)tg_rjC8c%vZ%m1JG?(SC=OlN+3 z-mBL4YYtsn2Y1(g&3T&dbtdZkk+`!f(NotK>lb*`O>RRKYnVfAr|*woyD1Nyd{zKI7Ed0YJ@;8!#_4g|wamdq*O$KC-c)paaNCmue(x@Y9qwgwTf~5A zu%m#?OGkF>va#tdzua7XO&hnhdf~l}`cboyZVeb1eYyLv`Q3FUX0PL~joxtQPyN;&blM2z zih1>WRS#RN_uonx;8s*!`eebDEOpZAgX^yB`jwWouxm@kKSeLzm-eimwPCN|*`4L| zY5#U_2crsRi|w@GqPX&qVl(s|Eauu zxcHu>MPS^{GglrB244;6y<^*%GPlChzP5L2{hI^r*Y203d%VIn&F*mMeH9V4IO|#N z8DYSon!Ssz<(I$!NDWqM`~7m@Ra ztPlCNvv>@=eeLbDw-?djk#Io-#4Kl*OjI&zn9SjWzf@>w>qv(kc8362HO*zNMA z<}MR%Y%aRx6YC}GiTpVGOpkl{k!{i~t?vQuhfB(@$M>;Do%L_3`P0<8drl2?-q}Wy znE_LAY>auusc|LYzwSt{+1E}9Y@HjK5+@9ZdHuH!oHgQl$$;`@tM<>cJ?<1T)@9YX zzt0z%@7`tq!)MR$Gv^&oj<6VyX7yABuh_Q-+7uV!usIjGZZhrKl{q^$E$!~?d}R@^ z(cB<>I;78@EL$tWwIH%b9CYHX&L+O)ZW@4pF?lRxqENit7Za!^lu=Hu^o_*rspJCSaiD&mi zMK>OI<0V!DmhXCP9XFE^iE3GV%AZYcDVOz29-m z^s7FtVuB%Rtj74og09z-9GCXFccQyC7O%N_Ys!3J*3Z!qVc84Euid@b}94oluvyjHcrrzHIIMdk6g^LAG*z6%J?`Kkk$f!nWz4$T{a#vFWnFl1+I-@SxW zsM+XAtIj^xIlkWg+49Tp8TV6SgA&I({9uz0WC==qasg>VR%OQeCV4yvC5_CschM?)LAF`1=b+8FJpC?-Vbt z?R`GkvDLU}NA)TnGW&A5>#sI^_nK5m?6x?2eCWrutroL<=3CHb3*RL7t9$Ho$i_2g z=9{Hff4_7MXi?D#T;{nCyZRiR85q87y+jeaU})9Wq%;X?fH)M}hg73=Brl+HpgzYgL zc%+v{t_+XVufIGw`%8VR(Wj>qFN8fG+S9zRWaGBKcaqAKZ3SLeUq5Ar*f}C!7bop5 zSTJWwOS>2FY}wC~ezSjP`3vq>wtg|XBJ;N2us?3gxNQqF`T(Ueuj{|}H;sJeWhI-F z{!(|bC*WYa;Kq|%MaN7!g4(NZr}jpEx%c(rqet`qVzYyy2S#sN)Ln)7ES~-iyC7=4 zSU)Z7(wwVK7u|OT`dlC9VA|!s{#<+SFATE!Tl@WP?hU`A>$h+C(>To#`TN`6I@9q2 z*Js1tC)QkM^%FL>F+1+LoyeF0Z!7YQvg=c|>f-Pi!Nf7!FLZo~@8dIbcXmbdsJ{mS zymuAOnHpFaHO?vXHPzo_o!!^N7GZ}%3VJf1-JiLv-#vYejegovb(`{I@6V>$GbTJZ z`7(E_B24w|ZqVf9vh(ZvTRB(!j%zRVoj58--+k-K#oizzmnrUE*N;b@lkNO4ewp>K zT1R0+=;D>zxg;*PIy(##8s<~4_0X$>8CFmKm|>-f)lebpLa&DqYc1@p*< zcdaM-c9yPH$Im$tdEtcSlBIjv`m5)F$+Hh6HXm$>o&c;la3Oih>20npbMKGO^PjM; z7@Mw@6A8UrQ-fl1tuCDs{1V1J%(?{DiH~ysY}$JKX85~4hK%#U*+9UgF5+oKqWQ*g z%I)>;Go`}9ktZ8_eRU+l_7E6 z8~3If-Ga)l+qS&1hqV^t`?QR!uRH7cEVcKGLWPda&gB->?j)OJ}v1`(zuDyp>FBxo>zum;?rHS<7foC74YcHK&OY^AgX4A|EhE;t+4tj{_BaNv+dC&%2}#|mR)(+`ICiBWD03hVy% zz4%1m9Bx-~i|6pA-LH-gn>CN?*S5k>LjrBYnbkVW+$!p>-|isdVg2kAJ(94_k4ugp zIb{D^wMJ18x6W<%m)S8&bEENvGX!rdJhHaZlRbsW7em6Gsty79Sec?dqRC;mhQ+r;*6;u?TTEuu_d=<&?1YXWnG~KE9JI=`U`D?oARcp z4d<*JYPKBHZa>_fW<*R)Px#pKP-S)rky?%COa^Oq5 z=ckvQS-r5|p@#kAKU{BaFfAT`bKg?D$9-O3dP7doQU9SgfTb&kYNdtrN4ZBySv%7$NBC|LYBgIIT{Ep^4f7s?U4 ze+`^m?ABUv()hIRkdv>@E*x>rXjuB~)@J4FRT~0Iic20StX-G9m~G*;_N7g+z@1MS2kJ`7Vb|>BMysH(n32MeVSYv7 z9wwE}IeIcIr4n^=%h#pl#W9Wro*@+j488(Hnc%C;A^iI`B+>r9<+kPNm_kYAxF#tY zLiDsxaCudJk;9;ohH&YXH{-WZIqEHq^1gqsK-Yqde(&1)yl<X@v$f46t!aD6h^oi!`xu3Umm`#VCzZ z?q6Og9T=bQ=0*+l3$LUBWr?f1X~p2oVnt4ARE)nU6L3z+O&aN7%4SyDkfCLciXi*E ze$@qygR?UO`!njGnjlN_3SpQuGbS@5*Fsz*% zSjv5^K+E#vVK#BzFN+q}9o*Zzd3wcOjfVMt?cE{6;vEE8)7=2EqZX&S|d z!Xa@Am1%1KKz({Y_flUUznYZBM#4pz<>Fr_wgN0Ftt?;%_n6wCn))(<#ILB(HMzJh zAQeKXxNRaF%h)`L{QU|Cd>AhV_a@Xv}98*D5AzADnm(M9;MSSx*8ewc{hCl9KHp;Qkm1-EJ&ejKnd5sE-32g|7Dy;DDSDaNkJeUe9a0~J&tcOGL z@nPbMG~3Gl*;*!pky!=?2U?FVv&a;?`2*p_QI6>u)l7t|lOZZ1qMyz<)8By(uJcsJ zs6%P9dVeG}Wl&{t-(o-~bW;_F*VVXG;qfWq?);O{^>$%W585QH#-`rbwU1M!ahf=T zh^;MUvO~C`ftB@6R>f}7U}&^?WCf-PL_8hYBJUwpUSTBKmuagZ754E zOX6|`cuBdj49RdcF?BbJWYtyPnZd>$)k6wB?a;!6+|rzq`auQWmgPAOc_wA>h@x1F zoI2$oU*ljb$3+!qPI-8b^l=S~!UX|tjhQ2={0K`n!M3kaYSqAmvSj;|0jYU<$eqEh zb3F>fQtI-YGBcyFBn$syGkeRrNHEEzmdP$R9pE)!0O`uPYAKl@B_L?{0AabC5${8i zB0{N?sbpFLl+prR4nYzKG-yZ+G)O=NK;nQ-Ea&}M-WruF6-ot+s7Ra;^MsQU+^87%IahG7+IQ$dr18R;tm-6k>ydl*-gNAe5qFm6-R` zSv3m@v>Zg}4Y*XK)+;!*41^7+1Scf?B5|!yh4QX51IZDoLa9bTp%`FP5=M?`BrvCy z>nMR-FVpGOS`1WbXbq;4ZW+W8mL403s2gV!2*{YC)-5rZDIL zEg(~30<~74P{|ky6X`(}WT0RvgbE=UMlc#!h8VC{KZkQ$dheL>sgk0MHO3ilR z&dkir!<_fHDK`8et4zFr_@bIR}HCG42G)I3qWeFX$xXaL@uKEh#VB&KdL(tNl1@%v>!n z@{#zFR)m&y&@tBhA)CZjM4-w5mB2s0~Z6mj*m)LD6>u#bfi?BVL7Hki2kTRC8QU7#su6yV^GvSOvN#?jZv zLrA!&Nl#ekYHO^=v;r$zg}uLj|w z-o*+lrI@re^*8qQq(HTaRe()^r_|4&H8m)m)XrWe*3O_3BRLCucRve(qg^0>tmkU# z=8J%)?sjgdnBoGA%xs;FK`~*+}jfJa)+&~AQ5_@N{mAShZbGh>KM^=(oEJ^F!CLV~Z-fQ;X>KOP#9+-O}xuGN!K8 zYe>VOUsL^x-lVJbWP+FBf(vz488WZa9&;oI%3T%)bq8rJo7^hckB4QlDR zQ&e4DyKBd4Qe5c(zBqwSyz|!9I9kn>(GP8Ewm~|Wb z&rRHR_V1T|YuBw)x?dP^Q~I8ry*;N_xiMm5LBxstkmg0gCnxt+eeCL(OI5z_Y3DH=u%c+yi+js`phAdI-=jLXULS}a|b%Ub^Ca=V&3=-@2*0(I-HB1 z7d6F&wXP%r&HLq@VYkJ6+q*XWryp{K*$=7TG>&v?CtnD^e(5!m zo9Far&gf}vT`Q7im!9h1HuO%9ty#su_MD4-qfV4>jx5{RF#gQS(vuNvPtn>D18>jy z5hdplXC*97knF%yx+C6G4$tWkIQFH1oW}I&=jw~ zy4oZwSDR4<*E*H0n;Kra;D!Nw#hz{WI`s6UKb@I{ldG`CK z1VM`cK)wx@k=&Ll)kiNW%cp5_tjnVydU*pB-VZf)i)s;TSe{Fx@HuS=_e%qxV z)?dvW!L%NGWuJJNv>X}vVWEAWd9`o+SN~(O*7fF#F9g5rRY+9T zoyoJhA8dF0)p$um+)HjGW^d^4@oMr5&oG;>^8=rZ9bvV;Bx&@Cr$=s#TXvpmc{%^k zn>E9IF04P%*KcqP+JG{}JKF13QkSESZQp&vLLV4&5!>qfC-L6z(#xHLuJ^HScyNCh zGd;|Aj0HL){?~#(Ti;v9`GnEHu5-&K9s9XksM&m}ywj`Y@|y0PJr+kTKippSY5K;f zIe~9alD|a{E-@W<^YriBr>xnvqCZMMoxT8n*E{fNz_5&Ut!Ldz!mrCtW|5Uw=BJo4 zanVygAFF(&RX!f%Z*XN3#XHnl9?j*|UH`1CL!a-SlY76(L2-M^z|&j9A3pZ5^k1=h zSZ3%yn}5da6yy5zSUd6U{#~zPH@`dG(xkoV)7@b)X7yNwKAm~%eN4Xt!@}Hq=`%r>gJ=0~XjoyjIl5My+bfpU`wLKNy|(S^#~Y+-{$> zk`qqu=xzN+h%@?)VeXSoiT#%x3Hy;&*`s?iv8AukQ{VpS#gnd!D<3x;l#i^oJ)0~% za=EnO@WoKGhQrVM9(laPR({aw{e#HGp&l-)R+ZG9O%v&Boo@V`Ci?RmG47uH)IROI zATQRaR6^Kx!TRm7eVZB=yNp?sLN9J@l=&AGMtj`dwXW#jHmJ&BKl zJJkhSA6;i-6S%S?%$n>BfzGeWt+KZ(vOKk|@3z9LKf25gzx{sWlxcJ5$B&M#nVmQ1 z{n#<&nn$xXp#P8=&fXK_bF)9YAQC+ytoPF1tB2?Bx0t$Z3(KQb* z7@m6Wz>$N$Y^7Zb-aL;c2h*;5y6(>|`1;xX(Z5Hh0qrA~yk=K@2>KeipxrU)^M%vv zn@eRqx=(jicbIe+cz4kTUD6kP+F~!Kp)W=$rX3nNXKCL2%BQvmf9UEb7G7^V{NTc< z_aA!aF|i(Nd#Zo?yy?9kIn!}*@1N!uixOtVzcluKwWjk>^!SJA^V?mQgv@Z-cl5D* zXY8#3Z?;yf?y-LPV#LF(A;FJ!7?+A-22QzJJtnOE=#)cF2WppX9S?08*5jStkw_4` zkPiz{c>Dy#mNA|wh((_ zQvA^B2`15x-RSXnSo4#zj8eL1$^DND^M+!h9{84*Mx8o3h8S01-<>$_XMOqx=g=!v z!sKn^4ur`ZM8}37rE@t{?(rdI2Lxz@%aU4LO)f_lbff+_SPd$!7r!H z>1|s-DpA8T`v=XxuFHb)C~INky3P;FRH~8|KW1)>O|#YIEdfXI7+FpBOZJ_XE+} zTN(596S`iNb@#rGnen7WurTn-cD=x1(3wZt9BgkUqq7Pp!b1p3z z1P|+LG1Os;?VqDLeQOWy%#$X~worOByq@%Hv))5CLi%cjWYya%395qljzqJW%QSc5 zWhIq>*QbX4mM1>NBH!}tFTXC2X4=zd$IVs#JNL9MuP9UyxY26TgGY^nL~*0jn$ng# zNPDiD?c7M<{;yx`ut>a(d93yIjhZ>Xs>Sw=-Q$EOK*!anM`kPb?^N&62(XJUo=d+c z5<3fixNQsZOCVRy7`e4&?5z<`#=)r}$r+(P;C8X_q%Wnl77>6>5vV-+JCznNNeK1S8FtXVEzab(GleQBRc?@TutoAnatS{hG<(#O6% z4ENn0_-|$ChZ>)N8+R|OrrN&k|KWFR$Aay5i}SUsl7?Aq6&!qUDXsQPpNQx`f{e)r zW}hj%aMico^l32m>xVQ$nZQ&^4Ejeq<%`SM&{=+aKJ z%cquWZ(rz^pnEo%p0J%`6YO#FSo7l}yWTCjp<8y`f0cE|=kbqxlQ$2xD=RrA`s>ef%z*{J5{UlV0)PSl?&*f}9qa_swT)M-z_y(0M8)V>Xwu5YC8 zTKD%>5`|1a!)`;9L@NWkPA@6GowetiD0A3GqM{%Te6lWn;-rL@p3`KWBQ~J_&*%@3 zXvwiP#e;?oz4&1-x+U>0l2dfEjed07^5f*OlOF`oxq+i^cD#JvemwX7(wvFt+0w)} zPgb>#a$N2;_qcziQGw~S&HioUygu)Y&pq7Zwe|h1G57ZhLtTzcfLdFW!rhx;(4d92 zdNFS|(m4Mr;v1gy22@YW^_*015X$(THiprO7(H!ZGz6sA>19HS-%%n4Sg$cCak)wk zi)oQa$LgfCUd#eQ+JJ}&CGRFE_}xAXYZRzP2l7o|q+Eh=8d4AOHxXDak{i@g18QIl zAZwryi427`pqOvsLv;q6gcva)r!^44(Gq^sEYpEPiO8VUVvvsGJpmfm69NQ~8PrNW zOtM0l@89D0%tBDbXgGy|R6r_H#Ysh&7Lk*zMj%oP^&rLXKXkZEA`%b~B4U&pgzo@T zXbGKAhYA@+qeQd{rGTT=pjs#fX$`0qsac%wG@*uN{A4vNlvO}L>xb*kdr~A zT8!{5Qn-#3!D_Xb@0$WyQXmv60J%bpt97v0pwa1&c%g-vLRkX+; z#aW3?%0Hkd`2I(+)Bx~YCCkA&xt^w$7qA_ EfAjZsk^lez literal 0 HcmV?d00001 diff --git a/tests/data/bcpack/bc7-8192-3.bin b/tests/data/bcpack/bc7-8192-3.bin new file mode 100644 index 0000000..c362eec --- /dev/null +++ b/tests/data/bcpack/bc7-8192-3.bin @@ -0,0 +1 @@ +KKKKKˆaa”””””òDD‡‡‡‡‡eÀÀŽŽŽŽŽD²²²²²‰ˆ6ò� KKKK6eÎ¥””””�D ×‡‡‡‡Î‰�ŽŽŽŽ í²²²²ttttttttt•• ‰‰‰‰‰‰‰‰‰ \ No newline at end of file diff --git a/tests/data/bcpack/generate.py b/tests/data/bcpack/generate.py new file mode 100644 index 0000000..18b738c --- /dev/null +++ b/tests/data/bcpack/generate.py @@ -0,0 +1,186 @@ +"""Generate synthetic q=0 and q=15 BCPack vectors using the encoder's byte counts. + +The multiplexer never decodes rANS. Each inverse step records the number +of bytes the forward step will need later. +""" + +import random +import struct +from collections import deque +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +BC1 = (8, 8, 5, 6, 5, 5, 6, 5, 8, 8, 8, 8) +BC7 = (4, 4, 8, 8, 8, 8, 8, 7, 7, 5, 6, 8, 8, 8, 8, 5) + + +WIDTHS = { + 1: BC1, + 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: BC7, +} + + +def record_header(mode, body_size): + if body_size <= 256: + return bytes((mode, body_size - 1)) + return bytes((mode | 32,)) + struct.pack('= 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(' Date: Mon, 23 Nov 2026 15:02:09 -0700 Subject: [PATCH 16/37] Config: recreate xcl.toml only on NotFound and resolve memory mode case-insensitively (#106) From ivall/xcl#237 by @slopgobblercobbler (head 6ad1cea4c), squashed. --- crates/xcl/src/config.rs | 63 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 6 deletions(-) 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); From 4099e537a01ca1b925d8b1d49828ee0183d84e04 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:09 -0700 Subject: [PATCH 17/37] Present: configure HDR swapchain color space via SetColorSpace1 (#103) From ivall/xcl#238 by @slopgobblercobbler (head bc727533d), squashed. --- crates/xcl/src/hle/d3d12x/present.rs | 80 +++++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) 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)] From 91aa44b4d3b41e4629d5c7cd1708def833371266 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:09 -0700 Subject: [PATCH 18/37] Report: lock-safe crash report persistence under contention and re-entrancy (#106) From ivall/xcl#240 by @slopgobblercobbler (head 62cd3bcc6), squashed. --- crates/xcl/src/report.rs | 213 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 200 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index d54f98b..62b4a8f 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -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")); } } From 91fe05241950afa7bba9b185347463f53e45a1ca Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:09 -0700 Subject: [PATCH 19/37] Recomp: clamp 64-bit float results to [0.0, 1.0] instead of saturate (#105) From ivall/xcl#246 by @slopgobblercobbler (head e120969ae), squashed. --- crates/xcl/src/gpu/recomp/emit.rs | 4 ++-- crates/xcl/src/gpu/recomp/tests.rs | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 954d6d4..0d6baa0 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3124,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)"), @@ -3132,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")); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index c1c5a7d..4d77c06 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -7673,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() { From 50619c5052a0fefbccd732172acfdcc10d0f1c07 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:09 -0700 Subject: [PATCH 20/37] fix(gpu/run): keep descriptor heaps alive, harden device loss handling From ivall/xcl#239 by @racknea (head cc124cf80), squashed. --- crates/xcl/src/gpu/recomp/runner.rs | 974 ++++++++++++++-------------- 1 file changed, 500 insertions(+), 474 deletions(-) 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); From f9989c2f14b2113e5be70465d3f9948f06711e8b Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:02:19 -0700 Subject: [PATCH 21/37] reaches its title screen and menus: GPU title memory in large pages, to_zero pruned once From ivall/xcl#203 by @Sr-0w (head 7cbd0088c), squashed; title names in comments reworded. --- crates/xcl/src/hle/d3d12x/sparse.rs | 20 +++++++++++++++----- crates/xcl/src/hle/kernelx.rs | 17 ++++++++++++++--- 2 files changed, 29 insertions(+), 8 deletions(-) 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/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index d971829..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(); From 17b0669e25741082d674df16fba560653d33241e Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:09:52 -0700 Subject: [PATCH 22/37] FFI: use extern "system-unwind" across guest-reentry boundaries (#106) From ivall/xcl#197 by @JGonzalezRodriguez, squashed; conflict resolved by hand. --- crates/xcl/src/eh.rs | 32 +- crates/xcl/src/hle/gameinput.rs | 153 +++++- crates/xcl/src/hle/kernelx.rs | 102 +++- crates/xcl/src/hle/user.rs | 43 +- crates/xcl/src/hle/xaudio2.rs | 106 ++-- crates/xcl/src/hle/xgameruntime/api.rs | 76 ++- crates/xcl/src/hle/xgameruntime/gamesave.rs | 36 +- crates/xcl/src/hle/xgameruntime/mod.rs | 26 +- crates/xcl/src/hle/xgameruntime/networking.rs | 12 +- crates/xcl/src/hle/xgameruntime/taskqueue.rs | 189 ++++++-- crates/xcl/src/hle/xgameruntime/xasync.rs | 457 ++++++++++++++++-- crates/xcl/src/loader.rs | 79 ++- crates/xcl/src/main.rs | 4 +- crates/xcl/src/vfs_hooks.rs | 16 +- 14 files changed, 1145 insertions(+), 186 deletions(-) diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index f065bc1..a30143f 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -61,7 +61,7 @@ pub fn set_title_filter(f: usize) -> usize { TITLE_FILTER.swap(f, Ordering::AcqRel) } -unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i32 { +unsafe extern "system-unwind" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i32 { crate::hle::d3d12x::real::log_device_removed(); if !info.is_null() && !(*info).ExceptionRecord.is_null() { let rec = &*(*info).ExceptionRecord; @@ -114,7 +114,7 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i } match TITLE_FILTER.load(Ordering::Acquire) { 0 => 0, // EXCEPTION_CONTINUE_SEARCH - f => std::mem::transmute:: i32>(f)(info), + f => std::mem::transmute:: i32>(f)(info), } } @@ -146,7 +146,11 @@ pub fn install_crash_handler() { if let Err(e) = hooks::hook("ntdll.dll", "NtTerminateProcess", hk_nt_terminate_process as usize, &ORIG_NT_TERMINATE) { crate::xlog_warn!("{e}"); } - SetUnhandledExceptionFilter(Some(unhandled_filter)); + // SAFETY: `extern "system-unwind"` and `extern "system"` share the identical Win64 ABI; + // Windows `UnhandledExceptionFilter` guards the filter call with SEH. + let filter: unsafe extern "system" fn(*const EXCEPTION_POINTERS) -> i32 = + std::mem::transmute:: i32, _>(unhandled_filter); + SetUnhandledExceptionFilter(Some(filter)); install_invalid_parameter_handler(); windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(0, Some(cpp_exception_logger)); } @@ -1125,4 +1129,26 @@ mod tests { VirtualFree(page as _, 0, MEM_RELEASE); } } + + static TITLE_FILTER_TEST_LOCK: Mutex<()> = Mutex::new(()); + + #[test] + fn unhandled_filter_unwinds_cleanly_from_title_filter() { + let _serial = TITLE_FILTER_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + struct ResetFilter(usize); + impl Drop for ResetFilter { + fn drop(&mut self) { + set_title_filter(self.0); + } + } + + unsafe extern "system-unwind" fn throwing_title_filter(_info: *const EXCEPTION_POINTERS) -> i32 { + panic!("guest unhandled exception filter unwind"); + } + + let prev = set_title_filter(throwing_title_filter as usize); + let _reset = ResetFilter(prev); + let r = std::panic::catch_unwind(|| unsafe { unhandled_filter(std::ptr::null()) }); + assert!(r.is_err(), "unhandled_filter must propagate unwind from guest title filter"); + } } diff --git a/crates/xcl/src/hle/gameinput.rs b/crates/xcl/src/hle/gameinput.rs index 402d4c7..0815db2 100644 --- a/crates/xcl/src/hle/gameinput.rs +++ b/crates/xcl/src/hle/gameinput.rs @@ -647,8 +647,8 @@ unsafe extern "system" fn get_temporal_reading(this: *mut Object, _timestamp: u6 static TOKENS: AtomicU64 = AtomicU64::new(0); -type ReadingCallback = unsafe extern "system" fn(u64, *mut c_void, *mut Reading, bool); -type DeviceCallback = unsafe extern "system" fn(u64, *mut c_void, *mut Object, u64, u32, u32); +type ReadingCallback = unsafe extern "system-unwind" fn(u64, *mut c_void, *mut Reading, bool); +type DeviceCallback = unsafe extern "system-unwind" fn(u64, *mut c_void, *mut Object, u64, u32, u32); enum CallbackKind { Reading { ctx: usize, cb: ReadingCallback }, @@ -779,12 +779,17 @@ fn dispatch_reading_callbacks(s: GamepadState) { for entry in cbs { let CallbackKind::Reading { ctx, cb } = entry.kind else { continue }; let Some(_guard) = entry.try_enter() else { continue }; - let r = new_reading(s); + struct ReadingGuard(*mut Reading); + impl Drop for ReadingGuard { + fn drop(&mut self) { + unsafe { reading_release(self.0) }; + } + } + let r = ReadingGuard(new_reading(s)); // SAFETY: `cb` and `ctx` were registered by the caller; `_guard` keeps // `UnregisterCallback` blocked until `cb` returns so `ctx` stays valid. unsafe { - cb(entry.token, ctx as *mut c_void, r, false); - reading_release(r); + cb(entry.token, ctx as *mut c_void, r.0, false); } } } @@ -812,7 +817,7 @@ fn start_poller() { /// RegisterDeviceCallback(device, kind, status filter, enumeration kind, context, callback, /// &token): the gamepad, connected – at once for a blocking enumeration, from another /// thread for an asynchronous one, not at all without enumeration (it never comes or goes) -unsafe extern "system" fn register_device_callback(_this: *mut Object, dev: *mut c_void, kind: u32, _filter: u32, enumeration: u32, context: *mut c_void, cb: Option, token: *mut u64) -> HRESULT { +unsafe extern "system-unwind" fn register_device_callback(_this: *mut Object, dev: *mut c_void, kind: u32, _filter: u32, enumeration: u32, context: *mut c_void, cb: Option, token: *mut u64) -> HRESULT { let t = TOKENS.fetch_add(1, Ordering::Relaxed) + 1; if !token.is_null() { *token = t; @@ -826,13 +831,19 @@ unsafe extern "system" fn register_device_callback(_this: *mut Object, dev: *mut CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::clone(&entry)); let ctx = context as usize; let spawned = std::thread::Builder::new().name("xcl-gameinput-enum".into()).spawn(move || { + struct EntryCleanup(u64); + impl Drop for EntryCleanup { + fn drop(&mut self) { + CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).retain(|c| c.token != self.0); + } + } + let _cleanup = EntryCleanup(t); crate::eh::arm_current_thread(); if let Some(_guard) = entry.try_enter() { // SAFETY: `cb` and `ctx` were registered by the caller; `_guard` keeps // `UnregisterCallback` blocked until `cb` returns so `ctx` stays valid. unsafe { cb(t, ctx as *mut c_void, device(), now_us(), STATUS, 0) }; } - CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).retain(|c| c.token != t); }); if spawned.is_err() { CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).retain(|c| c.token != t); @@ -1206,12 +1217,12 @@ mod tests { } } - unsafe extern "system" fn gated_reading_cb(_token: u64, ctx: *mut c_void, _reading: *mut Reading, _overflow: bool) { + unsafe extern "system-unwind" fn gated_reading_cb(_token: u64, ctx: *mut c_void, _reading: *mut Reading, _overflow: bool) { let gate = &*(ctx as *const CallbackGate); gate.on_callback(); } - unsafe extern "system" fn gated_device_cb(_token: u64, ctx: *mut c_void, _dev: *mut Object, _ts: u64, _cur: u32, _prev: u32) { + unsafe extern "system-unwind" fn gated_device_cb(_token: u64, ctx: *mut c_void, _dev: *mut Object, _ts: u64, _cur: u32, _prev: u32) { let gate = &*(ctx as *const CallbackGate); gate.on_callback(); } @@ -1304,7 +1315,7 @@ mod tests { calls: AtomicU32, unreg_ok: std::sync::atomic::AtomicBool, } - unsafe extern "system" fn self_unreg_cb(token: u64, ctx: *mut c_void, _reading: *mut Reading, _overflow: bool) { + unsafe extern "system-unwind" fn self_unreg_cb(token: u64, ctx: *mut c_void, _reading: *mut Reading, _overflow: bool) { let c = &*(ctx as *const SelfCtx); c.calls.fetch_add(1, Ordering::AcqRel); let ok = unregister_callback(input(), token, u64::MAX); @@ -1359,4 +1370,126 @@ mod tests { assert!(gate.finished.load(Ordering::Acquire)); releaser.join().unwrap(); } + + #[test] + fn blocking_device_callback_unwinds_cleanly() { + unsafe extern "system-unwind" fn throwing_device_cb( + _token: u64, + _ctx: *mut c_void, + _dev: *mut Object, + _ts: u64, + _cur: u32, + _prev: u32, + ) { + panic!("guest GameInput DeviceCallback unwind"); + } + + let g = input(); + let mut token = 0u64; + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { + register_device_callback(g, std::ptr::null_mut(), KIND_GAMEPAD, STATUS, ENUM_BLOCKING, std::ptr::null_mut(), Some(throwing_device_cb), &mut token) + })); + assert!(r.is_err(), "RegisterDeviceCallback(ENUM_BLOCKING) must propagate unwind from guest callback"); + assert_ne!(token, 0); + } + + #[test] + fn reading_callback_unwind_releases_guard_and_unblocks_unregister() { + let _serial = READING_CB_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + + use std::sync::atomic::AtomicUsize; + + struct ThrowCtx { + test_tid: ThreadId, + held_reading: AtomicUsize, + } + + struct UnregGuard { + g: *mut Object, + token: u64, + } + impl Drop for UnregGuard { + fn drop(&mut self) { + if self.token != 0 { + unsafe { unregister_callback(self.g, self.token, u64::MAX) }; + } + } + } + + struct HeldReadingGuard(usize); + impl Drop for HeldReadingGuard { + fn drop(&mut self) { + if self.0 != 0 { + unsafe { reading_release(self.0 as *mut Reading) }; + } + } + } + + unsafe extern "system-unwind" fn throwing_reading_cb( + _token: u64, + ctx: *mut c_void, + reading: *mut Reading, + _overflow: bool, + ) { + let c = &*(ctx as *const ThrowCtx); + // Only throw on the test thread so the background poller thread never panics. + if std::thread::current().id() == c.test_tid { + // Take a temporary extra ref so we can safely verify after unwind that + // ReadingGuard released dispatch_reading_callbacks’s reference. + reading_add_ref(reading); + c.held_reading.store(reading as usize, Ordering::Release); + panic!("guest GameInput ReadingCallback unwind"); + } + } + + let test_tid = std::thread::current().id(); + let ctx = Box::new(ThrowCtx { test_tid, held_reading: AtomicUsize::new(0) }); + let g = input(); + // Declared after `ctx` so Drop always unregisters and waits for the poller before `ctx` frees. + let mut unreg = UnregGuard { g, token: 0 }; + let mut token = 0u64; + unsafe { + assert_eq!( + register_reading_callback(g, std::ptr::null_mut(), KIND_GAMEPAD, 0.0, &*ctx as *const ThrowCtx as *mut c_void, Some(throwing_reading_cb), &mut token), + S_OK + ); + } + unreg.token = token; + let entry = CALLBACKS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .find(|c| c.token == token) + .cloned() + .expect("registered reading callback entry"); + + let r = std::panic::catch_unwind(|| { + dispatch_reading_callbacks(GamepadState { buttons: A, ..Default::default() }); + }); + assert!(r.is_err(), "dispatch_reading_callbacks must propagate unwind from guest ReadingCallback"); + + // Verify ReadingGuard::drop released the dispatcher’s ref (refs went 2 -> 1). + let held = HeldReadingGuard(ctx.held_reading.swap(0, Ordering::AcqRel)); + assert_ne!(held.0, 0, "callback must have received a Reading"); + let refs_after_unwind = unsafe { (*(held.0 as *const Reading)).refs.load(Ordering::Acquire) }; + assert_eq!(refs_after_unwind, 1, "ReadingGuard did not release Reading on unwind"); + drop(held); + + // Verify CallbackGuard::drop cleared this thread from running_threads and decremented in_flight. + { + let st = entry.state.lock().unwrap_or_else(|e| e.into_inner()); + assert!(!st.running_threads.contains(&test_tid), "CallbackGuard did not clear test_tid from running_threads on unwind"); + assert_eq!(st.in_flight, st.running_threads.len(), "CallbackGuard did not decrement in_flight on unwind"); + } + + // Also verify from a DIFFERENT thread that zero-timeout unregister does not see test_tid as in-flight. + let g_addr = g as usize; + let ok = std::thread::spawn(move || unsafe { unregister_callback(g_addr as *mut Object, token, 0) }) + .join() + .unwrap(); + if ok { + unreg.token = 0; + } + assert!(ok, "other-thread unregister_callback(0) saw stale in-flight tracking after unwind"); + } } diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 0a84078..746ec9b 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -498,19 +498,19 @@ pub unsafe extern "system" fn XMemFreeDefault(p: *mut c_void, attrs: u64) { } } -type XMemAllocFn = unsafe extern "system" fn(usize, u64) -> *mut c_void; -type XMemFreeFn = unsafe extern "system" fn(*mut c_void, u64); +type XMemAllocFn = unsafe extern "system-unwind" fn(usize, u64) -> *mut c_void; +type XMemFreeFn = unsafe extern "system-unwind" fn(*mut c_void, u64); static XMEM_ALLOC_HOOK: AtomicUsize = AtomicUsize::new(0); static XMEM_FREE_HOOK: AtomicUsize = AtomicUsize::new(0); -pub unsafe extern "system" fn XMemAlloc(size: usize, attrs: u64) -> *mut c_void { +pub unsafe extern "system-unwind" fn XMemAlloc(size: usize, attrs: u64) -> *mut c_void { match XMEM_ALLOC_HOOK.load(Ordering::Acquire) { 0 => XMemAllocDefault(size, attrs), f => std::mem::transmute::(f)(size, attrs), } } -pub unsafe extern "system" fn XMemFree(p: *mut c_void, attrs: u64) { +pub unsafe extern "system-unwind" fn XMemFree(p: *mut c_void, attrs: u64) { match XMEM_FREE_HOOK.load(Ordering::Acquire) { 0 => XMemFreeDefault(p, attrs), f => std::mem::transmute::(f)(p, attrs), @@ -1443,11 +1443,11 @@ fn load_library_impl(name: Option) -> usize { } } -pub unsafe extern "system" fn LoadLibraryW(name: *const u16) -> usize { +pub unsafe extern "system-unwind" fn LoadLibraryW(name: *const u16) -> usize { load_library_impl(from_wide_ptr(name)) } -pub unsafe extern "system" fn LoadLibraryA(name: *const u8) -> usize { +pub unsafe extern "system-unwind" fn LoadLibraryA(name: *const u8) -> usize { load_library_impl(from_ansi_ptr(name)) } @@ -1456,7 +1456,7 @@ unsafe fn load_as_data(name: &str, file: HANDLE, flags: u32) -> usize { ll::LoadLibraryExW(crate::util::wide(&real).as_ptr(), file, flags) as usize } -pub unsafe extern "system" fn LoadLibraryExW(name: *const u16, file: HANDLE, flags: u32) -> usize { +pub unsafe extern "system-unwind" fn LoadLibraryExW(name: *const u16, file: HANDLE, flags: u32) -> usize { if flags & LOAD_AS_DATA != 0 { let Some(name) = from_wide_ptr(name) else { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); @@ -1467,7 +1467,7 @@ pub unsafe extern "system" fn LoadLibraryExW(name: *const u16, file: HANDLE, fla load_library_impl(from_wide_ptr(name)) } -pub unsafe extern "system" fn LoadLibraryExA(name: *const u8, file: HANDLE, flags: u32) -> usize { +pub unsafe extern "system-unwind" fn LoadLibraryExA(name: *const u8, file: HANDLE, flags: u32) -> usize { if flags & LOAD_AS_DATA != 0 { let Some(name) = from_ansi_ptr(name) else { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); @@ -1478,11 +1478,11 @@ pub unsafe extern "system" fn LoadLibraryExA(name: *const u8, file: HANDLE, flag load_library_impl(from_ansi_ptr(name)) } -pub unsafe extern "system" fn LoadPackagedLibrary(name: *const u16, _reserved: u32) -> usize { +pub unsafe extern "system-unwind" fn LoadPackagedLibrary(name: *const u16, _reserved: u32) -> usize { load_library_impl(from_wide_ptr(name)) } -pub unsafe extern "system" fn GetProcAddress(h: usize, name: *const u8) -> usize { +pub unsafe extern "system-unwind" fn GetProcAddress(h: usize, name: *const u8) -> usize { if name.is_null() { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; @@ -2368,4 +2368,86 @@ mod tests { assert_ne!(stub_h, 0); assert_eq!(module_handle_in(®, "unit_stub_probe.dll"), stub_h); } + + #[test] + fn xmem_allocation_hooks_unwind_cleanly() { + use std::sync::atomic::AtomicU32; + + // Unique sentinel attributes so concurrent unit tests calling XMemAlloc/XMemFree + // continue using the default allocator undisturbed. + const SENTINEL_ATTRS: u64 = 0xDEAD_BEEF_CAFE_0001; + static DROPS: AtomicU32 = AtomicU32::new(0); + + struct DropProbe; + impl Drop for DropProbe { + fn drop(&mut self) { + DROPS.fetch_add(1, Ordering::SeqCst); + } + } + + struct HookReset; + impl Drop for HookReset { + fn drop(&mut self) { + unsafe { XMemSetAllocationHooks(0, 0) }; + TITLE_HOOKS[0].store(0, Ordering::Release); + TITLE_HOOKS[1].store(0, Ordering::Release); + } + } + + unsafe extern "system-unwind" fn throwing_alloc(size: usize, attrs: u64) -> *mut c_void { + if attrs == SENTINEL_ATTRS { + let _probe = DropProbe; + panic!("guest XMemAlloc hook unwind"); + } + XMemAllocDefault(size, attrs) + } + + unsafe extern "system-unwind" fn throwing_free(p: *mut c_void, attrs: u64) { + if attrs == SENTINEL_ATTRS { + let _probe = DropProbe; + panic!("guest XMemFree hook unwind"); + } + XMemFreeDefault(p, attrs); + } + + // Separate title hooks whose non-sentinel fallback returns null / no-op (matching + // `TITLE_HOOKS == [0, 0]`) so concurrent D3D12 tests calling `runtime_alloc` do not + // receive `Memory::Title` allocations that would miss `TITLE_HOOKS[1]` after reset. + unsafe extern "system-unwind" fn throwing_title_alloc(_size: usize, attrs: u64) -> *mut c_void { + if attrs == SENTINEL_ATTRS { + let _probe = DropProbe; + panic!("guest title runtime_alloc hook unwind"); + } + std::ptr::null_mut() + } + + unsafe extern "system-unwind" fn throwing_title_free(_p: *mut c_void, attrs: u64) { + if attrs == SENTINEL_ATTRS { + let _probe = DropProbe; + panic!("guest title runtime_free hook unwind"); + } + } + + let _reset = HookReset; + DROPS.store(0, Ordering::SeqCst); + + unsafe { + XMemSetAllocationHooks(throwing_alloc as usize, throwing_free as usize); + TITLE_HOOKS[0].store(throwing_title_alloc as usize, Ordering::Release); + TITLE_HOOKS[1].store(throwing_title_free as usize, Ordering::Release); + + let r1 = std::panic::catch_unwind(|| XMemAlloc(64, SENTINEL_ATTRS)); + assert!(r1.is_err(), "XMemAlloc should propagate unwind from guest alloc hook"); + + let r2 = std::panic::catch_unwind(|| XMemFree(0x1000 as *mut c_void, SENTINEL_ATTRS)); + assert!(r2.is_err(), "XMemFree should propagate unwind from guest free hook"); + + let r3 = std::panic::catch_unwind(|| runtime_alloc(64, SENTINEL_ATTRS)); + assert!(r3.is_err(), "runtime_alloc should propagate unwind from title alloc hook"); + + let r4 = std::panic::catch_unwind(|| runtime_free(0x1000, SENTINEL_ATTRS)); + assert!(r4.is_err(), "runtime_free should propagate unwind from title free hook"); + } + assert_eq!(DROPS.load(Ordering::SeqCst), 4, "Drop guards must run on every unwound FFI call"); + } } diff --git a/crates/xcl/src/hle/user.rs b/crates/xcl/src/hle/user.rs index d00fd4d..030e286 100644 --- a/crates/xcl/src/hle/user.rs +++ b/crates/xcl/src/hle/user.rs @@ -27,6 +27,10 @@ use crate::util::{from_ansi_ptr, wide}; extern "system" { fn RegisterClassExW(c: *const WndClassEx) -> u16; fn SetWindowLongPtrW(hwnd: *mut c_void, index: i32, value: isize) -> isize; +} + +#[link(name = "user32")] +extern "system-unwind" { fn CallWindowProcW(proc_: isize, hwnd: *mut c_void, msg: u32, wp: usize, lp: isize) -> isize; fn SetWindowPos(hwnd: *mut c_void, after: *mut c_void, x: i32, y: i32, w: i32, h: i32, flags: u32) -> i32; #[allow(clippy::too_many_arguments)] @@ -95,7 +99,7 @@ pub unsafe extern "system" fn RegisterClassExA(c: *const WndClassEx) -> u16 } #[allow(clippy::too_many_arguments)] -pub unsafe extern "system" fn CreateWindowExA(ex_style: u32, class: *const u8, title: *const u8, style: u32, x: i32, y: i32, w: i32, h: i32, parent: *mut c_void, menu: *mut c_void, instance: *mut c_void, param: *const c_void) -> *mut c_void { +pub unsafe extern "system-unwind" fn CreateWindowExA(ex_style: u32, class: *const u8, title: *const u8, style: u32, x: i32, y: i32, w: i32, h: i32, parent: *mut c_void, menu: *mut c_void, instance: *mut c_void, param: *const c_void) -> *mut c_void { let mut keep = Vec::new(); let class = name(class, &mut keep); let title = if title.is_null() { std::ptr::null() } else { name(title, &mut keep) }; @@ -105,7 +109,7 @@ pub unsafe extern "system" fn CreateWindowExA(ex_style: u32, class: *const u8, t /// CreateWindowExW of the console's ntuser API set: as `CreateWindowExA`, without the text /// conversion. #[allow(clippy::too_many_arguments)] -unsafe extern "system" fn create_window_ex_w(ex_style: u32, class: *const u16, title: *const u16, style: u32, x: i32, y: i32, w: i32, h: i32, parent: *mut c_void, menu: *mut c_void, instance: *mut c_void, param: *const c_void) -> *mut c_void { +unsafe extern "system-unwind" fn create_window_ex_w(ex_style: u32, class: *const u16, title: *const u16, style: u32, x: i32, y: i32, w: i32, h: i32, parent: *mut c_void, menu: *mut c_void, instance: *mut c_void, param: *const c_void) -> *mut c_void { console_window(ex_style, class, title, style, x, y, w, h, parent, menu, instance, param) } @@ -162,7 +166,7 @@ unsafe fn console_window(ex_style: u32, class: *const u16, title: *const u16, st /// A console window has no non-client area whatever its style, and may be the screen's size /// on a smaller PC monitor. -unsafe extern "system" fn console_wndproc(hwnd: *mut c_void, msg: u32, wp: usize, lp: isize) -> isize { +unsafe extern "system-unwind" fn console_wndproc(hwnd: *mut c_void, msg: u32, wp: usize, lp: isize) -> isize { let orig = PROCS.lock().unwrap().iter().find(|e| e.0 == hwnd as usize).map(|e| e.1); let Some(orig) = orig else { return 0 }; match msg { @@ -292,4 +296,37 @@ mod tests { assert_eq!(error, windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER); } } + + #[test] + fn console_wndproc_unwinds_cleanly_from_guest_wndproc() { + const FAKE_HWND: usize = 0x5843_4C01; + const WM_APP_TEST: u32 = 0x8001; + + struct ProcCleanup(usize); + impl Drop for ProcCleanup { + fn drop(&mut self) { + PROCS.lock().unwrap_or_else(|e| e.into_inner()).retain(|e| e.0 != self.0); + } + } + + unsafe extern "system-unwind" fn throwing_wndproc(_hwnd: *mut c_void, _msg: u32, _wp: usize, _lp: isize) -> isize { + panic!("guest wndproc unwind"); + } + + let _cleanup = ProcCleanup(FAKE_HWND); + PROCS.lock().unwrap().push((FAKE_HWND, throwing_wndproc as usize as isize)); + + let r = std::panic::catch_unwind(|| unsafe { + console_wndproc(FAKE_HWND as *mut c_void, WM_APP_TEST, 0, 0) + }); + assert!(r.is_err(), "console_wndproc should propagate unwind from guest wndproc through CallWindowProcW"); + assert!(PROCS.lock().is_ok(), "PROCS mutex must remain unpoisoned after unwind"); + + // WM_NCDESTROY removes the entry before delegating to the guest wndproc. + let r2 = std::panic::catch_unwind(|| unsafe { + console_wndproc(FAKE_HWND as *mut c_void, WM_NCDESTROY, 0, 0) + }); + assert!(r2.is_err(), "console_wndproc(WM_NCDESTROY) should propagate unwind cleanly"); + assert!(!PROCS.lock().unwrap().iter().any(|e| e.0 == FAKE_HWND)); + } } diff --git a/crates/xcl/src/hle/xaudio2.rs b/crates/xcl/src/hle/xaudio2.rs index 22baea9..f762160 100644 --- a/crates/xcl/src/hle/xaudio2.rs +++ b/crates/xcl/src/hle/xaudio2.rs @@ -534,13 +534,13 @@ struct DecodedVoiceHandle { // IXAudio2VoiceCallback vtable (7 methods, no IUnknown). #[repr(C)] struct VoiceCallbackVtbl { - pass_start: unsafe extern "system" fn(*mut c_void, u32), - pass_end: unsafe extern "system" fn(*mut c_void), - stream_end: unsafe extern "system" fn(*mut c_void), - buffer_start: unsafe extern "system" fn(*mut c_void, *mut c_void), - buffer_end: unsafe extern "system" fn(*mut c_void, *mut c_void), - loop_end: unsafe extern "system" fn(*mut c_void, *mut c_void), - voice_error: unsafe extern "system" fn(*mut c_void, *mut c_void, HRESULT), + pass_start: unsafe extern "system-unwind" fn(*mut c_void, u32), + pass_end: unsafe extern "system-unwind" fn(*mut c_void), + stream_end: unsafe extern "system-unwind" fn(*mut c_void), + buffer_start: unsafe extern "system-unwind" fn(*mut c_void, *mut c_void), + buffer_end: unsafe extern "system-unwind" fn(*mut c_void, *mut c_void), + loop_end: unsafe extern "system-unwind" fn(*mut c_void, *mut c_void), + voice_error: unsafe extern "system-unwind" fn(*mut c_void, *mut c_void, HRESULT), } #[repr(C)] @@ -561,28 +561,28 @@ unsafe fn title_cb_vtbl(cb: usize) -> Option<(*mut c_void, *const VoiceCallbackV Some((obj, vtbl)) } -unsafe extern "system" fn decoded_cb_pass_start(this: *mut c_void, bytes: u32) { +unsafe extern "system-unwind" fn decoded_cb_pass_start(this: *mut c_void, bytes: u32) { let cb = &*(this as *const DecodedCallback); if let Some((obj, vt)) = title_cb_vtbl(cb.state.title_cb) { ((*vt).pass_start)(obj, bytes); } } -unsafe extern "system" fn decoded_cb_pass_end(this: *mut c_void) { +unsafe extern "system-unwind" fn decoded_cb_pass_end(this: *mut c_void) { let cb = &*(this as *const DecodedCallback); if let Some((obj, vt)) = title_cb_vtbl(cb.state.title_cb) { ((*vt).pass_end)(obj); } } -unsafe extern "system" fn decoded_cb_stream_end(this: *mut c_void) { +unsafe extern "system-unwind" fn decoded_cb_stream_end(this: *mut c_void) { let cb = &*(this as *const DecodedCallback); if let Some((obj, vt)) = title_cb_vtbl(cb.state.title_cb) { ((*vt).stream_end)(obj); } } -unsafe extern "system" fn decoded_cb_buffer_start(this: *mut c_void, ctx: *mut c_void) { +unsafe extern "system-unwind" fn decoded_cb_buffer_start(this: *mut c_void, ctx: *mut c_void) { let cb = &*(this as *const DecodedCallback); let orig = cb .state @@ -597,7 +597,7 @@ unsafe extern "system" fn decoded_cb_buffer_start(this: *mut c_void, ctx: *mut c } } -unsafe extern "system" fn decoded_cb_buffer_end(this: *mut c_void, ctx: *mut c_void) { +unsafe extern "system-unwind" fn decoded_cb_buffer_end(this: *mut c_void, ctx: *mut c_void) { let cb = &*(this as *const DecodedCallback); // Remove and drop the decoded PCM buffer before invoking the title's callback so // the lock is released and no double-free or deadlock can occur. @@ -609,7 +609,7 @@ unsafe extern "system" fn decoded_cb_buffer_end(this: *mut c_void, ctx: *mut c_v } } -unsafe extern "system" fn decoded_cb_loop_end(this: *mut c_void, ctx: *mut c_void) { +unsafe extern "system-unwind" fn decoded_cb_loop_end(this: *mut c_void, ctx: *mut c_void) { let cb = &*(this as *const DecodedCallback); let orig = cb .state @@ -624,7 +624,7 @@ unsafe extern "system" fn decoded_cb_loop_end(this: *mut c_void, ctx: *mut c_voi } } -unsafe extern "system" fn decoded_cb_voice_error(this: *mut c_void, ctx: *mut c_void, hr: HRESULT) { +unsafe extern "system-unwind" fn decoded_cb_voice_error(this: *mut c_void, ctx: *mut c_void, hr: HRESULT) { let cb = &*(this as *const DecodedCallback); let orig = cb .state @@ -1314,19 +1314,19 @@ mod tests { static STARTED: AtomicUsize = AtomicUsize::new(0); static STREAM_END: AtomicUsize = AtomicUsize::new(0); - unsafe extern "system" fn on_pass_start(_: *mut c_void, _: u32) {} - unsafe extern "system" fn on_nothing(_: *mut c_void) {} - unsafe extern "system" fn on_stream_end(_: *mut c_void) { + unsafe extern "system-unwind" fn on_pass_start(_: *mut c_void, _: u32) {} + unsafe extern "system-unwind" fn on_nothing(_: *mut c_void) {} + unsafe extern "system-unwind" fn on_stream_end(_: *mut c_void) { STREAM_END.fetch_add(1, Ordering::SeqCst); } - unsafe extern "system" fn on_buf_start(_: *mut c_void, ctx: *mut c_void) { + unsafe extern "system-unwind" fn on_buf_start(_: *mut c_void, ctx: *mut c_void) { STARTED.fetch_add(ctx as usize, Ordering::SeqCst); } - unsafe extern "system" fn on_buf_end(_: *mut c_void, ctx: *mut c_void) { + unsafe extern "system-unwind" fn on_buf_end(_: *mut c_void, ctx: *mut c_void) { ENDED.fetch_add(ctx as usize, Ordering::SeqCst); } - unsafe extern "system" fn on_loop(_: *mut c_void, _: *mut c_void) {} - unsafe extern "system" fn on_err(_: *mut c_void, _: *mut c_void, _: HRESULT) {} + unsafe extern "system-unwind" fn on_loop(_: *mut c_void, _: *mut c_void) {} + unsafe extern "system-unwind" fn on_err(_: *mut c_void, _: *mut c_void, _: HRESULT) {} static TEST_VTBL: VoiceCallbackVtbl = VoiceCallbackVtbl { pass_start: on_pass_start, @@ -1461,19 +1461,19 @@ mod tests { static STARTED: AtomicUsize = AtomicUsize::new(0); static STREAM_END: AtomicUsize = AtomicUsize::new(0); - unsafe extern "system" fn on_pass_start(_: *mut c_void, _: u32) {} - unsafe extern "system" fn on_nothing(_: *mut c_void) {} - unsafe extern "system" fn on_stream_end(_: *mut c_void) { + unsafe extern "system-unwind" fn on_pass_start(_: *mut c_void, _: u32) {} + unsafe extern "system-unwind" fn on_nothing(_: *mut c_void) {} + unsafe extern "system-unwind" fn on_stream_end(_: *mut c_void) { STREAM_END.fetch_add(1, Ordering::SeqCst); } - unsafe extern "system" fn on_buf_start(_: *mut c_void, ctx: *mut c_void) { + unsafe extern "system-unwind" fn on_buf_start(_: *mut c_void, ctx: *mut c_void) { STARTED.fetch_add(ctx as usize, Ordering::SeqCst); } - unsafe extern "system" fn on_buf_end(_: *mut c_void, ctx: *mut c_void) { + unsafe extern "system-unwind" fn on_buf_end(_: *mut c_void, ctx: *mut c_void) { ENDED.fetch_add(ctx as usize, Ordering::SeqCst); } - unsafe extern "system" fn on_loop(_: *mut c_void, _: *mut c_void) {} - unsafe extern "system" fn on_err(_: *mut c_void, _: *mut c_void, _: HRESULT) {} + unsafe extern "system-unwind" fn on_loop(_: *mut c_void, _: *mut c_void) {} + unsafe extern "system-unwind" fn on_err(_: *mut c_void, _: *mut c_void, _: HRESULT) {} static TEST_VTBL: VoiceCallbackVtbl = VoiceCallbackVtbl { pass_start: on_pass_start, @@ -1757,4 +1757,54 @@ mod tests { assert_eq!(flush(guard.voice), S_OK); } } + + #[test] + fn decoded_voice_callback_unwinds_cleanly_and_frees_buffer() { + unsafe extern "system-unwind" fn noop_u32(_: *mut c_void, _: u32) {} + unsafe extern "system-unwind" fn noop(_: *mut c_void) {} + unsafe extern "system-unwind" fn noop_ptr(_: *mut c_void, _: *mut c_void) {} + unsafe extern "system-unwind" fn throwing_buf_end(_: *mut c_void, ctx: *mut c_void) { + assert_eq!(ctx as usize, 0xCAFE_BABE); + panic!("guest IXAudio2VoiceCallback::OnBufferEnd unwind"); + } + unsafe extern "system-unwind" fn noop_err(_: *mut c_void, _: *mut c_void, _: HRESULT) {} + + static THROW_VTBL: VoiceCallbackVtbl = VoiceCallbackVtbl { + pass_start: noop_u32, + pass_end: noop, + stream_end: noop, + buffer_start: noop_ptr, + buffer_end: throwing_buf_end, + loop_end: noop_ptr, + voice_error: noop_err, + }; + #[repr(C)] + struct ThrowCb { + vtbl: &'static VoiceCallbackVtbl, + } + static THROW_CB: ThrowCb = ThrowCb { vtbl: &THROW_VTBL }; + + let mut xma_fmt = xma2(1, 48_000, 6080, 2048, 1); + xma_fmt.num_streams = 1; + let dec = xma2::Decoder::new(unsafe { xma_stream_config(&xma_fmt.wfx).unwrap().unwrap() }).unwrap(); + let state = Arc::new(DecodedVoiceState { + decoder: Mutex::new(VoiceDecoder::Xma { decoder: dec, info: XmaInfo::default() }), + block_align: 2048, + channels: 1, + rate: 48_000, + avg_bytes: 6080, + title_cb: &THROW_CB as *const ThrowCb as usize, + live_buffers: Mutex::new(HashMap::new()), + }); + let buf = Box::new(DecodedBuffer { orig_context: 0xCAFE_BABE, _pcm: vec![0u8; 64].into_boxed_slice() }); + let tok = &*buf as *const DecodedBuffer as usize; + state.live_buffers.lock().unwrap().insert(tok, buf); + + let wrapped = DecodedCallback { vtbl: &DECODED_CALLBACK_VTBL, state: Arc::clone(&state) }; + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { + decoded_cb_buffer_end(&wrapped as *const DecodedCallback as *mut c_void, tok as *mut c_void); + })); + assert!(r.is_err(), "decoded_cb_buffer_end must propagate unwind from guest OnBufferEnd"); + assert!(state.live_buffers.lock().unwrap().is_empty(), "decoded buffer must be freed and lock unpoisoned on unwind"); + } } diff --git a/crates/xcl/src/hle/xgameruntime/api.rs b/crates/xcl/src/hle/xgameruntime/api.rs index 2af27ab..a35e9e2 100644 --- a/crates/xcl/src/hle/xgameruntime/api.rs +++ b/crates/xcl/src/hle/xgameruntime/api.rs @@ -223,14 +223,14 @@ pub unsafe extern "system" fn UninitializeApiImpl() { static ERROR_CB: Mutex> = Mutex::new(None); static ERROR_OPTIONS: AtomicUsize = AtomicUsize::new(0); -pub unsafe extern "system" fn XErrorReport(hr: HRESULT, message: *const u8) { +pub unsafe extern "system-unwind" fn XErrorReport(hr: HRESULT, message: *const u8) { let text = crate::util::from_cstr_ptr(message).unwrap_or_default(); crate::xlog_warn!("XErrorReport {:#x}: {text}", hr as u32); // Copy and release `ERROR_CB` before invoking the guest callback so re-entrant calls to // `XErrorSetCallback` or `XErrorReport` do not deadlock. let entry = *ERROR_CB.lock().unwrap(); if let Some((cb, ctx)) = entry { - let f: unsafe extern "system" fn(HRESULT, *const u8, *mut c_void) -> bool = std::mem::transmute(cb); + let f: unsafe extern "system-unwind" fn(HRESULT, *const u8, *mut c_void) -> bool = std::mem::transmute(cb); let _ = f(hr, message, ctx as *mut c_void); } } @@ -413,7 +413,7 @@ unsafe fn unknown_slot(this: *const Obj, slot: usize) -> usize { } } -type Fwd = unsafe extern "system" fn(*const Obj, usize, usize, usize, usize, usize, usize, usize, usize, usize) -> usize; +type Fwd = unsafe extern "system-unwind" fn(*const Obj, usize, usize, usize, usize, usize, usize, usize, usize, usize) -> usize; /// Call slot `slot` of the PC object with the caller's arguments (up to 9; extra ones are /// ignored by the callee). @@ -428,14 +428,14 @@ unsafe fn forward(this: *const Obj, slot: usize, a: [usize; 9]) -> usize { /// Slot `slot` of an XCL object: its API function with the caller's arguments after `this`. unsafe fn call_target(this: *const Obj, slot: usize, a: [usize; 9]) -> usize { - let f: unsafe extern "system" fn(usize, usize, usize, usize, usize, usize, usize, usize, usize) -> usize = std::mem::transmute((*this).targets[slot]); + let f: unsafe extern "system-unwind" fn(usize, usize, usize, usize, usize, usize, usize, usize, usize) -> usize = std::mem::transmute((*this).targets[slot]); f(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]) } macro_rules! per_slot { ($($n:literal)*) => { const SHIMS: [Fwd; SLOTS] = [$({ - unsafe extern "system" fn f(this: *const Obj, a: usize, b: usize, c: usize, d: usize, e: usize, g: usize, h: usize, i: usize, j: usize) -> usize { + unsafe extern "system-unwind" fn f(this: *const Obj, a: usize, b: usize, c: usize, d: usize, e: usize, g: usize, h: usize, i: usize, j: usize) -> usize { call_target(this, $n, [a, b, c, d, e, g, h, i, j]) } f @@ -447,7 +447,7 @@ macro_rules! per_slot { f }),*]; const FORWARDS: [Fwd; SLOTS] = [$({ - unsafe extern "system" fn f(this: *const Obj, a: usize, b: usize, c: usize, d: usize, e: usize, g: usize, h: usize, i: usize, j: usize) -> usize { + unsafe extern "system-unwind" fn f(this: *const Obj, a: usize, b: usize, c: usize, d: usize, e: usize, g: usize, h: usize, i: usize, j: usize) -> usize { forward(this, $n, [a, b, c, d, e, g, h, i, j]) } f @@ -953,19 +953,19 @@ unsafe extern "system" fn empty_result(b: *mut XAsyncBlock) -> HRESULT { XAsyncGetStatus(b, false) } -unsafe extern "system" fn resolve_privilege_async(_user: usize, _options: u32, _privilege: u32, b: *mut XAsyncBlock) -> HRESULT { +unsafe extern "system-unwind" fn resolve_privilege_async(_user: usize, _options: u32, _privilege: u32, b: *mut XAsyncBlock) -> HRESULT { completed(b) } -unsafe extern "system" fn resolve_issue_async(_user: usize, _url: usize, b: *mut XAsyncBlock) -> HRESULT { +unsafe extern "system-unwind" fn resolve_issue_async(_user: usize, _url: usize, b: *mut XAsyncBlock) -> HRESULT { completed(b) } -unsafe extern "system" fn sign_out_async(_user: usize, b: *mut XAsyncBlock) -> HRESULT { +unsafe extern "system-unwind" fn sign_out_async(_user: usize, b: *mut XAsyncBlock) -> HRESULT { completed(b) } -unsafe extern "system" fn prompt_space_async(_bytes: u64, b: *mut XAsyncBlock) -> HRESULT { +unsafe extern "system-unwind" fn prompt_space_async(_bytes: u64, b: *mut XAsyncBlock) -> HRESULT { completed(b) } @@ -978,7 +978,7 @@ unsafe extern "system" fn sign_out_deferral(out: *mut usize) -> HRESULT { /// XUserAddByIdWithUiAsync: the local user by either of its ids (XUserAddByIdWithUiResult = /// XUserAddResult) -unsafe extern "system" fn add_by_id_async(id: u64, b: *mut XAsyncBlock) -> HRESULT { +unsafe extern "system-unwind" fn add_by_id_async(id: u64, b: *mut XAsyncBlock) -> HRESULT { let mut h = std::ptr::null_mut(); if find_user(id, &mut h) < 0 { return E_GAMEUSER_USER_NOT_FOUND; @@ -1006,7 +1006,7 @@ static PICTURE_ID: u8 = 0; /// XUserGetGamerPictureAsync(user, size, async): a plain picture (PNG) of the requested size /// (XUserGamerPictureSize: 64, 208, 424, 1080 pixels) – there is no profile offline. -unsafe extern "system" fn gamer_picture_async(user: *mut c_void, size: u32, b: *mut XAsyncBlock) -> HRESULT { +unsafe extern "system-unwind" fn gamer_picture_async(user: *mut c_void, size: u32, b: *mut XAsyncBlock) -> HRESULT { let side = match size { 0 => 64, 1 => 208, @@ -1020,7 +1020,7 @@ unsafe extern "system" fn gamer_picture_async(user: *mut c_void, size: u32, b: * begin_with(b, &PICTURE_ID as *const u8 as usize, move || Ok(png_square(side, [0x5A, 0x6E, 0x82]))) } -unsafe extern "system" fn gamer_picture_result(b: *mut XAsyncBlock, size: usize, buf: *mut c_void, used: *mut usize) -> HRESULT { +unsafe extern "system-unwind" fn gamer_picture_result(b: *mut XAsyncBlock, size: usize, buf: *mut c_void, used: *mut usize) -> HRESULT { XAsyncGetResult(b, &PICTURE_ID as *const u8 as *const c_void, size, buf, used) } @@ -1109,15 +1109,15 @@ unsafe extern "system" fn install_chunks(id: *const u8, count: u32, sel: *const static INSTALL_ID: u8 = 0; static MOUNT_ID: u8 = 0; -unsafe extern "system" fn install_chunks_async(_id: usize, _count: u32, _sel: usize, _interval: u32, _suppress: bool, b: *mut XAsyncBlock) -> HRESULT { +unsafe extern "system-unwind" fn install_chunks_async(_id: usize, _count: u32, _sel: usize, _interval: u32, _suppress: bool, b: *mut XAsyncBlock) -> HRESULT { begin_with(b, &INSTALL_ID as *const u8 as usize, || Ok((&MONITOR as *const u64 as usize).to_le_bytes().to_vec())) } -unsafe extern "system" fn install_chunks_result(b: *mut XAsyncBlock, out: *mut usize) -> HRESULT { +unsafe extern "system-unwind" fn install_chunks_result(b: *mut XAsyncBlock, out: *mut usize) -> HRESULT { XAsyncGetResult(b, &INSTALL_ID as *const u8 as *const c_void, 8, out as *mut c_void, std::ptr::null_mut()) } -unsafe extern "system" fn mount_with_ui_async(id: *const u8, b: *mut XAsyncBlock) -> HRESULT { +unsafe extern "system-unwind" fn mount_with_ui_async(id: *const u8, b: *mut XAsyncBlock) -> HRESULT { let mut m: *mut c_void = std::ptr::null_mut(); let hr = XPackageMount(id, &mut m); if hr < 0 { @@ -1127,7 +1127,7 @@ unsafe extern "system" fn mount_with_ui_async(id: *const u8, b: *mut XAsyncBlock begin_with(b, &MOUNT_ID as *const u8 as usize, move || Ok(m.to_le_bytes().to_vec())) } -unsafe extern "system" fn mount_with_ui_result(b: *mut XAsyncBlock, out: *mut usize) -> HRESULT { +unsafe extern "system-unwind" fn mount_with_ui_result(b: *mut XAsyncBlock, out: *mut usize) -> HRESULT { XAsyncGetResult(b, &MOUNT_ID as *const u8 as *const c_void, 8, out as *mut c_void, std::ptr::null_mut()) } @@ -1149,7 +1149,7 @@ struct PackageDetails { } /// XPackageEnumeratePackages(kind, scope, context, callback): the game itself (no DLC). -unsafe extern "system" fn enumerate_packages(kind: u32, _scope: u32, ctx: *mut c_void, cb: Option bool>) -> HRESULT { +unsafe extern "system-unwind" fn enumerate_packages(kind: u32, _scope: u32, ctx: *mut c_void, cb: Option bool>) -> HRESULT { let Some(cb) = cb else { return E_INVALIDARG }; if kind != 0 { return S_OK; @@ -2061,4 +2061,44 @@ mod tests { assert!(!queried.is_null()); } } + + #[test] + fn vtable_shim_unwinds_cleanly_for_xerror_and_xpackage() { + let _g = crate::hle::xgameruntime::xasync::ASYNC_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + + struct ResetErrorCb; + impl Drop for ResetErrorCb { + fn drop(&mut self) { + unsafe { error_set_callback(0, std::ptr::null_mut()) }; + } + } + + unsafe extern "system-unwind" fn throwing_error_cb(_hr: HRESULT, _msg: *const u8, _ctx: *mut c_void) -> bool { + panic!("guest XError callback unwind"); + } + + unsafe extern "system-unwind" fn throwing_pkg_cb(_ctx: *mut c_void, _details: *const PackageDetails) -> bool { + panic!("guest XPackageEnumeratePackages callback unwind"); + } + + let _reset = ResetErrorCb; + unsafe { + // (a) XError COM vtable shim (slot 3 -> XErrorReport -> guest callback). + let (hr, err) = query(XERROR, XERROR); + assert_eq!(hr, S_OK); + let report: unsafe extern "system-unwind" fn(*mut c_void, HRESULT, *const u8) = slot(err, 3); + let set_cb: unsafe extern "system" fn(*mut c_void, usize, *mut c_void) = slot(err, 4); + set_cb(err, throwing_error_cb as usize, std::ptr::null_mut()); + let r1 = std::panic::catch_unwind(|| report(err, crate::util::E_FAIL, b"unwind test\0".as_ptr())); + assert!(r1.is_err(), "XError COM vtable shim must propagate unwind from guest callback"); + assert!(ERROR_CB.lock().is_ok(), "ERROR_CB mutex must remain unpoisoned after unwind"); + + // (b) XPackage COM vtable shim (V1 slot 28 -> XPackageEnumeratePackages -> guest callback). + let (hr, pkg) = query(XPACKAGE, XPACKAGE_V1_IID); + assert_eq!(hr, S_OK); + let enum_pkgs: unsafe extern "system-unwind" fn(*mut c_void, u32, u32, *mut c_void, Option bool>) -> HRESULT = slot(pkg, 28); + let r2 = std::panic::catch_unwind(|| enum_pkgs(pkg, 0, 0, std::ptr::null_mut(), Some(throwing_pkg_cb))); + assert!(r2.is_err(), "XPackage COM vtable shim must propagate unwind from guest callback"); + } + } } diff --git a/crates/xcl/src/hle/xgameruntime/gamesave.rs b/crates/xcl/src/hle/xgameruntime/gamesave.rs index e529c18..ca9bdc9 100644 --- a/crates/xcl/src/hle/xgameruntime/gamesave.rs +++ b/crates/xcl/src/hle/xgameruntime/gamesave.rs @@ -66,8 +66,8 @@ pub struct Blob { pub data: *mut u8, } -type ContainerCb = unsafe extern "system" fn(*const ContainerInfo, *mut c_void) -> bool; -type BlobCb = unsafe extern "system" fn(*const BlobInfo, *mut c_void) -> bool; +type ContainerCb = unsafe extern "system-unwind" fn(*const ContainerInfo, *mut c_void) -> bool; +type BlobCb = unsafe extern "system-unwind" fn(*const BlobInfo, *mut c_void) -> bool; /// File-name form of a container / blob name: unusual characters as %XX. fn enc(name: &str) -> String { @@ -198,12 +198,12 @@ pub unsafe extern "system" fn XGameSaveInitializeProvider(_user: *mut c_void, co static INIT_ID: u8 = 0; -pub unsafe extern "system" fn XGameSaveInitializeProviderAsync(_user: *mut c_void, config: *const u8, _sync: bool, b: *mut XAsyncBlock) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveInitializeProviderAsync(_user: *mut c_void, config: *const u8, _sync: bool, b: *mut XAsyncBlock) -> HRESULT { let config = from_cstr_ptr(config); begin_with(b, &INIT_ID as *const u8 as usize, move || Ok((open_provider(config) as usize).to_le_bytes().to_vec())) } -pub unsafe extern "system" fn XGameSaveInitializeProviderResult(b: *mut XAsyncBlock, out: *mut *mut Provider) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveInitializeProviderResult(b: *mut XAsyncBlock, out: *mut *mut Provider) -> HRESULT { if out.is_null() { return E_INVALIDARG; } @@ -241,13 +241,13 @@ pub unsafe extern "system" fn XGameSaveGetRemainingQuota(p: *mut Provider, quota static QUOTA_ID: u8 = 0; -pub unsafe extern "system" fn XGameSaveGetRemainingQuotaAsync(p: *mut Provider, b: *mut XAsyncBlock) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveGetRemainingQuotaAsync(p: *mut Provider, b: *mut XAsyncBlock) -> HRESULT { let mut q = 0i64; let hr = XGameSaveGetRemainingQuota(p, &mut q); begin_with(b, "A_ID as *const u8 as usize, move || if hr < 0 { Err(hr) } else { Ok(q.to_le_bytes().to_vec()) }) } -pub unsafe extern "system" fn XGameSaveGetRemainingQuotaResult(b: *mut XAsyncBlock, quota: *mut i64) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveGetRemainingQuotaResult(b: *mut XAsyncBlock, quota: *mut i64) -> HRESULT { XAsyncGetResult(b, "A_ID as *const u8 as *const c_void, 8, quota as *mut c_void, std::ptr::null_mut()) } @@ -284,7 +284,7 @@ pub unsafe extern "system" fn XGameSaveDeleteContainer(p: *mut Provider, name: * static DELETE_ID: u8 = 0; -pub unsafe extern "system" fn XGameSaveDeleteContainerAsync(p: *mut Provider, name: *const u8, b: *mut XAsyncBlock) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveDeleteContainerAsync(p: *mut Provider, name: *const u8, b: *mut XAsyncBlock) -> HRESULT { if b.is_null() { return E_INVALIDARG; } @@ -360,7 +360,7 @@ unsafe fn each_container(pr: &Provider, prefix: &str, exact: bool, ctx: *mut c_v n } -pub unsafe extern "system" fn XGameSaveGetContainerInfo(p: *mut Provider, name: *const u8, ctx: *mut c_void, cb: Option) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveGetContainerInfo(p: *mut Provider, name: *const u8, ctx: *mut c_void, cb: Option) -> HRESULT { let (Some(pr), Some(n), Some(cb)) = (provider(p), from_cstr_ptr(name), cb) else { return E_INVALIDARG }; if each_container(pr, &n, true, ctx, cb) == 0 { return E_GS_CONTAINER_NOT_FOUND; @@ -368,13 +368,13 @@ pub unsafe extern "system" fn XGameSaveGetContainerInfo(p: *mut Provider, name: S_OK } -pub unsafe extern "system" fn XGameSaveEnumerateContainerInfo(p: *mut Provider, ctx: *mut c_void, cb: Option) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveEnumerateContainerInfo(p: *mut Provider, ctx: *mut c_void, cb: Option) -> HRESULT { let (Some(pr), Some(cb)) = (provider(p), cb) else { return E_INVALIDARG }; each_container(pr, "", false, ctx, cb); S_OK } -pub unsafe extern "system" fn XGameSaveEnumerateContainerInfoByName(p: *mut Provider, prefix: *const u8, ctx: *mut c_void, cb: Option) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveEnumerateContainerInfoByName(p: *mut Provider, prefix: *const u8, ctx: *mut c_void, cb: Option) -> HRESULT { let (Some(pr), Some(cb)) = (provider(p), cb) else { return E_INVALIDARG }; each_container(pr, &from_cstr_ptr(prefix).unwrap_or_default(), false, ctx, cb); S_OK @@ -392,13 +392,13 @@ unsafe fn each_blob(c: &Container, prefix: &str, ctx: *mut c_void, cb: BlobCb) { } } -pub unsafe extern "system" fn XGameSaveEnumerateBlobInfo(c: *mut Container, ctx: *mut c_void, cb: Option) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveEnumerateBlobInfo(c: *mut Container, ctx: *mut c_void, cb: Option) -> HRESULT { let (Some(c), Some(cb)) = (container(c), cb) else { return E_INVALIDARG }; each_blob(c, "", ctx, cb); S_OK } -pub unsafe extern "system" fn XGameSaveEnumerateBlobInfoByName(c: *mut Container, prefix: *const u8, ctx: *mut c_void, cb: Option) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveEnumerateBlobInfoByName(c: *mut Container, prefix: *const u8, ctx: *mut c_void, cb: Option) -> HRESULT { let (Some(c), Some(cb)) = (container(c), cb) else { return E_INVALIDARG }; each_blob(c, &from_cstr_ptr(prefix).unwrap_or_default(), ctx, cb); S_OK @@ -482,7 +482,7 @@ pub unsafe extern "system" fn XGameSaveReadBlobData(c: *mut Container, names: *c static READ_ID: u8 = 0; -pub unsafe extern "system" fn XGameSaveReadBlobDataAsync(c: *mut Container, names: *const *const u8, count: u32, b: *mut XAsyncBlock) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveReadBlobDataAsync(c: *mut Container, names: *const *const u8, count: u32, b: *mut XAsyncBlock) -> HRESULT { let Some(c) = container(c) else { return E_INVALIDARG }; let Ok(list) = names_of(names, count) else { return E_INVALIDARG }; let dir = c.dir.clone(); @@ -493,7 +493,7 @@ pub unsafe extern "system" fn XGameSaveReadBlobDataAsync(c: *mut Container, name }) } -pub unsafe extern "system" fn XGameSaveReadBlobDataResult(b: *mut XAsyncBlock, size: usize, out: *mut Blob, count: *mut u32) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveReadBlobDataResult(b: *mut XAsyncBlock, size: usize, out: *mut Blob, count: *mut u32) -> HRESULT { let mut need = 0usize; let hr = XAsyncGetResultSize(b, &mut need); if hr < 0 { @@ -596,7 +596,7 @@ pub unsafe extern "system" fn XGameSaveSubmitUpdate(u: *mut Update) -> HRESULT { static SUBMIT_ID: u8 = 0; -pub unsafe extern "system" fn XGameSaveSubmitUpdateAsync(u: *mut Update, b: *mut XAsyncBlock) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveSubmitUpdateAsync(u: *mut Update, b: *mut XAsyncBlock) -> HRESULT { let Some(u) = update(u) else { return E_INVALIDARG }; let (dir, display, ops) = (u.dir.clone(), u.display.clone(), u.ops.clone()); begin_with(b, &SUBMIT_ID as *const u8 as usize, move || match apply(&dir, display.as_deref(), &ops) { @@ -605,7 +605,7 @@ pub unsafe extern "system" fn XGameSaveSubmitUpdateAsync(u: *mut Update, b: *mut }) } -pub unsafe extern "system" fn XGameSaveSubmitUpdateResult(b: *mut XAsyncBlock) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveSubmitUpdateResult(b: *mut XAsyncBlock) -> HRESULT { XAsyncGetResult(b, &SUBMIT_ID as *const u8 as *const c_void, 0, std::ptr::null_mut(), std::ptr::null_mut()) } @@ -745,7 +745,7 @@ mod tests { assert!(fixture.root.is_dir()); } - unsafe extern "system" fn count_containers(i: *const ContainerInfo, ctx: *mut c_void) -> bool { + unsafe extern "system-unwind" fn count_containers(i: *const ContainerInfo, ctx: *mut c_void) -> bool { let v = &mut *(ctx as *mut Vec<(String, String, u32, u64)>); let i = &*i; v.push((from_cstr_ptr(i.name).unwrap(), from_cstr_ptr(i.display_name).unwrap(), i.blob_count, i.total_size)); @@ -812,7 +812,7 @@ mod tests { } } - unsafe extern "system" fn blob_names(i: *const BlobInfo, ctx: *mut c_void) -> bool { + unsafe extern "system-unwind" fn blob_names(i: *const BlobInfo, ctx: *mut c_void) -> bool { (*(ctx as *mut Vec<(String, u32)>)).push((from_cstr_ptr((*i).name).unwrap(), (*i).size)); true } diff --git a/crates/xcl/src/hle/xgameruntime/mod.rs b/crates/xcl/src/hle/xgameruntime/mod.rs index c4dac5a..dcf02eb 100644 --- a/crates/xcl/src/hle/xgameruntime/mod.rs +++ b/crates/xcl/src/hle/xgameruntime/mod.rs @@ -476,7 +476,7 @@ pub unsafe extern "system" fn XPersistentLocalStorageGetSpaceInfo(info: *mut XPe static SAVE_FILES_IDENTITY: u8 = 0; -pub unsafe extern "system" fn XGameSaveFilesGetFolderWithUiAsync(_user: *mut c_void, scid: *const u8, b: *mut XAsyncBlock) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveFilesGetFolderWithUiAsync(_user: *mut c_void, scid: *const u8, b: *mut XAsyncBlock) -> HRESULT { let scid = crate::util::from_cstr_ptr(scid).unwrap_or_else(|| "default".into()); let safe: String = scid.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' { c } else { '_' }).collect(); begin_with(b, &SAVE_FILES_IDENTITY as *const u8 as usize, move || { @@ -488,7 +488,7 @@ pub unsafe extern "system" fn XGameSaveFilesGetFolderWithUiAsync(_user: *mut c_v }) } -pub unsafe extern "system" fn XGameSaveFilesGetFolderWithUiResult(b: *mut XAsyncBlock, size: usize, buf: *mut u8) -> HRESULT { +pub unsafe extern "system-unwind" fn XGameSaveFilesGetFolderWithUiResult(b: *mut XAsyncBlock, size: usize, buf: *mut u8) -> HRESULT { XAsyncGetResult(b, &SAVE_FILES_IDENTITY as *const u8 as *const c_void, size, buf as *mut c_void, std::ptr::null_mut()) } @@ -514,7 +514,7 @@ unsafe fn valid_user(h: *mut c_void) -> bool { h == user_ptr() } -pub unsafe extern "system" fn XUserAddAsync(options: u32, b: *mut XAsyncBlock) -> HRESULT { +pub unsafe extern "system-unwind" fn XUserAddAsync(options: u32, b: *mut XAsyncBlock) -> HRESULT { crate::xlog_info!("XUserAddAsync(options={options:#x}) → local offline user '{}'", crate::state::config().gamertag); begin_with(b, &USER_ADD_IDENTITY as *const u8 as usize, || { USER.refs.fetch_add(1, Ordering::AcqRel); @@ -522,7 +522,7 @@ pub unsafe extern "system" fn XUserAddAsync(options: u32, b: *mut XAsyncBlock) - }) } -pub unsafe extern "system" fn XUserAddResult(b: *mut XAsyncBlock, out: *mut *mut c_void) -> HRESULT { +pub unsafe extern "system-unwind" fn XUserAddResult(b: *mut XAsyncBlock, out: *mut *mut c_void) -> HRESULT { if out.is_null() { return E_INVALIDARG; } @@ -753,7 +753,7 @@ fn note_token_request(method: &str, url: &str) -> Result<(), HRESULT> { } } -pub unsafe extern "system" fn XUserGetTokenAndSignatureAsync( +pub unsafe extern "system-unwind" fn XUserGetTokenAndSignatureAsync( user: *mut c_void, _options: u32, method: *const u8, @@ -781,7 +781,7 @@ pub unsafe extern "system" fn XUserGetTokenAndSignatureResultSize(b: *mut XAsync XAsyncGetResultSize(b, size) } -pub unsafe extern "system" fn XUserGetTokenAndSignatureResult( +pub unsafe extern "system-unwind" fn XUserGetTokenAndSignatureResult( b: *mut XAsyncBlock, buffer_size: usize, buffer: *mut c_void, @@ -795,7 +795,7 @@ pub unsafe extern "system" fn XUserGetTokenAndSignatureResult( hr } -pub unsafe extern "system" fn XUserGetTokenAndSignatureUtf16Async( +pub unsafe extern "system-unwind" fn XUserGetTokenAndSignatureUtf16Async( user: *mut c_void, _options: u32, method: *const u16, @@ -823,7 +823,7 @@ pub unsafe extern "system" fn XUserGetTokenAndSignatureUtf16ResultSize(b: *mut X XAsyncGetResultSize(b, size) } -pub unsafe extern "system" fn XUserGetTokenAndSignatureUtf16Result( +pub unsafe extern "system-unwind" fn XUserGetTokenAndSignatureUtf16Result( b: *mut XAsyncBlock, buffer_size: usize, buffer: *mut c_void, @@ -864,9 +864,9 @@ struct AssociationCall { change: DeviceAssociationChange, } -unsafe extern "system" fn association_call(rec: *mut c_void, _canceled: bool) { +unsafe extern "system-unwind" fn association_call(rec: *mut c_void, _canceled: bool) { let r = Box::from_raw(rec as *mut AssociationCall); - let f: unsafe extern "system" fn(*mut c_void, *const DeviceAssociationChange) = std::mem::transmute(r.cb); + let f: unsafe extern "system-unwind" fn(*mut c_void, *const DeviceAssociationChange) = std::mem::transmute(r.cb); f(r.ctx as *mut c_void, &r.change); } @@ -888,7 +888,7 @@ unsafe fn notify_association(queue: usize, ctx: usize, cb: usize) { /// title hears of it here: Minecraft marks its controller "connected" only from this /// callback (device arrival alone just attaches the device to the user's player), and its /// Ore UI screens take gamepad input only from a connected controller. -pub unsafe extern "system" fn XUserRegisterForDeviceAssociationChanged(queue: *mut c_void, ctx: *mut c_void, cb: usize, token: *mut u64) -> HRESULT { +pub unsafe extern "system-unwind" fn XUserRegisterForDeviceAssociationChanged(queue: *mut c_void, ctx: *mut c_void, cb: usize, token: *mut u64) -> HRESULT { if token.is_null() || cb == 0 { return E_INVALIDARG; } @@ -932,14 +932,14 @@ pub unsafe extern "system" fn XUserFindForDevice(_device: *const c_void, out: *m S_OK } -pub unsafe extern "system" fn XUserFindControllerForUserWithUiAsync(user: *mut c_void, b: *mut XAsyncBlock) -> HRESULT { +pub unsafe extern "system-unwind" fn XUserFindControllerForUserWithUiAsync(user: *mut c_void, b: *mut XAsyncBlock) -> HRESULT { if !valid_user(user) { return E_INVALIDARG; } begin_with(b, &FIND_CONTROLLER_ID as *const u8 as usize, || Ok(crate::hle::gameinput::gamepad_device_id().to_vec())) } -pub unsafe extern "system" fn XUserFindControllerForUserWithUiResult(b: *mut XAsyncBlock, device_id: *mut [u8; 32]) -> HRESULT { +pub unsafe extern "system-unwind" fn XUserFindControllerForUserWithUiResult(b: *mut XAsyncBlock, device_id: *mut [u8; 32]) -> HRESULT { if device_id.is_null() { return E_INVALIDARG; } diff --git a/crates/xcl/src/hle/xgameruntime/networking.rs b/crates/xcl/src/hle/xgameruntime/networking.rs index 39e9078..1ed1272 100644 --- a/crates/xcl/src/hle/xgameruntime/networking.rs +++ b/crates/xcl/src/hle/xgameruntime/networking.rs @@ -72,11 +72,11 @@ pub unsafe extern "system" fn XNetworkingQueryPreferredLocalUdpMultiplayerPort(p S_OK } -pub unsafe extern "system" fn XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync(b: *mut XAsyncBlock) -> HRESULT { +pub unsafe extern "system-unwind" fn XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync(b: *mut XAsyncBlock) -> HRESULT { begin_with(b, &UDP_PORT_ID as *const u8 as usize, || Ok(DEFAULT_UDP_PORT.to_le_bytes().to_vec())) } -pub unsafe extern "system" fn XNetworkingQueryPreferredLocalUdpMultiplayerPortAsyncResult( +pub unsafe extern "system-unwind" fn XNetworkingQueryPreferredLocalUdpMultiplayerPortAsyncResult( b: *mut XAsyncBlock, port: *mut u16, ) -> HRESULT { @@ -119,7 +119,7 @@ fn default_security_info_bytes() -> Vec { out } -pub unsafe extern "system" fn XNetworkingQuerySecurityInformationForUrlAsync( +pub unsafe extern "system-unwind" fn XNetworkingQuerySecurityInformationForUrlAsync( url: *const u8, b: *mut XAsyncBlock, ) -> HRESULT { @@ -137,7 +137,7 @@ pub unsafe extern "system" fn XNetworkingQuerySecurityInformationForUrlAsyncResu } /// Note the GDK parameter order: `buffer_used` precedes `buffer` and `out_ptr`. -pub unsafe extern "system" fn XNetworkingQuerySecurityInformationForUrlAsyncResult( +pub unsafe extern "system-unwind" fn XNetworkingQuerySecurityInformationForUrlAsyncResult( b: *mut XAsyncBlock, buffer_size: usize, buffer_used: *mut usize, @@ -147,7 +147,7 @@ pub unsafe extern "system" fn XNetworkingQuerySecurityInformationForUrlAsyncResu security_info_result(&SEC_INFO_ID as *const u8 as *const c_void, b, buffer_size, buffer_used, buffer, out_ptr) } -pub unsafe extern "system" fn XNetworkingQuerySecurityInformationForUrlUtf16Async( +pub unsafe extern "system-unwind" fn XNetworkingQuerySecurityInformationForUrlUtf16Async( url: *const u16, b: *mut XAsyncBlock, ) -> HRESULT { @@ -164,7 +164,7 @@ pub unsafe extern "system" fn XNetworkingQuerySecurityInformationForUrlUtf16Asyn XAsyncGetResultSize(b, size) } -pub unsafe extern "system" fn XNetworkingQuerySecurityInformationForUrlUtf16AsyncResult( +pub unsafe extern "system-unwind" fn XNetworkingQuerySecurityInformationForUrlUtf16AsyncResult( b: *mut XAsyncBlock, buffer_size: usize, buffer_used: *mut usize, diff --git a/crates/xcl/src/hle/xgameruntime/taskqueue.rs b/crates/xcl/src/hle/xgameruntime/taskqueue.rs index e5565ad..ee4a52b 100644 --- a/crates/xcl/src/hle/xgameruntime/taskqueue.rs +++ b/crates/xcl/src/hle/xgameruntime/taskqueue.rs @@ -29,9 +29,9 @@ pub const PORT_WORK: u32 = 0; pub const PORT_COMPLETION: u32 = 1; pub const E_NO_TASK_QUEUE: HRESULT = 0x8007_01ABu32 as i32; -pub type XTaskQueueCallback = unsafe extern "system" fn(*mut c_void, bool); -pub type XTaskQueueTerminatedCallback = unsafe extern "system" fn(*mut c_void); -pub type XTaskQueueMonitorCallback = unsafe extern "system" fn(*mut c_void, *mut c_void, u32); +pub type XTaskQueueCallback = unsafe extern "system-unwind" fn(*mut c_void, bool); +pub type XTaskQueueTerminatedCallback = unsafe extern "system-unwind" fn(*mut c_void); +pub type XTaskQueueMonitorCallback = unsafe extern "system-unwind" fn(*mut c_void, *mut c_void, u32); #[derive(Clone, Copy)] pub struct Item { @@ -223,7 +223,7 @@ impl Queue { } fn done_one(&self, port: u32) { - let mut state = self.state.lock().unwrap(); + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); state.inflight[port as usize] -= 1; if state.inflight[0] == 0 && state.inflight[1] == 0 { self.idle_cv.notify_all(); @@ -231,9 +231,15 @@ impl Queue { } unsafe fn execute(self: &Arc, port: u32, item: Item) { + struct InflightGuard<'a>(&'a Queue, u32); + impl Drop for InflightGuard<'_> { + fn drop(&mut self) { + self.0.done_one(self.1); + } + } + let _done = InflightGuard(self, port); let canceled = self.is_terminated(); item.run(canceled); - self.done_one(port); } fn notify_monitors(&self, port: u32) { @@ -248,23 +254,37 @@ impl Queue { } fn drain_serialized(p: Arc) { + struct RunningGuard(Arc); + impl Drop for RunningGuard { + fn drop(&mut self) { + self.0.running.store(false, Ordering::Release); + // Re-check: an item may have arrived after pop (or remain after an unwind) + // before `running` cleared. + let more = !self.0.items.lock().unwrap_or_else(|e| e.into_inner()).is_empty(); + if more && !self.0.running.swap(true, Ordering::AcqRel) { + let p2 = self.0.clone(); + spawn(Box::new(move || drain_serialized(p2))); + } + } + } + let _running = RunningGuard(p.clone()); loop { - let next = p.items.lock().unwrap().pop_front(); + let next = p.items.lock().unwrap_or_else(|e| e.into_inner()).pop_front(); match next { Some(qi) => unsafe { qi.queue.execute(qi.port, qi.item) }, - None => { - p.running.store(false, Ordering::Release); - // re-check: an item may have arrived after pop but before the store - let more = !p.items.lock().unwrap().is_empty(); - if more && !p.running.swap(true, Ordering::AcqRel) { - continue; - } - break; - } + None => break, } } } +/// Decrements `inflight` if a monitor callback unwinds before execution/spawning claims it. +struct CancelInflight<'a>(&'a Queue, u32); +impl Drop for CancelInflight<'_> { + fn drop(&mut self) { + self.0.done_one(self.1); + } +} + /// Submit an item to `port` immediately. Returns `false` if `q` is already terminated. /// /// Lock order is always `p.items` (or `timer`) -> `q.state` so submission and `XTaskQueueTerminate` @@ -280,7 +300,9 @@ pub fn submit_now(q: &Arc, port: u32, item: Item) -> bool { } state.inflight[port as usize] += 1; } + let inflight = CancelInflight(q, port); q.notify_monitors(port); + std::mem::forget(inflight); // SAFETY: Caller guarantees `item.cb` is a valid `XTaskQueueCallback` for `item.ctx`. unsafe { q.execute(port, item) }; } @@ -292,9 +314,11 @@ pub fn submit_now(q: &Arc, port: u32, item: Item) -> bool { } state.inflight[port as usize] += 1; } + let inflight = CancelInflight(q, port); q.notify_monitors(port); let q2 = q.clone(); spawn(Box::new(move || unsafe { q2.execute(port, item) })); + std::mem::forget(inflight); } MODE_SERIALIZED_THREAD_POOL => { { @@ -308,11 +332,11 @@ pub fn submit_now(q: &Arc, port: u32, item: Item) -> bool { } items.push_back(QueuedItem { item, queue: q.clone(), port }); } - q.notify_monitors(port); if !p.running.swap(true, Ordering::AcqRel) { let p2 = p.clone(); spawn(Box::new(move || drain_serialized(p2))); } + q.notify_monitors(port); } _ => { { @@ -519,7 +543,7 @@ pub unsafe extern "system" fn XTaskQueueCloseHandle(h: *mut c_void) { } } -pub unsafe extern "system" fn XTaskQueueSubmitCallback(h: *mut c_void, port: u32, ctx: *mut c_void, cb: usize) -> HRESULT { +pub unsafe extern "system-unwind" fn XTaskQueueSubmitCallback(h: *mut c_void, port: u32, ctx: *mut c_void, cb: usize) -> HRESULT { if cb == 0 || port > 1 { return E_INVALIDARG; } @@ -530,7 +554,7 @@ pub unsafe extern "system" fn XTaskQueueSubmitCallback(h: *mut c_void, port: u32 S_OK } -pub unsafe extern "system" fn XTaskQueueSubmitDelayedCallback(h: *mut c_void, port: u32, delay: u32, ctx: *mut c_void, cb: usize) -> HRESULT { +pub unsafe extern "system-unwind" fn XTaskQueueSubmitDelayedCallback(h: *mut c_void, port: u32, delay: u32, ctx: *mut c_void, cb: usize) -> HRESULT { if cb == 0 || port > 1 { return E_INVALIDARG; } @@ -543,7 +567,7 @@ pub unsafe extern "system" fn XTaskQueueSubmitDelayedCallback(h: *mut c_void, po S_OK } -pub unsafe extern "system" fn XTaskQueueDispatch(h: *mut c_void, port: u32, timeout: u32) -> bool { +pub unsafe extern "system-unwind" fn XTaskQueueDispatch(h: *mut c_void, port: u32, timeout: u32) -> bool { if port > 1 { return false; } @@ -564,30 +588,39 @@ pub unsafe extern "system" fn XTaskQueueIsEmpty(h: *mut c_void, port: u32) -> bo } } -pub unsafe extern "system" fn XTaskQueueTerminate(h: *mut c_void, wait: bool, ctx: *mut c_void, cb: usize) -> HRESULT { +pub unsafe extern "system-unwind" fn XTaskQueueTerminate(h: *mut c_void, wait: bool, ctx: *mut c_void, cb: usize) -> HRESULT { let Some(q) = queue_from(h) else { return E_INVALIDARG }; q.state.lock().unwrap().terminated = true; // Cancel only queued items submitted through `q`; sibling queues sharing a composite port - // keep their pending work untouched. Wake any manual-port dispatchers waiting on this port. + // keep their pending work untouched. Drain both ports and wake any manual-port dispatchers + // on both ports before running any canceled callback so an unwind during a `PORT_WORK` + // callback still drains `PORT_COMPLETION` and never strands `PORT_COMPLETION` waiters. + struct Remaining(VecDeque); + impl Drop for Remaining { + fn drop(&mut self) { + for qi in self.0.drain(..) { + qi.queue.done_one(qi.port); + } + } + } + let mut mine = Remaining(VecDeque::new()); for port in 0..2 { - let mine = { + { let mut items = q.ports[port].items.lock().unwrap(); - let mut mine = Vec::new(); let mut keep = VecDeque::with_capacity(items.len()); while let Some(qi) = items.pop_front() { if Arc::ptr_eq(&qi.queue, &q) { - mine.push(qi); + mine.0.push_back(qi); } else { keep.push_back(qi); } } *items = keep; - mine - }; - q.ports[port].cv.notify_all(); - for qi in mine { - qi.queue.execute(qi.port, qi.item); } + q.ports[port].cv.notify_all(); + } + while let Some(qi) = mine.0.pop_front() { + qi.queue.execute(qi.port, qi.item); } // Delayed callbacks of `q` still waiting for their time are canceled too, before the // termination callback (libHttpClient: CancelPendingEntries when a port terminates). They @@ -1101,4 +1134,102 @@ mod tests { XTaskQueueCloseHandle(h); } } + + #[test] + fn callbacks_unwind_cleanly_and_release_inflight_count() { + unsafe extern "system-unwind" fn throwing_cb(_ctx: *mut c_void, _canceled: bool) { + panic!("guest XTaskQueue callback unwind"); + } + unsafe extern "system-unwind" fn throwing_monitor(_ctx: *mut c_void, _q: *mut c_void, _port: u32) { + panic!("guest XTaskQueue monitor unwind"); + } + unsafe extern "system-unwind" fn throwing_term(_ctx: *mut c_void) { + panic!("guest XTaskQueue terminated callback unwind"); + } + unsafe extern "system-unwind" fn noop(_ctx: *mut c_void, _canceled: bool) {} + + unsafe { + // (a) MODE_MANUAL: unwind through XTaskQueueDispatch drops InflightGuard so Terminate doesn't deadlock. + let mut h = std::ptr::null_mut(); + assert_eq!(XTaskQueueCreate(MODE_MANUAL, MODE_MANUAL, &mut h), S_OK); + assert_eq!(XTaskQueueSubmitCallback(h, PORT_WORK, std::ptr::null_mut(), throwing_cb as usize), S_OK); + assert!(!XTaskQueueIsEmpty(h, PORT_WORK)); + let r = std::panic::catch_unwind(|| XTaskQueueDispatch(h, PORT_WORK, 0)); + assert!(r.is_err(), "XTaskQueueDispatch must propagate unwind from guest callback"); + assert!(XTaskQueueIsEmpty(h, PORT_WORK), "InflightGuard must decrement inflight count on unwind"); + assert_eq!(XTaskQueueTerminate(h, true, std::ptr::null_mut(), 0), S_OK); + XTaskQueueCloseHandle(h); + + // (b) MODE_IMMEDIATE: unwind through XTaskQueueSubmitCallback releases inflight count. + let mut h2 = std::ptr::null_mut(); + assert_eq!(XTaskQueueCreate(MODE_IMMEDIATE, MODE_IMMEDIATE, &mut h2), S_OK); + let r2 = std::panic::catch_unwind(|| { + XTaskQueueSubmitCallback(h2, PORT_WORK, std::ptr::null_mut(), throwing_cb as usize) + }); + assert!(r2.is_err(), "XTaskQueueSubmitCallback(MODE_IMMEDIATE) must propagate unwind"); + assert!(XTaskQueueIsEmpty(h2, PORT_WORK)); + // Monitor callback unwinding on MODE_IMMEDIATE must also release the inflight reservation. + let mut mon_tok = RegistrationToken { token: 0 }; + assert_eq!(XTaskQueueRegisterMonitor(h2, std::ptr::null_mut(), throwing_monitor as usize, &mut mon_tok), S_OK); + let r3 = std::panic::catch_unwind(|| { + XTaskQueueSubmitCallback(h2, PORT_WORK, std::ptr::null_mut(), noop as usize) + }); + assert!(r3.is_err(), "XTaskQueueMonitorCallback unwind must propagate cleanly"); + assert!(XTaskQueueIsEmpty(h2, PORT_WORK), "CancelInflight must decrement inflight count when monitor unwinds"); + XTaskQueueUnregisterMonitor(h2, mon_tok); + // Terminated callback unwinding through XTaskQueueTerminate(wait=true) must also propagate cleanly. + let r4 = std::panic::catch_unwind(|| { + XTaskQueueTerminate(h2, true, std::ptr::null_mut(), throwing_term as usize) + }); + assert!(r4.is_err(), "XTaskQueueTerminate(wait=true) must propagate unwind from terminated callback"); + XTaskQueueCloseHandle(h2); + } + } + + #[test] + fn terminate_work_unwind_still_drains_completion_and_wakes_waiters() { + use std::sync::mpsc; + + unsafe extern "system-unwind" fn throwing_cb(_ctx: *mut c_void, _canceled: bool) { + panic!("guest canceled PORT_WORK unwind"); + } + unsafe extern "system-unwind" fn noop(_ctx: *mut c_void, _canceled: bool) {} + + unsafe { + // (a) Unwind during a canceled PORT_WORK callback still drains PORT_COMPLETION and + // releases inflight counts for both ports. + let mut h1 = std::ptr::null_mut(); + assert_eq!(XTaskQueueCreate(MODE_MANUAL, MODE_MANUAL, &mut h1), S_OK); + assert_eq!(XTaskQueueSubmitCallback(h1, PORT_WORK, std::ptr::null_mut(), throwing_cb as usize), S_OK); + assert_eq!(XTaskQueueSubmitCallback(h1, PORT_COMPLETION, std::ptr::null_mut(), noop as usize), S_OK); + let r1 = std::panic::catch_unwind(|| XTaskQueueTerminate(h1, true, std::ptr::null_mut(), 0)); + assert!(r1.is_err()); + assert!(XTaskQueueIsEmpty(h1, PORT_WORK), "PORT_WORK must be empty after terminate unwind"); + assert!(XTaskQueueIsEmpty(h1, PORT_COMPLETION), "PORT_COMPLETION must be drained even when PORT_WORK unwinds"); + XTaskQueueCloseHandle(h1); + + // (b) A manual dispatcher blocked in XTaskQueueDispatch(PORT_COMPLETION, INFINITE) + // must still be woken even when a canceled PORT_WORK callback unwinds. + let mut h2 = std::ptr::null_mut(); + assert_eq!(XTaskQueueCreate(MODE_MANUAL, MODE_MANUAL, &mut h2), S_OK); + assert_eq!(XTaskQueueSubmitCallback(h2, PORT_WORK, std::ptr::null_mut(), throwing_cb as usize), S_OK); + let h2_addr = h2 as usize; + let (tx, rx) = mpsc::channel(); + let dispatcher = std::thread::spawn(move || { + let ran = XTaskQueueDispatch(h2_addr as *mut c_void, PORT_COMPLETION, u32::MAX); + let _ = tx.send(ran); + }); + std::thread::sleep(Duration::from_millis(10)); + let r2 = std::panic::catch_unwind(|| XTaskQueueTerminate(h2, true, std::ptr::null_mut(), 0)); + assert!(r2.is_err()); + let ran = rx + .recv_timeout(Duration::from_secs(2)) + .expect("PORT_COMPLETION dispatcher hung after PORT_WORK unwind in XTaskQueueTerminate"); + dispatcher.join().unwrap(); + assert!(!ran); + assert!(XTaskQueueIsEmpty(h2, PORT_WORK)); + assert!(XTaskQueueIsEmpty(h2, PORT_COMPLETION)); + XTaskQueueCloseHandle(h2); + } + } } diff --git a/crates/xcl/src/hle/xgameruntime/xasync.rs b/crates/xcl/src/hle/xgameruntime/xasync.rs index d358dc5..3ecab46 100644 --- a/crates/xcl/src/hle/xgameruntime/xasync.rs +++ b/crates/xcl/src/hle/xgameruntime/xasync.rs @@ -16,7 +16,7 @@ use std::collections::HashMap; use std::ffi::c_void; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, OnceLock}; use super::taskqueue::{self, Item, PORT_COMPLETION, PORT_WORK}; @@ -50,7 +50,7 @@ pub struct XAsyncProviderData { pub context: *mut c_void, } -pub type XAsyncProvider = unsafe extern "system" fn(u32, *const XAsyncProviderData) -> HRESULT; +pub type XAsyncProvider = unsafe extern "system-unwind" fn(u32, *const XAsyncProviderData) -> HRESULT; /// The PC runtime's XAsync / XTaskQueue object (0 = XCL's own queues). Its slots: 3 GetStatus, /// 4 GetResultSize, 5 Cancel, 6 Run, 7 Begin, 9 Schedule, 10 Complete, 11 GetResult. @@ -74,14 +74,14 @@ unsafe fn pc(slot: usize) -> Option<(usize, usize)> { /// XAsync object when in use – its queue handles mean nothing to XCL's – else XCL's). pub unsafe fn submit_callback(queue: *mut c_void, port: u32, ctx: *mut c_void, cb: usize) -> HRESULT { if let Some((o, f)) = pc(18) { - let f: unsafe extern "system" fn(usize, *mut c_void, u32, *mut c_void, usize) -> HRESULT = std::mem::transmute(f); + let f: unsafe extern "system-unwind" fn(usize, *mut c_void, u32, *mut c_void, usize) -> HRESULT = std::mem::transmute(f); return f(o, queue, port, ctx, cb); } super::taskqueue::XTaskQueueSubmitCallback(queue, port, ctx, cb) } -pub type XAsyncWork = unsafe extern "system" fn(*mut XAsyncBlock) -> HRESULT; -type Completion = unsafe extern "system" fn(*mut XAsyncBlock); +pub type XAsyncWork = unsafe extern "system-unwind" fn(*mut XAsyncBlock) -> HRESULT; +type Completion = unsafe extern "system-unwind" fn(*mut XAsyncBlock); #[derive(Clone, Copy, PartialEq, Eq)] enum Phase { @@ -116,6 +116,9 @@ pub struct State { identity: usize, /// For XAsyncRun. work: usize, + /// Keeps XCL's `begin_with` / `begin_with_fixups` payload alive as long as any `Arc` + /// exists (eliminating concurrent/unwind UAF when `PC_ASYNC == 0`). + _owned_payload: Option>, inner: Mutex, cv: Condvar, } @@ -195,7 +198,7 @@ unsafe fn call_provider(s: &State, op: u32, b: *mut XAsyncBlock, buffer: *mut c_ f(op, &data) } -unsafe extern "system" fn do_work_cb(ctx: *mut c_void, canceled: bool) { +unsafe extern "system-unwind" fn do_work_cb(ctx: *mut c_void, canceled: bool) { let b = ctx as *mut XAsyncBlock; let Lookup::Active(s) = lookup(b) else { return }; if canceled { @@ -217,7 +220,7 @@ unsafe extern "system" fn do_work_cb(ctx: *mut c_void, canceled: bool) { } } -unsafe extern "system" fn completion_cb(ctx: *mut c_void, _canceled: bool) { +unsafe extern "system-unwind" fn completion_cb(ctx: *mut c_void, _canceled: bool) { let b = ctx as *mut XAsyncBlock; if (*b).callback != 0 { let f: Completion = std::mem::transmute((*b).callback); @@ -225,17 +228,52 @@ unsafe extern "system" fn completion_cb(ctx: *mut c_void, _canceled: bool) { } } -pub unsafe extern "system" fn XAsyncBegin( +/// Removes `b` from `ACTIVE` and marks it aborted/consumed (waking any waiters) if `OP_BEGIN` +/// or `XAsyncSchedule` unwinds while the block is still `Phase::Pending`. If the block already +/// completed synchronously before unwinding (e.g. `Phase::Done` with payload), it is left intact. +struct BeginCleanup { + b: *mut XAsyncBlock, + s: Arc, + armed: bool, +} + +impl Drop for BeginCleanup { + fn drop(&mut self) { + if !self.armed { + return; + } + let woke = { + let mut map = active_map().lock().unwrap_or_else(|e| e.into_inner()); + let mut g = self.s.inner.lock().unwrap_or_else(|e| e.into_inner()); + if g.phase == Phase::Pending { + if map.get(&(self.b as usize)).is_some_and(|cur| cur.id == self.s.id) { + map.remove(&(self.b as usize)); + } + unsafe { + write_header(self.b, BlockHeader { status: E_ABORT, flags: FLAG_DONE | FLAG_CONSUMED, id: self.s.id }); + } + g.status = E_ABORT; + g.result_size = 0; + g.phase = Phase::Consumed; + true + } else { + false + } + }; + if woke { + self.s.cv.notify_all(); + } + } +} + +unsafe fn xasync_begin_inner( b: *mut XAsyncBlock, context: *mut c_void, identity: *const c_void, _identity_name: *const u8, provider: usize, + owned_payload: Option>, ) -> HRESULT { - if let Some((o, f)) = pc(7) { - let f: unsafe extern "system" fn(usize, *mut XAsyncBlock, *mut c_void, *const c_void, *const u8, usize) -> HRESULT = std::mem::transmute(f); - return f(o, b, context, identity, _identity_name, provider); - } if b.is_null() || provider == 0 { return E_INVALIDARG; } @@ -245,22 +283,39 @@ pub unsafe extern "system" fn XAsyncBegin( context: context as usize, identity: identity as usize, work: 0, + _owned_payload: owned_payload, inner: Mutex::new(Inner { status: E_PENDING, result_size: 0, phase: Phase::Pending }), cv: Condvar::new(), }); register_state(b, s.clone()); + let mut cleanup = BeginCleanup { b, s: s.clone(), armed: true }; // A failing Begin fails the async call, not XAsyncBegin (libHttpClient): the caller gets // the error once, through the block, and not also as this return value. let hr = call_provider(&s, OP_BEGIN, b, std::ptr::null_mut(), 0); + cleanup.armed = false; if hr < 0 { XAsyncComplete(b, hr, 0); } S_OK } -pub unsafe extern "system" fn XAsyncSchedule(b: *mut XAsyncBlock, delay_ms: u32) -> HRESULT { +pub unsafe extern "system-unwind" fn XAsyncBegin( + b: *mut XAsyncBlock, + context: *mut c_void, + identity: *const c_void, + identity_name: *const u8, + provider: usize, +) -> HRESULT { + if let Some((o, f)) = pc(7) { + let f: unsafe extern "system-unwind" fn(usize, *mut XAsyncBlock, *mut c_void, *const c_void, *const u8, usize) -> HRESULT = std::mem::transmute(f); + return f(o, b, context, identity, identity_name, provider); + } + xasync_begin_inner(b, context, identity, identity_name, provider, None) +} + +pub unsafe extern "system-unwind" fn XAsyncSchedule(b: *mut XAsyncBlock, delay_ms: u32) -> HRESULT { if let Some((o, f)) = pc(9) { - let f: unsafe extern "system" fn(usize, *mut XAsyncBlock, u32) -> HRESULT = std::mem::transmute(f); + let f: unsafe extern "system-unwind" fn(usize, *mut XAsyncBlock, u32) -> HRESULT = std::mem::transmute(f); return f(o, b, delay_ms); } if b.is_null() { @@ -276,9 +331,9 @@ pub unsafe extern "system" fn XAsyncSchedule(b: *mut XAsyncBlock, delay_ms: u32) S_OK } -pub unsafe extern "system" fn XAsyncComplete(b: *mut XAsyncBlock, result: HRESULT, required: usize) { +pub unsafe extern "system-unwind" fn XAsyncComplete(b: *mut XAsyncBlock, result: HRESULT, required: usize) { if let Some((o, f)) = pc(10) { - let f: unsafe extern "system" fn(usize, *mut XAsyncBlock, HRESULT, usize) = std::mem::transmute(f); + let f: unsafe extern "system-unwind" fn(usize, *mut XAsyncBlock, HRESULT, usize) = std::mem::transmute(f); return f(o, b, result, required); } // E_PENDING is not a completion: the provider still has work to do (libHttpClient). @@ -303,9 +358,36 @@ pub unsafe extern "system" fn XAsyncComplete(b: *mut XAsyncBlock, result: HRESUL // Snapshot callback/queue before publishing completion so a waiter woken from // `XAsyncGetStatus(b, true)` can safely destroy a stack-allocated `XAsyncBlock`. let (cb, queue_ptr) = ((*b).callback, (*b).queue); + // If guest `OP_CLEANUP` unwinds, finalize `FLAG_DONE`, remove `b` from `ACTIVE`, move to + // `Phase::Consumed`, and wake any `XAsyncGetStatus(_, true)` waiters. + struct CompleteCleanup<'a> { + b: *mut XAsyncBlock, + s: &'a State, + status: HRESULT, + armed: bool, + } + impl Drop for CompleteCleanup<'_> { + fn drop(&mut self) { + if !self.armed { + return; + } + { + let mut map = active_map().lock().unwrap_or_else(|e| e.into_inner()); + unsafe { write_header(self.b, BlockHeader { status: self.status, flags: FLAG_DONE, id: self.s.id }) }; + if map.get(&(self.b as usize)).is_some_and(|cur| cur.id == self.s.id) { + map.remove(&(self.b as usize)); + } + let mut g = self.s.inner.lock().unwrap_or_else(|e| e.into_inner()); + g.phase = Phase::Consumed; + } + self.s.cv.notify_all(); + } + } + let mut complete_guard = CompleteCleanup { b, s: &s, status, armed: true }; if cleanup_now { call_provider(&s, OP_CLEANUP, b, std::ptr::null_mut(), 0); } + complete_guard.armed = false; // Persist the finalized status into `b.internal` under `ACTIVE`, remove `s` if no payload // remains, and publish `Done`/`Consumed` (lock order: `ACTIVE` -> `s.inner`) before // submitting the completion callback or waking waiters. @@ -318,12 +400,18 @@ pub unsafe extern "system" fn XAsyncComplete(b: *mut XAsyncBlock, result: HRESUL let mut g = s.inner.lock().unwrap(); g.phase = if cleanup_now { Phase::Consumed } else { Phase::Done }; } + struct NotifyGuard<'a>(&'a Condvar); + impl Drop for NotifyGuard<'_> { + fn drop(&mut self) { + self.0.notify_all(); + } + } + let _notify = NotifyGuard(&s.cv); if cb != 0 { if let Some(q) = taskqueue::queue_from(queue_ptr) { let _ = taskqueue::submit_now(&q, PORT_COMPLETION, Item { cb: completion_cb as usize, ctx: b as usize }); } } - s.cv.notify_all(); } pub unsafe extern "system" fn XAsyncGetStatus(b: *mut XAsyncBlock, wait: bool) -> HRESULT { @@ -372,7 +460,7 @@ pub unsafe extern "system" fn XAsyncGetResultSize(b: *mut XAsyncBlock, size: *mu } } -pub unsafe extern "system" fn XAsyncGetResult( +pub unsafe extern "system-unwind" fn XAsyncGetResult( b: *mut XAsyncBlock, identity: *const c_void, size: usize, @@ -380,7 +468,7 @@ pub unsafe extern "system" fn XAsyncGetResult( used: *mut usize, ) -> HRESULT { if let Some((o, f)) = pc(11) { - let f: unsafe extern "system" fn(usize, *mut XAsyncBlock, *const c_void, usize, *mut c_void, *mut usize) -> HRESULT = std::mem::transmute(f); + let f: unsafe extern "system-unwind" fn(usize, *mut XAsyncBlock, *const c_void, usize, *mut c_void, *mut usize) -> HRESULT = std::mem::transmute(f); return f(o, b, identity, size, buffer, used); } match lookup(b) { @@ -422,11 +510,36 @@ pub unsafe extern "system" fn XAsyncGetResult( (g.status, g.result_size) }; if need > 0 { + // If guest `OP_GET_RESULT` or `OP_CLEANUP` unwinds, finalize `FLAG_CONSUMED` and + // remove `b` from `ACTIVE` without re-entering guest `OP_CLEANUP` during unwind. + struct ConsumeCleanup<'a> { + b: *mut XAsyncBlock, + s: &'a State, + status: HRESULT, + armed: bool, + } + impl Drop for ConsumeCleanup<'_> { + fn drop(&mut self) { + if !self.armed { + return; + } + let mut map = active_map().lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + write_header(self.b, BlockHeader { status: self.status, flags: FLAG_DONE | FLAG_CONSUMED, id: self.s.id }); + } + if map.get(&(self.b as usize)).is_some_and(|cur| cur.id == self.s.id) { + map.remove(&(self.b as usize)); + } + self.s.inner.lock().unwrap_or_else(|e| e.into_inner()).phase = Phase::Consumed; + } + } + let mut consume_guard = ConsumeCleanup { b, s: &s, status, armed: true }; let hr = call_provider(&s, OP_GET_RESULT, b, buffer, size); if !used.is_null() { *used = need; } call_provider(&s, OP_CLEANUP, b, std::ptr::null_mut(), 0); + consume_guard.armed = false; let mut map = active_map().lock().unwrap(); write_header(b, BlockHeader { status, flags: FLAG_DONE | FLAG_CONSUMED, id: s.id }); if map.get(&(b as usize)).is_some_and(|cur| cur.id == s.id) { @@ -443,9 +556,9 @@ pub unsafe extern "system" fn XAsyncGetResult( } } -pub unsafe extern "system" fn XAsyncCancel(b: *mut XAsyncBlock) { +pub unsafe extern "system-unwind" fn XAsyncCancel(b: *mut XAsyncBlock) { if let Some((o, f)) = pc(5) { - let f: unsafe extern "system" fn(usize, *mut XAsyncBlock) = std::mem::transmute(f); + let f: unsafe extern "system-unwind" fn(usize, *mut XAsyncBlock) = std::mem::transmute(f); return f(o, b); } let Lookup::Active(s) = lookup(b) else { return }; @@ -459,9 +572,9 @@ pub unsafe extern "system" fn XAsyncCancel(b: *mut XAsyncBlock) { let _ = call_provider(&s, OP_CANCEL, b, std::ptr::null_mut(), 0); } -pub unsafe extern "system" fn XAsyncRun(b: *mut XAsyncBlock, work: usize) -> HRESULT { +pub unsafe extern "system-unwind" fn XAsyncRun(b: *mut XAsyncBlock, work: usize) -> HRESULT { if let Some((o, f)) = pc(6) { - let f: unsafe extern "system" fn(usize, *mut XAsyncBlock, usize) -> HRESULT = std::mem::transmute(f); + let f: unsafe extern "system-unwind" fn(usize, *mut XAsyncBlock, usize) -> HRESULT = std::mem::transmute(f); return f(o, b, work); } if b.is_null() || work == 0 { @@ -473,11 +586,14 @@ pub unsafe extern "system" fn XAsyncRun(b: *mut XAsyncBlock, work: usize) -> HRE context: 0, identity: 0, work, + _owned_payload: None, inner: Mutex::new(Inner { status: E_PENDING, result_size: 0, phase: Phase::Pending }), cv: Condvar::new(), }); - register_state(b, s); + register_state(b, s.clone()); + let mut cleanup = BeginCleanup { b, s, armed: true }; let hr = XAsyncSchedule(b, 0); + cleanup.armed = false; if hr < 0 { XAsyncComplete(b, hr, 0); } @@ -499,9 +615,11 @@ pub struct PayloadBuf { struct Payload { result: Mutex>>, work: Mutex Result + Send>>>, + cleaned_up: AtomicBool, + owned_by_pc: bool, } -unsafe extern "system" fn payload_provider(op: u32, data: *const XAsyncProviderData) -> HRESULT { +unsafe extern "system-unwind" fn payload_provider(op: u32, data: *const XAsyncProviderData) -> HRESULT { let d = &*data; let p = &*(d.context as *const Payload); match op { @@ -534,7 +652,16 @@ unsafe extern "system" fn payload_provider(op: u32, data: *const XAsyncProviderD S_OK } OP_CLEANUP => { - drop(Box::from_raw(d.context as *mut Payload)); + if p.owned_by_pc { + if !p.cleaned_up.swap(true, Ordering::AcqRel) { + drop(Arc::from_raw(d.context as *const Payload)); + } + } else { + // Release captured work/result buffers promptly while keeping `Payload` itself + // alive until every `Arc` drops (UAF-safe across concurrent workers). + *p.work.lock().unwrap_or_else(|e| e.into_inner()) = None; + *p.result.lock().unwrap_or_else(|e| e.into_inner()) = None; + } S_OK } _ => S_OK, @@ -554,14 +681,32 @@ pub unsafe fn begin_with_fixups(b: *mut XAsyncBlock, identity: usize, work: F where F: FnOnce() -> Result + Send + 'static, { - let p = Box::into_raw(Box::new(Payload { result: Mutex::new(None), work: Mutex::new(Some(Box::new(work))) })); - let hr = XAsyncBegin(b, p as *mut c_void, identity as *const c_void, std::ptr::null(), payload_provider as usize); - if hr < 0 { - // SAFETY: `XAsyncBegin` rejected the call before adopting `p`, so `OP_CLEANUP` will - // never run; reclaim the `Box` allocated above to avoid leaking it. - drop(Box::from_raw(p)); + if let Some((o, f)) = pc(7) { + let p = Arc::into_raw(Arc::new(Payload { + result: Mutex::new(None), + work: Mutex::new(Some(Box::new(work))), + cleaned_up: AtomicBool::new(false), + owned_by_pc: true, + })); + let f: unsafe extern "system-unwind" fn(usize, *mut XAsyncBlock, *mut c_void, *const c_void, *const u8, usize) -> HRESULT = std::mem::transmute(f); + let hr = f(o, b, p as *mut c_void, identity as *const c_void, std::ptr::null(), payload_provider as usize); + if hr < 0 { + // SAFETY: The PC runtime rejected `XAsyncBegin` synchronously before adopting `p`. + let payload = &*p; + if !payload.cleaned_up.swap(true, Ordering::AcqRel) { + drop(Arc::from_raw(p)); + } + } + return hr; } - hr + let payload = Arc::new(Payload { + result: Mutex::new(None), + work: Mutex::new(Some(Box::new(work))), + cleaned_up: AtomicBool::new(false), + owned_by_pc: false, + }); + let ctx = Arc::as_ptr(&payload) as *mut c_void; + xasync_begin_inner(b, ctx, identity as *const c_void, std::ptr::null(), payload_provider as usize, Some(payload)) } #[cfg(test)] @@ -1227,4 +1372,250 @@ mod tests { taskqueue::XTaskQueueCloseHandle(q); } } + + #[test] + fn provider_and_completion_callbacks_unwind_cleanly() { + let _g = crate::hle::xgameruntime::xasync::ASYNC_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + + unsafe extern "system-unwind" fn throwing_provider(op: u32, _data: *const XAsyncProviderData) -> HRESULT { + if op == OP_BEGIN { + panic!("guest XAsyncProvider unwind"); + } + S_OK + } + + unsafe extern "system-unwind" fn noop_provider(_op: u32, _data: *const XAsyncProviderData) -> HRESULT { + S_OK + } + + unsafe extern "system-unwind" fn throwing_completion(_b: *mut XAsyncBlock) { + panic!("guest XAsync completion callback unwind"); + } + + unsafe { + let mut q = std::ptr::null_mut(); + assert_eq!(taskqueue::XTaskQueueCreate(taskqueue::MODE_IMMEDIATE, taskqueue::MODE_IMMEDIATE, &mut q), S_OK); + + // (a) Unwind from guest XAsyncProvider::OP_BEGIN across XAsyncBegin. + let mut b1: XAsyncBlock = std::mem::zeroed(); + b1.queue = q; + let r1 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + XAsyncBegin(&mut b1, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), throwing_provider as usize) + })); + assert!(r1.is_err(), "XAsyncBegin must propagate unwind from guest provider"); + assert!( + !active_map().lock().unwrap().contains_key(&(&mut b1 as *mut XAsyncBlock as usize)), + "BeginCleanup must remove active entry when OP_BEGIN unwinds" + ); + + // (b) Unwind from guest completion callback across XAsyncComplete (MODE_IMMEDIATE). + let mut b2: XAsyncBlock = std::mem::zeroed(); + b2.queue = q; + b2.callback = throwing_completion as usize; + assert_eq!(XAsyncBegin(&mut b2, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), noop_provider as usize), S_OK); + let r2 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + XAsyncComplete(&mut b2, S_OK, 0); + })); + assert!(r2.is_err(), "XAsyncComplete must propagate unwind from guest completion callback"); + assert_eq!(XAsyncGetStatus(&mut b2, false), S_OK); + assert!(taskqueue::XTaskQueueIsEmpty(q, taskqueue::PORT_COMPLETION)); + + assert_eq!(taskqueue::XTaskQueueTerminate(q, true, std::ptr::null_mut(), 0), S_OK); + taskqueue::XTaskQueueCloseHandle(q); + } + } + + #[test] + fn begin_cleanup_preserves_sync_completed_payload_and_payload_ownership_on_unwind() { + let _g = crate::hle::xgameruntime::xasync::ASYNC_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + + unsafe extern "system-unwind" fn throwing_completion(_b: *mut XAsyncBlock) { + panic!("immediate completion callback unwind"); + } + unsafe extern "system-unwind" fn throwing_monitor(_ctx: *mut c_void, _q: *mut c_void, _port: u32) { + panic!("work monitor unwind"); + } + struct DropCount(Arc); + impl Drop for DropCount { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + + unsafe { + let mut q = std::ptr::null_mut(); + assert_eq!(taskqueue::XTaskQueueCreate(taskqueue::MODE_IMMEDIATE, taskqueue::MODE_IMMEDIATE, &mut q), S_OK); + + // (a) Synchronous completion with non-empty payload inside OP_BEGIN followed by an + // unwinding immediate completion callback must NOT strip `b` from `ACTIVE` or lose its + // payload / leak `Payload`. + let drops_a = Arc::new(AtomicU32::new(0)); + let probe_a = DropCount(Arc::clone(&drops_a)); + let mut b_a: XAsyncBlock = std::mem::zeroed(); + b_a.queue = q; + b_a.callback = throwing_completion as usize; + let r_a = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + begin_with(&mut b_a, 0xA1, move || { + let _keep = &probe_a; + Ok(b"data".to_vec()) + }) + })); + assert!(r_a.is_err()); + assert_eq!(XAsyncGetStatus(&mut b_a, false), S_OK); + let mut sz = 0usize; + assert_eq!(XAsyncGetResultSize(&mut b_a, &mut sz), S_OK); + assert_eq!(sz, 4, "BeginCleanup must not erase completed payload from ACTIVE"); + let mut buf = [0u8; 4]; + let mut used = 0usize; + assert_eq!(XAsyncGetResult(&mut b_a, 0xA1 as *const c_void, 4, buf.as_mut_ptr() as *mut c_void, &mut used), S_OK); + assert_eq!(&buf, b"data"); + assert_eq!(used, 4); + assert_eq!(drops_a.load(Ordering::SeqCst), 1, "Payload must be dropped once via OP_CLEANUP"); + assert!(!active_map().lock().unwrap().contains_key(&(&mut b_a as *mut XAsyncBlock as usize))); + + // (b) Synchronous completion with empty payload (OP_CLEANUP already freed Payload) + // followed by an unwinding immediate completion callback must not double-free Payload. + let drops_b = Arc::new(AtomicU32::new(0)); + let probe_b = DropCount(Arc::clone(&drops_b)); + let mut b_b: XAsyncBlock = std::mem::zeroed(); + b_b.queue = q; + b_b.callback = throwing_completion as usize; + let r_b = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + begin_with(&mut b_b, 0xB2, move || { + let _keep = &probe_b; + Ok(Vec::new()) + }) + })); + assert!(r_b.is_err()); + assert_eq!(XAsyncGetStatus(&mut b_b, false), S_OK); + assert_eq!(drops_b.load(Ordering::SeqCst), 1, "Payload must be dropped exactly once"); + + // (c) Unwind during XAsyncSchedule before OP_CLEANUP runs must reclaim Payload and + // remove `b` from `ACTIVE` without leaking. + let mut mon_tok = taskqueue::RegistrationToken { token: 0 }; + assert_eq!(taskqueue::XTaskQueueRegisterMonitor(q, std::ptr::null_mut(), throwing_monitor as usize, &mut mon_tok), S_OK); + let drops_c = Arc::new(AtomicU32::new(0)); + let probe_c = DropCount(Arc::clone(&drops_c)); + let mut b_c: XAsyncBlock = std::mem::zeroed(); + b_c.queue = q; + let r_c = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + begin_with(&mut b_c, 0xC3, move || { + let _keep = &probe_c; + Ok(b"never".to_vec()) + }) + })); + assert!(r_c.is_err()); + assert_eq!(drops_c.load(Ordering::SeqCst), 1, "PayloadGuard must reclaim Payload when OP_BEGIN unwinds before OP_CLEANUP"); + assert!(!active_map().lock().unwrap().contains_key(&(&mut b_c as *mut XAsyncBlock as usize))); + assert_eq!(XAsyncGetStatus(&mut b_c, false), E_ABORT); + taskqueue::XTaskQueueUnregisterMonitor(q, mon_tok); + + assert_eq!(taskqueue::XTaskQueueTerminate(q, true, std::ptr::null_mut(), 0), S_OK); + taskqueue::XTaskQueueCloseHandle(q); + } + } + + #[test] + fn complete_and_get_result_and_run_unwinds_finalize_state() { + use std::sync::mpsc; + use std::time::Duration; + let _g = crate::hle::xgameruntime::xasync::ASYNC_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + + unsafe extern "system-unwind" fn cleanup_throws_provider(op: u32, _data: *const XAsyncProviderData) -> HRESULT { + if op == OP_CLEANUP { + panic!("guest OP_CLEANUP unwind"); + } + S_OK + } + unsafe extern "system-unwind" fn get_result_throws_provider(op: u32, data: *const XAsyncProviderData) -> HRESULT { + let cleanups = &*((*data).context as *const AtomicU32); + match op { + OP_GET_RESULT => panic!("guest OP_GET_RESULT unwind"), + OP_CLEANUP => { + cleanups.fetch_add(1, Ordering::SeqCst); + S_OK + } + _ => S_OK, + } + } + unsafe extern "system-unwind" fn get_result_ok_cleanup_throws_provider(op: u32, data: *const XAsyncProviderData) -> HRESULT { + match op { + OP_GET_RESULT => { + std::ptr::copy_nonoverlapping(b"abcd".as_ptr(), (*data).buffer as *mut u8, 4); + S_OK + } + OP_CLEANUP => panic!("guest OP_CLEANUP unwind in GetResult"), + _ => S_OK, + } + } + unsafe extern "system-unwind" fn throwing_monitor(_ctx: *mut c_void, _q: *mut c_void, _port: u32) { + panic!("XAsyncRun schedule monitor unwind"); + } + unsafe extern "system-unwind" fn dummy_work(_b: *mut XAsyncBlock) -> HRESULT { + S_OK + } + + unsafe { + // (a) XAsyncComplete OP_CLEANUP unwind: finalizes state, removes from ACTIVE, and wakes waiter. + let mut b1 = Box::new(std::mem::zeroed::()); + assert_eq!(XAsyncBegin(&mut *b1, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), cleanup_throws_provider as usize), S_OK); + let b1_addr = &mut *b1 as *mut XAsyncBlock as usize; + let (tx, rx) = mpsc::channel(); + let waiter = std::thread::spawn(move || { + let hr = XAsyncGetStatus(b1_addr as *mut XAsyncBlock, true); + let _ = tx.send(hr); + }); + std::thread::sleep(Duration::from_millis(10)); + let r1 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + XAsyncComplete(&mut *b1, S_OK, 0); + })); + assert!(r1.is_err()); + let waited_hr = rx.recv_timeout(Duration::from_secs(2)).expect("XAsyncGetStatus(wait=true) hung after OP_CLEANUP unwind"); + waiter.join().unwrap(); + assert_eq!(waited_hr, S_OK); + assert!(!active_map().lock().unwrap().contains_key(&b1_addr)); + + // (b) XAsyncGetResult OP_GET_RESULT unwind: marks Consumed, removes from ACTIVE, does NOT run OP_CLEANUP in Drop. + let cleanups = AtomicU32::new(0); + let mut b2: XAsyncBlock = std::mem::zeroed(); + assert_eq!(XAsyncBegin(&mut b2, &cleanups as *const AtomicU32 as *mut c_void, std::ptr::null(), std::ptr::null(), get_result_throws_provider as usize), S_OK); + XAsyncComplete(&mut b2, S_OK, 4); + let mut out = [0u8; 4]; + let r2 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + XAsyncGetResult(&mut b2, std::ptr::null(), 4, out.as_mut_ptr() as *mut c_void, std::ptr::null_mut()) + })); + assert!(r2.is_err()); + assert_eq!(cleanups.load(Ordering::SeqCst), 0, "ConsumeCleanup must not call guest OP_CLEANUP during unwind"); + assert!(!active_map().lock().unwrap().contains_key(&(&mut b2 as *mut XAsyncBlock as usize))); + assert_eq!(XAsyncGetResult(&mut b2, std::ptr::null(), 4, out.as_mut_ptr() as *mut c_void, std::ptr::null_mut()), E_ILLEGAL_METHOD_CALL); + + // (c) XAsyncGetResult OP_CLEANUP unwind: also marks Consumed and removes from ACTIVE. + let mut b3: XAsyncBlock = std::mem::zeroed(); + assert_eq!(XAsyncBegin(&mut b3, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), get_result_ok_cleanup_throws_provider as usize), S_OK); + XAsyncComplete(&mut b3, S_OK, 4); + let r3 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + XAsyncGetResult(&mut b3, std::ptr::null(), 4, out.as_mut_ptr() as *mut c_void, std::ptr::null_mut()) + })); + assert!(r3.is_err()); + assert!(!active_map().lock().unwrap().contains_key(&(&mut b3 as *mut XAsyncBlock as usize))); + assert_eq!(XAsyncGetResult(&mut b3, std::ptr::null(), 4, out.as_mut_ptr() as *mut c_void, std::ptr::null_mut()), E_ILLEGAL_METHOD_CALL); + + // (d) XAsyncRun schedule unwind: BeginCleanup removes pending block from ACTIVE and marks E_ABORT. + let mut q = std::ptr::null_mut(); + assert_eq!(taskqueue::XTaskQueueCreate(taskqueue::MODE_IMMEDIATE, taskqueue::MODE_IMMEDIATE, &mut q), S_OK); + let mut mon_tok = taskqueue::RegistrationToken { token: 0 }; + assert_eq!(taskqueue::XTaskQueueRegisterMonitor(q, std::ptr::null_mut(), throwing_monitor as usize, &mut mon_tok), S_OK); + let mut b4: XAsyncBlock = std::mem::zeroed(); + b4.queue = q; + let r4 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + XAsyncRun(&mut b4, dummy_work as usize) + })); + assert!(r4.is_err()); + assert!(!active_map().lock().unwrap().contains_key(&(&mut b4 as *mut XAsyncBlock as usize))); + assert_eq!(XAsyncGetStatus(&mut b4, false), E_ABORT); + taskqueue::XTaskQueueUnregisterMonitor(q, mon_tok); + assert_eq!(taskqueue::XTaskQueueTerminate(q, true, std::ptr::null_mut(), 0), S_OK); + taskqueue::XTaskQueueCloseHandle(q); + } + } } diff --git a/crates/xcl/src/loader.rs b/crates/xcl/src/loader.rs index 5297d15..1046b2f 100644 --- a/crates/xcl/src/loader.rs +++ b/crates/xcl/src/loader.rs @@ -51,9 +51,9 @@ fn section_protection(ch: u32) -> u32 { } } -type TlsCallback = unsafe extern "system" fn(*mut c_void, u32, *mut c_void); -type DllMain = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; -type ExeEntry = unsafe extern "system" fn(*mut c_void) -> u32; +type TlsCallback = unsafe extern "system-unwind" fn(*mut c_void, u32, *mut c_void); +type DllMain = unsafe extern "system-unwind" fn(*mut c_void, u32, *mut c_void) -> i32; +type ExeEntry = unsafe extern "system-unwind" fn(*mut c_void) -> u32; /// Map an image, apply relocations, resolve imports, set up TLS / exception data and /// page protections. Does NOT run any code of the image. @@ -332,7 +332,7 @@ struct EntryArgs { entry: usize, } -unsafe extern "system" fn main_thread(param: *mut c_void) -> u32 { +unsafe extern "system-unwind" fn main_thread(param: *mut c_void) -> u32 { let args = Box::from_raw(param as *mut EntryArgs); let f: ExeEntry = std::mem::transmute(args.entry); f(peb() as *mut c_void) @@ -366,10 +366,15 @@ pub fn run_main(m: &Arc) -> u32 { ); crate::log::flush(); unsafe { + // SAFETY: `extern "system-unwind"` and `extern "system"` share the identical Win64 ABI; + // Windows `BaseThreadInitThunk` wraps the thread routine in an SEH handler so foreign/guest + // exceptions can reach `SetUnhandledExceptionFilter` instead of aborting in `main_thread`. + let start_routine: unsafe extern "system" fn(*mut c_void) -> u32 = + std::mem::transmute:: u32, _>(main_thread); let h = CreateThread( std::ptr::null(), stack, - Some(main_thread), + Some(start_routine), args as *const c_void, STACK_SIZE_PARAM_IS_A_RESERVATION, std::ptr::null_mut(), @@ -529,4 +534,68 @@ mod tests { assert!(modules::find_mapped_by_name(&key).is_none(), "attempt {attempt}: still registered"); } } + + #[test] + fn init_dll_and_tls_callback_unwind_cleanly() { + unsafe extern "system-unwind" fn throwing_dll_main(_base: *mut c_void, _reason: u32, _reserved: *mut c_void) -> i32 { + panic!("guest DllMain unwind"); + } + unsafe extern "system-unwind" fn throwing_tls_cb(_base: *mut c_void, _reason: u32, _reserved: *mut c_void) { + panic!("guest TLS callback unwind"); + } + + // (a) Guest DllMain unwinding across `init_dll` drops `LoadGuard` and releases `LOAD_LOCK`. + let dll_main_addr = throwing_dll_main as usize; + let m_dll = Arc::new(MappedModule { + name: "unwind_test_dllmain.dll".into(), + path: PathBuf::from("unwind_test_dllmain.dll"), + base: dll_main_addr - 0x1000, + size: 0x2000, + entry_rva: 0x1000, + is_dll: true, + exports: OwnedExports::default(), + tls_callbacks: Mutex::new(Vec::new()), + no_thread_calls: AtomicBool::new(false), + initialized: AtomicBool::new(false), + stack_reserve: 0, + }); + let r1 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let (_g, _lock) = LoadGuard::enter(); + let _ = init_dll(&m_dll); + })); + assert!(r1.is_err(), "init_dll must propagate unwind from guest DllMain"); + assert_eq!(IN_LOAD.with(|c| c.get()), 0, "LoadGuard::drop must reset IN_LOAD on unwind"); + LOAD_LOCK.clear_poison(); + { + // Subsequent LoadGuard::enter() must succeed cleanly without deadlocking. + let (_g, _lock) = LoadGuard::enter(); + } + assert!(!m_dll.initialized.load(Ordering::Acquire)); + + // (b) Guest TLS callback unwinding across `init_dll` drops `LoadGuard` cleanly. + let m_tls = Arc::new(MappedModule { + name: "unwind_test_tls.dll".into(), + path: PathBuf::from("unwind_test_tls.dll"), + base: 0x1000, + size: 0x1000, + entry_rva: 0, + is_dll: true, + exports: OwnedExports::default(), + tls_callbacks: Mutex::new(vec![throwing_tls_cb as usize]), + no_thread_calls: AtomicBool::new(false), + initialized: AtomicBool::new(false), + stack_reserve: 0, + }); + let r2 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let (_g, _lock) = LoadGuard::enter(); + let _ = init_dll(&m_tls); + })); + assert!(r2.is_err(), "init_dll must propagate unwind from guest TLS callback"); + assert_eq!(IN_LOAD.with(|c| c.get()), 0, "LoadGuard::drop must reset IN_LOAD on TLS unwind"); + LOAD_LOCK.clear_poison(); + { + let (_g, _lock) = LoadGuard::enter(); + } + assert!(!m_tls.initialized.load(Ordering::Acquire)); + } } diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 83ed102..a7f7ead 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -7,7 +7,7 @@ use std::sync::atomic::Ordering; /// Our own TLS callback: ntdll calls it for every thread start/exit in the process. /// In host mode it initialises the game's static TLS for the new thread and forwards /// the notification to the game's TLS callbacks / DllMains. -unsafe extern "system" fn xcl_tls_callback(_h: *mut c_void, reason: u32, _r: *mut c_void) { +unsafe extern "system-unwind" fn xcl_tls_callback(_h: *mut c_void, reason: u32, _r: *mut c_void) { if xcl::host::HOST_MODE.load(Ordering::Acquire) { xcl::loader::on_tls_event(reason); } @@ -15,7 +15,7 @@ unsafe extern "system" fn xcl_tls_callback(_h: *mut c_void, reason: u32, _r: *mu #[used] #[link_section = ".CRT$XLY"] -static XCL_TLS_CALLBACK: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = xcl_tls_callback; +static XCL_TLS_CALLBACK: unsafe extern "system-unwind" fn(*mut c_void, u32, *mut c_void) = xcl_tls_callback; const HELP: &str = "\ XCL – Xbox Series X|S → Windows compatibility layer diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index 7cf09a9..a15e3cd 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -474,11 +474,11 @@ unsafe extern "system" fn hk_disk_free_a(n: *const u8, spc: *mut u32, bps: *mut type FnCreateDirW = unsafe extern "system" fn(*const u16, *const c_void) -> i32; type FnPathW = unsafe extern "system" fn(*const u16) -> i32; type FnMoveFileExW = unsafe extern "system" fn(*const u16, *const u16, u32) -> i32; -type FnMoveFileWithProgressW = unsafe extern "system" fn(*const u16, *const u16, *const c_void, *const c_void, u32) -> i32; -type FnMoveFileWithProgressA = unsafe extern "system" fn(*const u8, *const u8, *const c_void, *const c_void, u32) -> i32; -type FnCopyFileExW = unsafe extern "system" fn(*const u16, *const u16, *const c_void, *const c_void, *mut i32, u32) -> i32; +type FnMoveFileWithProgressW = unsafe extern "system-unwind" fn(*const u16, *const u16, *const c_void, *const c_void, u32) -> i32; +type FnMoveFileWithProgressA = unsafe extern "system-unwind" fn(*const u8, *const u8, *const c_void, *const c_void, u32) -> i32; +type FnCopyFileExW = unsafe extern "system-unwind" fn(*const u16, *const u16, *const c_void, *const c_void, *mut i32, u32) -> i32; type FnCopyFileW = unsafe extern "system" fn(*const u16, *const u16, i32) -> i32; -type FnCopyFile2 = unsafe extern "system" fn(*const u16, *const u16, *const c_void) -> i32; +type FnCopyFile2 = unsafe extern "system-unwind" fn(*const u16, *const u16, *const c_void) -> i32; type FnReplaceFileW = unsafe extern "system" fn(*const u16, *const u16, *const u16, u32, *const c_void, *const c_void) -> i32; static O_CREATE_DIR_W: AtomicUsize = AtomicUsize::new(0); static O_REMOVE_DIR_W: AtomicUsize = AtomicUsize::new(0); @@ -606,7 +606,7 @@ unsafe extern "system" fn hk_move_file_ex_w(src: *const u16, dst: *const u16, fl /// MoveFileW reaches MoveFileWithProgressW without going through MoveFileExW (Windows 11; under /// Wine the ANSI moves do too). Where MoveFileExW calls it, the guard lets the inner call through. -unsafe extern "system" fn hk_move_file_with_progress_w(src: *const u16, dst: *const u16, prog: *const c_void, data: *const c_void, flags: u32) -> i32 { +unsafe extern "system-unwind" fn hk_move_file_with_progress_w(src: *const u16, dst: *const u16, prog: *const c_void, data: *const c_void, flags: u32) -> i32 { let orig = orig!(O_MOVE_FILE_PROGRESS_W as FnMoveFileWithProgressW); move_file(src, dst, flags, |s, d, f| orig(s, d, prog, data, f)) } @@ -630,7 +630,7 @@ unsafe extern "system" fn hk_move_file_ex_a(src: *const u8, dst: *const u8, flag move_file_a(src, dst, std::ptr::null(), std::ptr::null(), flags, || orig(src, dst, flags)) } -unsafe extern "system" fn hk_move_file_with_progress_a(src: *const u8, dst: *const u8, prog: *const c_void, data: *const c_void, flags: u32) -> i32 { +unsafe extern "system-unwind" fn hk_move_file_with_progress_a(src: *const u8, dst: *const u8, prog: *const c_void, data: *const c_void, flags: u32) -> i32 { let orig = orig!(O_MOVE_FILE_PROGRESS_A as FnMoveFileWithProgressA); move_file_a(src, dst, prog, data, flags, || orig(src, dst, prog, data, flags)) } @@ -814,7 +814,7 @@ unsafe fn copy_file_ex_w_vfs( ok } -unsafe extern "system" fn hk_copy_file_ex_w(src: *const u16, dst: *const u16, prog: *const c_void, data: *const c_void, cancel: *mut i32, flags: u32) -> i32 { +unsafe extern "system-unwind" fn hk_copy_file_ex_w(src: *const u16, dst: *const u16, prog: *const c_void, data: *const c_void, cancel: *mut i32, flags: u32) -> i32 { let orig = orig!(O_COPY_FILE_EX_W as FnCopyFileExW); let (Some(_g), Some(v)) = (Guard::enter(), vfs::get()) else { return orig(src, dst, prog, data, cancel, flags) }; let (Some(s), Some(d)) = (from_wide_ptr(src), from_wide_ptr(dst)) else { return orig(src, dst, prog, data, cancel, flags) }; @@ -886,7 +886,7 @@ unsafe fn copy_file_2_vfs( hr } -unsafe extern "system" fn hk_copy_file_2(src: *const u16, dst: *const u16, params: *const c_void) -> i32 { +unsafe extern "system-unwind" fn hk_copy_file_2(src: *const u16, dst: *const u16, params: *const c_void) -> i32 { let orig = orig!(O_COPY_FILE_2 as FnCopyFile2); let (Some(_g), Some(v)) = (Guard::enter(), vfs::get()) else { return orig(src, dst, params) }; let (Some(s), Some(d)) = (from_wide_ptr(src), from_wide_ptr(dst)) else { return orig(src, dst, params) }; From 83d31e0be7776cbd8388abd709b76754c334c577 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:10:23 -0700 Subject: [PATCH 23/37] recomp: memory window from the full address, carry in 32 bits (#123 again) From ivall/xcl#138 by @gefydev, squashed; conflict resolved by hand. --- crates/xcl/src/gpu/recomp/emit.rs | 61 +++++++++++++++++++++++------- crates/xcl/src/gpu/recomp/tests.rs | 58 ++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 0d6baa0..063cdf5 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -1469,8 +1469,8 @@ impl Em { if name.starts_with("s_buffer_load") { // V#: base = dw0 | dw1[15:0] << 32, stride = dw1[29:16], num_records = dw2 let (d0, d1, d2) = (self.sreg(sbase), self.sreg(sbase + 1), self.sreg(sbase + 2)); - self.window(&d1); self.line(&format!("uint {t}_off = {} + {soff};", hex(imm))); + self.window_at(&d1, &[d0.clone(), format!("{t}_off")], None); self.line(&format!("uint {t}_st = ({d1} >> 16) & 0x3FFFu;")); self.line(&format!("uint {t}_lim = select({t}_st == 0u, {d2}, {d2} * {t}_st);")); self.line(&format!("uint {t}_a = ({d0} + {t}_off) & ~3u;")); @@ -1495,7 +1495,7 @@ impl Em { let imm = ((imm << 11) as i32 >> 11) as u32; // 21-bit signed let b = self.sreg(sbase); let hi = self.sreg(sbase + 1); - self.window(&hi); + self.window_at(&hi, &[b.clone(), soff.clone()], Some(imm)); // the dwords are contiguous: Load2 / Load4 (one window switch per four dwords) self.line(&format!("uint {t}_a = ({b} + {} + {soff}) & ~3u;", hex(imm))); match count { @@ -1541,15 +1541,50 @@ impl Em { } } - /// `window` for a FLAT / global address: SADDR pair (global with SADDR) or the 64-bit - /// VGPR address. - fn flat_window(&mut self, global: bool, saddr: u64, addr: u64) { + /// `window` for the address `hi:lo + offsets`: `terms` are the low dword and the unsigned + /// 32-bit offsets, `signed` a sign-extended one. Their carry (or borrow) out of the low + /// dword moves the address to the next (previous) window, as it does on the console. 32-bit + /// adds and compares only (64-bit integers made the AMD shader compiler crash on a large + /// program, #123). One window: nothing (the single-window HLSL is unchanged). + fn window_at(&mut self, hi: &str, terms: &[String], signed: Option) { + if self.opt.mem_windows <= 1 { + return; + } + let terms: Vec<&String> = terms.iter().filter(|t| t.as_str() != "0u").collect(); + let Some((first, rest)) = terms.split_first() else { + return self.window(hi); + }; + let mut body = format!("uint xcl_ws = {first}, xcl_wc = 0u, xcl_wt;"); + for t in rest { + body += &format!(" xcl_wt = {t}; xcl_ws += xcl_wt; xcl_wc += (uint)(xcl_ws < xcl_wt);"); + } + match signed.filter(|&o| o != 0) { + Some(o) if (o as i32) > 0 => body += &format!(" xcl_ws += {0}; xcl_wc += (uint)(xcl_ws < {0});", hex(o)), + Some(o) => body += &format!(" xcl_wc -= (uint)(xcl_ws < {0}); xcl_ws -= {0};", hex((o as i32).unsigned_abs())), + None => {} + } + self.line(&format!("{{ {body} xcl_w = (({hi}) + xcl_wc) & 3u; }}")); + } + + /// `window_at` for a FLAT / global address: the SADDR pair plus the VGPR offset (global + /// with SADDR) or the 64-bit VGPR address, plus the signed instruction offset. + fn flat_window(&mut self, global: bool, saddr: u64, addr: u64, off: u32) { if self.opt.mem_windows > 1 { - let hi = if global && saddr != 0x7D && saddr != 0x7F { self.sreg(saddr + 1) } else { self.vreg(addr + 1) }; - self.window(&hi); + let (hi, terms) = if global && saddr != 0x7D && saddr != 0x7F { + (self.sreg(saddr + 1), vec![self.sreg(saddr), self.vreg(addr)]) + } else { + (self.vreg(addr + 1), vec![self.vreg(addr)]) + }; + self.window_at(&hi, &terms, Some(off)); } } + /// `window_at` for a MUBUF address: V# base + SOFFSET + `{t}_off` + `{t}_stride` · index. + fn buffer_window(&mut self, d0: &str, d1: &str, soff: &str, t: &str, index: &str) { + let terms = [d0.to_string(), soff.to_string(), format!("{t}_off"), format!("{t}_stride * ({index})")]; + self.window_at(d1, &terms, None); + } + /// The sampler of the MIMG instruction at `pc`: a static sampler when its S# is constant /// (register `static_sampler_base + i`, space 1), else the sampler heap entry S# word 3 /// [11:0] names (XCL shader ABI). @@ -1597,13 +1632,13 @@ impl Em { let soff = self.code32(f("SOFFSET"), None, false).ok_or("op")?; let (offen, idxen) = (f("OFFEN") != 0, f("IDXEN") != 0); let (d0, d1, d2, d3) = (self.sreg(srsrc), self.sreg(srsrc + 1), self.sreg(srsrc + 2), self.sreg(srsrc + 3)); - self.window(&d1); let index = if idxen { self.vreg(vaddr) } else { "0u".into() }; let voff = if offen { self.vreg(vaddr + idxen as u64) } else { "0u".into() }; let t = self.t(); self.line(&format!("uint {t}_stride = ({d1} >> 16) & 0x3FFFu;")); self.line(&format!("uint {t}_off = {voff} + {}u;", f("OFFSET"))); self.line(&format!("uint {t}_a = {d0} + {soff} + {t}_off + {t}_stride * {index};")); + self.buffer_window(&d0, &d1, &soff, &t, &index); let act = self.act(); let in_range = |bytes: String| format!("select({t}_stride == 0u, {t}_off + {bytes} <= {d2}, {index} < {d2})"); if let Some((n, signed, store)) = small { @@ -3659,7 +3694,6 @@ impl Em { let soff = self.code32(f("SOFFSET"), None, false).ok_or("op")?; let (offen, idxen) = (f("OFFEN") != 0, f("IDXEN") != 0); let (d0, d1, d2) = (self.sreg(srsrc), self.sreg(srsrc + 1), self.sreg(srsrc + 2)); - self.window(&d1); let index = if idxen { self.vreg(vaddr) } else { "0u".into() }; let voff = if offen { self.vreg(vaddr + idxen as u64) } else { "0u".into() }; let t = self.t(); @@ -3669,6 +3703,7 @@ impl Em { self.line(&format!("uint {t}_stride = ({d1} >> 16) & 0x3FFFu;")); self.line(&format!("uint {t}_off = {voff} + {}u;", f("OFFSET"))); self.line(&format!("uint {t}_a = ({d0} + {soff} + {t}_off + {t}_stride * {index}) & ~{}u;", bytes - 1)); + self.buffer_window(&d0, &d1, &soff, &t, &index); self.line(&format!("bool {t}_ok = select({t}_stride == 0u, {t}_off + {bytes}u <= {d2}, {index} < {d2});")); let act = self.act(); if x2 { @@ -3708,13 +3743,13 @@ impl Em { let soff = self.code32(f("SOFFSET"), None, false).ok_or("op")?; let (offen, idxen) = (f("OFFEN") != 0, f("IDXEN") != 0); let (d0, d1, d2) = (self.sreg(srsrc), self.sreg(srsrc + 1), self.sreg(srsrc + 2)); - self.window(&d1); let index = if idxen { self.vreg(vaddr) } else { "0u".into() }; let voff = if offen { self.vreg(vaddr + idxen as u64) } else { "0u".into() }; let t = self.t(); self.line(&format!("uint {t}_stride = ({d1} >> 16) & 0x3FFFu;")); self.line(&format!("uint {t}_off = {voff} + {}u;", f("OFFSET"))); self.line(&format!("uint {t}_a = {d0} + {soff} + {t}_off + {t}_stride * {index};")); + self.buffer_window(&d0, &d1, &soff, &t, &index); let ok = format!("select({t}_stride == 0u, {t}_off + {n}u <= {d2}, {index} < {d2})"); let act = self.act(); let v = self.vreg(vdata); @@ -3743,9 +3778,9 @@ impl Em { let addr = self.vreg(f("ADDR")); let saddr = f("SADDR"); let base = if global && saddr != 0x7D && saddr != 0x7F { format!("{} + {addr}", self.sreg(saddr)) } else { addr }; - self.flat_window(global, saddr, f("ADDR")); let raw = f("OFFSET") as u32; let off = if global { (((raw << 20) as i32) >> 20) as u32 } else { raw }; + self.flat_window(global, saddr, f("ADDR"), off); let t = self.t(); self.line(&format!("uint {t}_a = {base} + {};", hex(off))); let act = self.act(); @@ -3789,9 +3824,9 @@ impl Em { addr } }; - self.flat_window(global, saddr, f("ADDR")); let raw = f("OFFSET") as u32; let off = if global { (((raw << 20) as i32) >> 20) as u32 } else { raw }; + self.flat_window(global, saddr, f("ADDR"), off); let t = self.t(); self.line(&format!("uint {t}_a = {base} + {};", hex(off))); let act = self.act(); @@ -3861,9 +3896,9 @@ impl Em { let addr = self.vreg(f("ADDR")); let saddr = f("SADDR"); let base = if global && saddr != 0x7D && saddr != 0x7F { format!("{} + {addr}", self.sreg(saddr)) } else { addr }; - self.flat_window(global, saddr, f("ADDR")); let raw = f("OFFSET") as u32; let off = if global { (((raw << 20) as i32) >> 20) as u32 } else { raw }; + self.flat_window(global, saddr, f("ADDR"), off); let t = self.t(); let x2 = op.ends_with("_x2"); let op = op.trim_end_matches("_x2"); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 4d77c06..cd62d3d 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3823,6 +3823,64 @@ fn gpu_uma_import_check_at_init() { assert!(s.starts_with("ok") || s.starts_with("off"), "{s}"); } +/// An address whose offset carries out of the low dword is in the next window: the base sits +/// at 0xFFFF_F000 of window 0, base + offset in window 1 (s_load, s_buffer_load, buffer load / +/// store, global with SADDR, global atomic). +#[test] +fn gpu_memory_window_carry() { + if !gpu_ready() { + return; + } + let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); + let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64); + assert_eq!((w1 - w0, w0 as u32), (1 << 32, 0)); + let word = |a: u64| unsafe { &mut *(a as *mut u32) }; + *word(w1 + 0x1000) = 0xC0FFEE; + *word(w1 + 0x1004) = 0x1234; + for l in 0..64u64 { + *word(w1 + 0x2000 + 4 * l) = 1000 + l as u32; + *word(w1 + 0x4000 + 4 * l) = 5000 + l as u32; + } + let list: Vec<(&str, &str, &[(&str, u64)], Option)> = vec![ + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 1), ("OFFSET", 0x2000)], None), + ("S_BUFFER_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 22), ("SBASE", 4), ("OFFSET", 0x3000)], None), + ("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 2), ("SOFFSET", 128), ("OFFEN", 1)], None), + ("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 2), ("VADDR", 6), ("SRSRC", 3), ("SOFFSET", 128), ("OFFEN", 1)], None), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 11), ("ADDR", 1), ("SADDR", 16), ("OFFSET", 0)], None), + ("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 12), ("ADDR", 3), ("DATA", 13), ("SADDR", 16), ("OFFSET", 0), ("GLC", 1)], None), + ]; + let p = prog(&list); + let t = translate(&p, &on_gpu(Options { mem_windows: 2, ..Default::default() })).unwrap(); + // 32-bit adds and compares only: 64-bit integers here crashed the AMD shader compiler (#123) + let carries: Vec<&str> = t.hlsl.lines().filter(|l| l.contains("xcl_w =")).collect(); + assert!(carries.len() >= 6 && carries.iter().all(|l| !l.contains("64")), "{carries:#?}"); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); + let hi0 = (w0 >> 32) as u32; + let mut st = KernelState::default(); + st.sgpr[2..4].copy_from_slice(&[0xFFFF_F000, hi0]); + st.sgpr[8..12].copy_from_slice(&[0xFFFF_F000, hi0 & 0xFFFF, 0x10000, 0]); + st.sgpr[12..16].copy_from_slice(&[0xFFFF_F000, hi0 & 0xFFFF, 0x10000, 0]); + st.sgpr[16..18].copy_from_slice(&[0xFFFF_F000, hi0]); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let l = l as u32; + r[0] = 0x3000 + 4 * l; // → w1 + 0x2000 + r[1] = 0x5000 + 4 * l; // → w1 + 0x4000 + r[2] = 7 * l; + r[3] = 0x7000; // → w1 + 0x6000, one counter + r[6] = 0x9000 + 4 * l; // → w1 + 0x8000 + r[13] = 1; + } + let r = runner::run_in_arena(&dxil, &st, &arena).unwrap(); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0xC0FFEE, 0x1234), "s_load carried into window 1"); + assert_eq!(r.sgpr[22], 1000, "s_buffer_load carried into window 1"); + for l in 0..64u64 { + assert_eq!(r.vgpr[l as usize][10], 1000 + l as u32, "lane {l}: buffer_load carried into window 1"); + assert_eq!(r.vgpr[l as usize][11], 5000 + l as u32, "lane {l}: global_load (SADDR) carried into window 1"); + assert_eq!(*word(w1 + 0x8000 + 4 * l), 7 * l as u32, "lane {l}: buffer_store carried into window 1"); + } + assert_eq!(*word(w1 + 0x6000), 64, "global_atomic_add carried into window 1"); +} + /// End-to-end GPU test of the sparse-window VRAM runtime layout: /// - Window 0..2 = sparse VRAM (tiled reserved buffers on DEFAULT heaps) /// - Window 3 = committed coherent RAM (`OpenExistingHeapFromAddress`) From 6f5e6991d9736088f5f142db99ca8dfb97c89eea Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:10:46 -0700 Subject: [PATCH 24/37] Pixel shaders: masks hold the helper lanes (#105 item 1) From ivall/xcl#134 by @tiagonleal, squashed; conflict resolved by hand. --- crates/xcl/src/gpu/recomp/emit.rs | 160 +++++++++++++++++++++++-- crates/xcl/src/gpu/recomp/mod.rs | 12 +- crates/xcl/src/gpu/recomp/tests.rs | 158 ++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/x64_masks.rs | 2 + 4 files changed, 319 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 0d6baa0..41cf81e 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -40,9 +40,13 @@ pub(super) struct Em { /// split wave64 (`x64`): words one exchange carries (1: masks and lane reads, up to 16: /// coherent scalar loads, 32: `ds_bpermute`) x64_words: usize, - /// 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, + /// split wave64 and pixel shaders: pc → SGPRs whose whole value may be read after that + /// instruction (`x64_masks`); a mask written to none of them is only read lane by lane + /// (split: stays in its half, no exchange; pixel: no quad reads for the helper lanes) + pub mask_whole_live: BTreeMap, + /// pixel shaders: the program's loops (`loop_ranges`); a mask written in one takes its + /// helper lanes' bits from quad reads of its vector operands (`quad_bits`, #134) + pub loops: Vec<(u64, u64)>, /// compute mode: the group is padded to whole console waves (`partial_waves`), the /// padding lanes inactive at the start pub cs_pad: bool, @@ -163,6 +167,79 @@ fn float_compare(op: &str, a: &str, b: &str, isnan: &str) -> Option { }) } +/// A pixel shader's mask written in a loop (#134): the quad's four bits (bit p: member p's +/// `act` and `cond`) for `ballot_px_quad`, every lane evaluating each member's condition with +/// that member's vector registers read through quad reads. `ballot_px` quad-reads the compare's +/// result instead, and AMD's RDNA2 compiler crashed in `CreateGraphicsPipelineState` on quad +/// reads of a value computed from a `WaveReadLaneAt` in a loop – the shape that gives every +/// `v_cmp` of a waterfall loop over `v_readfirstlane` (WarmMilkCodes on an RX 6600 XT, driver +/// 32.0.21045.29003: the loop's `ballot_px` replaced by `ballot` builds; `rla`'s quad reads of +/// the loop's vector operand did not crash it). The same bits as `ballot_px` as long as the +/// other terms are the same in every lane of a quad, which is all this accepts: scalar +/// registers, constants, pure functions and `lane_id` (rewritten per member). Anything else (a +/// temporary, a lane read, a derivative) gives `None`, and the mask keeps `ballot_px`. Returns +/// the quad reads (one per vector register and member, into `{tmp}_vN_p`) and the bits. +fn quad_bits(act: &str, cond: &str, tmp: &str) -> Option<(String, String)> { + let mut reads = std::collections::BTreeSet::new(); + let mut terms = Vec::with_capacity(4); + for p in 0..4u32 { + // the wave64 EXEC bit (`lanebit` reads `lane_id` inside); the wave32 one names it + let a = if act == "lanebit(exec_lo, exec_hi)" { format!("lanebit_at(exec_lo, exec_hi, (lane_id & ~3u) | {p}u)") } else { quad_member(act, p, tmp, &mut reads)? }; + let c = quad_member(cond, p, tmp, &mut reads)?; + terms.push(if p == 0 { format!("(uint)and({a}, ({c}))") } else { format!("((uint)and({a}, ({c})) << {p}u)") }); + } + let reads: Vec = reads.iter().map(|(v, p)| format!("uint {tmp}_{v}_{p} = QuadReadLaneAt({v}, {p}u);")).collect(); + Some((reads.join(" "), terms.join(" | "))) +} + +/// `expr` as member `p` of the lane's quad evaluates it (`quad_bits`): vector registers through +/// `QuadReadLaneAt` (`{tmp}_vN_p`, noted in `reads`), `lane_id` as the member's; `None` for a +/// term that may differ between the lanes of a quad in another way. +fn quad_member(expr: &str, p: u32, tmp: &str, reads: &mut std::collections::BTreeSet<(String, u32)>) -> Option { + const PURE: &[&str] = &[ + "asfloat", "asuint", "asint", "asdouble", "isnan", "isnan_d", "isinf", "isfinite", "and", "or", "select", "abs", "min", "max", + "fclass", "fclass16", "fclass64", "f16tof32", "f32tof16", "sdwa_sel", "firstbitlow", "firstbithigh", "countbits", "reversebits", + "mul_hi_u32", "uint", "int", "float", "double", + ]; + const SAME: &[&str] = &["vcc_lo", "vcc_hi", "exec_lo", "exec_hi", "m0", "scc", "true", "false", "uint", "int", "float", "bool", "double", "uint64_t", "int64_t"]; + let b = expr.as_bytes(); + let mut out = String::with_capacity(expr.len() * 2); + let mut i = 0; + while i < b.len() { + let c = b[i]; + if c.is_ascii_digit() { + // a literal (0x3F800000u, 1.0f, 1e-3f), copied as it is + let s = i; + while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'.' || ((b[i] == b'-' || b[i] == b'+') && matches!(b[i - 1], b'e' | b'E') && !expr[s..].starts_with("0x"))) { + i += 1; + } + out.push_str(&expr[s..i]); + } else if c.is_ascii_alphabetic() || c == b'_' { + let s = i; + while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { + i += 1; + } + let id = &expr[s..i]; + let call = expr[i..].trim_start().starts_with('('); + let reg = |prefix: &str| id.strip_prefix(prefix).is_some_and(|n| !n.is_empty() && n.bytes().all(|d| d.is_ascii_digit())); + if reg("v") { + out.push_str(&format!("{tmp}_{id}_{p}")); + reads.insert((id.to_string(), p)); + } else if id == "lane_id" { + out.push_str(&format!("((lane_id & ~3u) | {p}u)")); + } else if reg("s") || reg("ttmp") || (call && PURE.contains(&id)) || (!call && SAME.contains(&id)) { + out.push_str(id); + } else { + return None; + } + } else { + out.push(c as char); + i += 1; + } + } + Some(out) +} + /// Layout of the SDWA / DPP extension dword for this instruction's base encoding. pub(super) fn ext_encoding(d: &Decoded) -> Option<&'static Encoding> { let base = match d.enc.name { @@ -479,7 +556,8 @@ impl Em { uses_lds: false, uses_scratch: false, x64_words: 1, - x64_whole_live: BTreeMap::new(), + mask_whole_live: BTreeMap::new(), + loops: Vec::new(), cs_pad: false, upper: None, cur_pc: 0, @@ -559,10 +637,13 @@ impl Em { self.opt.wave64 && self.opt.split_wave64 && matches!(self.opt.mode, Mode::Kernel | Mode::Compute(_) | Mode::Mesh(_) | Mode::Geometry(_)) } - /// `ballot` of the program's wave (both halves' words in the split form). + /// `ballot` of the program's wave (both halves' words in the split form, the helper lanes' + /// bits in a pixel shader). fn ballot_fn(&self) -> &'static str { if self.x64() { "xcl_x_ballot" + } else if matches!(self.opt.mode, Mode::Pixel(_)) { + "ballot_px" } else { "ballot" } @@ -805,17 +886,31 @@ impl Em { let a = self.act(); let m = self.t(); let mut ballot = self.ballot_fn(); - // no exchange for a mask that is only ever read lane by lane (the half's own word is - // enough), that goes nowhere, or that is 0 in every lane anyway + // no exchange (split) or quad reads (pixel) for a mask that is only ever read lane by + // lane (the half's own word, the lane's own bit are enough), that goes nowhere, or that + // is 0 in every lane anyway let local = match *dst { - Dst::S(n) => n < 126 && self.x64_whole_live.get(&self.cur_pc).is_some_and(|live| live & (3u128 << n) == 0), + Dst::S(n) => n < 126 && self.mask_whole_live.get(&self.cur_pc).is_some_and(|live| live & (3u128 << n) == 0), Dst::Null => true, Dst::V(_) => false, }; - if self.x64() && (local || cond == "false") { - ballot = "xcl_x_ballot_local"; + if local || cond == "false" { + if self.x64() { + ballot = "xcl_x_ballot_local"; + } else if matches!(self.opt.mode, Mode::Pixel(_)) { + ballot = "ballot_px_local"; + } + } + let in_loop = self.loops.iter().any(|&(start, end)| start <= self.cur_pc && self.cur_pc < end); + match if ballot == "ballot_px" && in_loop { quad_bits(a, cond, &m) } else { None } { + Some((reads, q)) => { + if !reads.is_empty() { + self.line(&reads); + } + self.line(&format!("uint2 {m} = ballot_px_quad({q});")); + } + None => self.line(&format!("uint2 {m} = {ballot}(and({a}, ({cond})));")), } - self.line(&format!("uint2 {m} = {ballot}(and({a}, ({cond})));")); if self.opt.wave64 { self.write64(dst, &format!("{m}.x"), &format!("{m}.y")); } else { @@ -4209,6 +4304,9 @@ impl Em { let _ = writeln!(h, "{ty} xcl_ss{k} : register(s{k}, space1);"); } h.push_str(PRELUDE); + if matches!(self.opt.mode, Mode::Pixel(_)) { + h.push_str(PRELUDE_PIXEL); + } if self.x64() { self.x64_prelude(&mut h); } @@ -5386,6 +5484,46 @@ uint2 xcl_x_ballot_local(bool b) { uint xcl_x_rla_half(uint v, uint l) { return WaveReadLaneAt(v, l & 31u); } "#; +/// Pixel shaders: masks hold the helper lanes (#105). After `s_wqm` the helper pixels of a +/// quad a primitive's edge splits are in EXEC and the console's `v_cmp*` / carries set their +/// bits like any other lane's; wave ops leave helper lanes out before SM 6.7 (their ballot bits +/// are 0), quad ops do not. The entry EXEC stays `ballot(true)` – the live lanes, without the +/// helper lanes, as on the console, which returns to it after `s_wqm` (with the helper lanes +/// in it they never stop: `[WaveOpsIncludeHelperLanes]` hung the device that way). +const PRELUDE_PIXEL: &str = r#" +// every lane gets its quad's four bits through quad reads (they see helper lanes); ballot p +// collects bit p of them from the live lanes, and any live lane of a quad (every quad has one) +// answers for its member p. Only ballots and quad reads: a helper lane gets the wave's result +// of a ballot, not of every wave op (WaveActiveBitOr gives it another value on an RTX 5070 Ti), +// and each lane holds its own copy of EXEC – a helper lane's must be right as well. +// (bit p of q: the quad's member p). In a loop the translator gives q from quad reads of the +// compare's vector operands, not of its result (`quad_bits`: AMD's compiler crashed on those, +// #134); elsewhere ballot_px quad-reads the result. +uint2 ballot_px_quad(uint q) { + uint2 m = uint2(0u, 0u); + [unroll] for (uint p = 0u; p < 4u; p++) { + uint2 w = WaveActiveBallot(((q >> p) & 1u) != 0u).xy; + w |= w >> 1; + w |= w >> 2; + m |= (w & 0x11111111u) << p; + } + return uint2(select(and(xcl_w32, xcl_half != 0u), m.y, m.x), select(xcl_w32, 0u, m.y)); +} +uint2 ballot_px(bool b) { + uint own = (uint)b << (WaveGetLaneIndex() & 3u); + return ballot_px_quad(own | QuadReadAcrossX(own) | QuadReadAcrossY(own) | QuadReadAcrossDiagonal(own)); +} +// a mask only ever read lane by lane (v_cndmask, carry-ins; `x64_masks`): the wave's ballot +// with the reading lane's own bit, which a helper lane has too +uint2 ballot_px_local(bool b) { + uint hw = WaveGetLaneIndex(); + uint4 w = WaveActiveBallot(b); + uint own = (uint)b << (hw & 31u); + uint2 m = uint2(w.x | select(hw < 32u, own, 0u), w.y | select(and(hw >= 32u, hw < 64u), own, 0u)); + return uint2(select(and(xcl_w32, xcl_half != 0u), m.y, m.x), select(xcl_w32, 0u, m.y)); +} +"#; + const PRELUDE: &str = r#" static uint lane_id; // loop iterations a lane may run (`LOOP_GUARD`): far above what a working program needs diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 75c9595..d7adc98 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1354,9 +1354,17 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { em.configure_round_modes(&insts, branches == 0); em.static_ss = constant_samplers(&insts, &leaders); // split wave64: masks only read lane by lane skip the halves' exchange (geometry mode - // continues from the ES into the GS through s_setpc: left as it is) + // continues from the ES into the GS through s_setpc: left as it is); pixel shaders: they + // skip the quad reads that give the helper lanes' bits 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)); + em.mask_whole_live = x64_masks::by_pc(&insts, matches!(opt.mode, Mode::Kernel)); + } else if matches!(opt.mode, Mode::Pixel(_)) { + em.mask_whole_live = x64_masks::by_pc(&insts, false); + } + // pixel shaders: a mask written in a loop takes its helper lanes' bits from quad reads of + // the compare's vector operands (`quad_bits`, #134) + if matches!(opt.mode, Mode::Pixel(_)) { + em.loops = loop_ranges(&insts); } // 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 diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 4d77c06..9fd1765 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2817,6 +2817,164 @@ fn gpu_wave64_vs_spill_slots_and_identity() { } } +/// Masks in whole-quad mode hold the helper lanes (#105): after `s_wqm` the helper pixels of a +/// quad a primitive's edge splits are in EXEC, and the console's `v_cmp` sets their bits like +/// any other lane's. Wave ops leave helper lanes out before SM 6.7, so a mask taken with +/// `WaveActiveBallot` alone had them 0: `v_cndmask` gave them the false value, `s_and_saveexec` +/// dropped them, and a derivative taken across the quad by hand (DPP) was wrong along the +/// diagonal of two triangles. A waterfall loop over `v_readfirstlane` never removed a helper +/// lane from EXEC and ran into the loop budget. The target is two triangles sharing the +/// diagonal; per pixel: |ddx| of a value picked by `v_cndmask`, |ddy| of a value written +/// under `s_and_saveexec` (both 1 everywhere), and the waterfall loop's iteration count. +#[test] +fn gpu_ps_masks_hold_helper_lanes_on_triangle_edges() { + if !gpu_ready() { + return; + } + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + let vs = super::dxc::compile("float4 main(float2 p : POSITION) : SV_Position { return float4(p, 0.5, 1.0); }\n", "main", "vs_6_6", &[]).unwrap(); + for wave64 in [true, false] { + let pt = helper_lane_masks_ps(wave64); + assert!(pt.complete(), "{:?}\n{}", pt.unsupported_why, pt.hlsl); + let ps = super::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); + // the whole target as two triangles sharing the diagonal x = y + let quad = [-1.0f32, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0]; + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + let size = 32usize; + let px = runner::draw(&vs, &ps, &layout, &quad, 8, &[], &[], size as u32, [9.0; 4]).unwrap(); + let lanes = if wave64 { 64.0 } else { 32.0 }; + let bad: Vec<(usize, usize, [f32; 4])> = (0..size * size) + .filter(|&i| { + let p = px[i]; + p[0].abs() != 1.0 || p[1].abs() != 1.0 || !(1.0..=lanes).contains(&p[2]) || p[3] != 1.0 + }) + .map(|i| (i % size, i / size, px[i])) + .collect(); + let count = |k: usize, ok: &dyn Fn(f32) -> bool| px.iter().filter(|p| !ok(p[k])).count(); + let (dx, dy, it) = (count(0, &|v| v.abs() == 1.0), count(1, &|v| v.abs() == 1.0), count(2, &|v| (1.0..=lanes).contains(&v))); + println!("wave64 {wave64}: {} of {} pixels wrong (ddx {dx}, ddy {dy}, loop {it}), first: {:?}", bad.len(), size * size, bad.iter().take(6).collect::>()); + assert!(bad.is_empty(), "wave64 {wave64}: {} pixels wrong (ddx {dx}, ddy {dy}, loop {it}; |ddx|, |ddy|, loop iterations, 1), first {:?}", bad.len(), &bad[..bad.len().min(6)]); + } +} + +/// The masks of a waterfall loop in a pixel shader take the helper lanes' bits from quad reads +/// of the compare's vector operand, not of the compare (#134): AMD's RDNA2 compiler crashed in +/// `CreateGraphicsPipelineState` on quad reads of a value computed from a `WaveReadLaneAt` in a +/// loop (WarmMilkCodes, RX 6600 XT), which `ballot_px` gave the loop's `v_cmp`. Outside loops the +/// masks keep `ballot_px`. CPU only: what the GPU sees is `gpu_ps_masks_hold_helper_lanes_on_triangle_edges`. +#[test] +fn ps_masks_in_loops_quad_read_the_operands_not_the_compare() { + for wave64 in [true, false] { + let pt = helper_lane_masks_ps(wave64); + assert!(pt.complete(), "{:?}\n{}", pt.unsupported_why, pt.hlsl); + let (before, rest) = pt.hlsl.split_once("[loop] for (;;) {").unwrap_or_else(|| panic!("no loop\n{}", pt.hlsl)); + let body = &rest[..rest.find("\n }\n").unwrap_or_else(|| panic!("no loop end\n{}", pt.hlsl))]; + assert!(!body.contains("ballot_px(") && !body.contains("QuadReadAcross"), "wave64 {wave64}: a quad read of a compare in the loop\n{body}"); + assert!(body.contains("ballot_px_quad(") && body.contains("QuadReadLaneAt(v2, 3u)"), "wave64 {wave64}: the loop's v_cmp without its operand's quad reads\n{body}"); + // one read per register and member, though the float compare names v2 twice (NaN test, ==) + assert_eq!(body.matches("QuadReadLaneAt(v2, ").count(), 4, "wave64 {wave64}\n{body}"); + assert!(before.contains("= ballot_px(and("), "wave64 {wave64}: the masks before the loop lost ballot_px\n{before}"); + } +} + +/// The pixel shader of the two tests above, translated: after `s_wqm`, a mask read by +/// `v_cndmask` (A), one for `s_and_saveexec` (B) and a waterfall loop over `v_readfirstlane` of +/// pos.x (C); exports |ddx| of A, |ddy| of B, C's iteration count and 1. +fn helper_lane_masks_ps(wave64: bool) -> super::Translation { + use super::PsInterface; + { + // the wave-size forms of the scalar mask instructions; EXEC / VCC = their low words in wave32 + let (mov, wqm, and_save, xor) = if wave64 { + ("S_MOV_B64", "S_WQM_B64", "S_AND_SAVEEXEC_B64", "S_XOR_B64") + } else { + ("S_MOV_B32", "S_WQM_B32", "S_AND_SAVEEXEC_B32", "S_XOR_B32") + }; + let sop1 = |n: &'static str, d: u64, s: u64| (n, "ENC_SOP1", vec![("SDST", d), ("SSRC0", s)], None); + type I = (&'static str, &'static str, Vec<(&'static str, u64)>, Option); + let head: Vec = vec![ + sop1(mov, 20, 126), // s[20:21] = the live lanes + sop1(wqm, 126, 126), + // A: v4 = v_cndmask(0, pos.x, 0 < pos.x) – pos.x in every lane; v6 = v4 of the quad's + // other column (quad_perm [1,0,3,2]) - v4 + ("V_CMP_LT_F32", "ENC_VOPC", vec![("SRC0", 128), ("VSRC1", 2)], None), + ("V_CNDMASK_B32", "ENC_VOP2", vec![("VDST", 4), ("SRC0", 128), ("VSRC1", 2)], None), + ("V_MOV_B32", "VOP1_VOP_DPP16", vec![("VDST", 5), ("SRC0", 0xFA), ("VSRC0", 4), ("DPP_CTRL", 0xB1), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None), + ("V_SUB_F32", "ENC_VOP2", vec![("VDST", 6), ("SRC0", V + 5), ("VSRC1", 4)], None), + // B: v7 = pos.y under s_and_saveexec(0 < pos.y); v9 = v7 of the quad's other row + // (quad_perm [2,3,0,1]) - v7 + ("V_CMP_LT_F32", "ENC_VOPC", vec![("SRC0", 128), ("VSRC1", 3)], None), + sop1(and_save, 22, 106), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 7), ("SRC0", V + 3)], None), + sop1(mov, 126, 22), + ("V_MOV_B32", "VOP1_VOP_DPP16", vec![("VDST", 8), ("SRC0", 0xFA), ("VSRC0", 7), ("DPP_CTRL", 0x4E), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None), + ("V_SUB_F32", "ENC_VOP2", vec![("VDST", 9), ("SRC0", V + 8), ("VSRC1", 7)], None), + // C: a waterfall loop over pos.x, s8 = its iterations + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 8), ("SSRC0", 128)], None), + sop1(mov, 24, 126), + ]; + let body: Vec = vec![ + ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 4), ("SRC0", V + 2)], None), + ("V_CMP_EQ_F32", "ENC_VOPC", vec![("SRC0", 4), ("VSRC1", 2)], None), + sop1(and_save, 26, 106), + ("S_ADD_U32", "ENC_SOP2", vec![("SDST", 8), ("SSRC0", 8), ("SSRC1", 129)], None), + (xor, "ENC_SOP2", vec![("SDST", 126), ("SSRC0", 26), ("SSRC1", 126)], None), + ]; + let tail: Vec = vec![ + sop1(mov, 126, 24), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 10), ("SRC0", 8)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 11), ("SRC0", 242)], None), + sop1(mov, 126, 20), // back to the live lanes for the export + ("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 6), ("VSRC1", 9), ("VSRC2", 10), ("VSRC3", 11), ("DONE", 1), ("VM", 1)], None), + ]; + let enc = |l: &[I]| -> Vec { l.iter().flat_map(|(n, e, f, x)| encode(n, e, f, *x).unwrap_or_else(|err| panic!("{n}: {err}"))).collect() }; + let body_code = enc(&body); + let back = (-((body_code.len() as i64 + 4) / 4)) as u16 as u64; + let mut ps_code = enc(&head); + ps_code.extend(&body_code); + ps_code.extend(encode("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", back)], None).unwrap()); + ps_code.extend(enc(&tail)); + ps_code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None }; + translate(&ps_code, &Options { mode: Mode::Pixel(psi), wave64, ..Default::default() }).unwrap() + } +} + +/// What the pixel shaders' masks (`ballot_px`) and lane reads (`rla`) rely on, checked on the +/// adapter with native HLSL on the same two triangles: a quad is hardware lanes 4k..4k+3 (X = ^1, +/// Y = ^2, diagonal = ^3), and a helper lane gets the wave's result of a `WaveActiveBallot` – +/// each lane holds its own copy of EXEC, a helper lane's included. Not every wave op does that: +/// `WaveActiveBitOr` gave helper lanes another value on an RTX 5070 Ti (printed, not checked). +#[test] +fn gpu_ps_helper_lanes_see_ballots_and_quads_are_lanes_4k() { + if !gpu_ready() { + return; + } + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + let vs = super::dxc::compile("float4 main(float2 p : POSITION) : SV_Position { return float4(p, 0.5, 1.0); }\n", "main", "vs_6_6", &[]).unwrap(); + // per pixel: is the quad's other column a helper lane; does it see this lane's ballot and + // bit-or; are this lane and that one at lanes 4k..4k+3 + let src = "float4 main(float4 p : SV_Position) : SV_Target {\n\ + uint l = WaveGetLaneIndex();\n\ + uint hl = IsHelperLane() ? 1u : 0u;\n\ + uint b = WaveActiveBallot(((uint)p.x & 3u) == 1u).x;\n\ + uint o = WaveActiveBitOr(1u << (l & 31u));\n\ + bool lay = QuadReadAcrossX(l) == (l ^ 1u) && QuadReadAcrossY(l) == (l ^ 2u) && QuadReadAcrossDiagonal(l) == (l ^ 3u) && QuadReadLaneAt(l, 0u) == (l & ~3u);\n\ + bool both = lay && QuadReadAcrossX((uint)lay) != 0u;\n\ + return float4(QuadReadAcrossX(hl), QuadReadAcrossX(b) == b ? 1.0 : 0.0, QuadReadAcrossX(o) == o ? 1.0 : 0.0, both ? 1.0 : 0.0);\n}\n"; + let ps = super::dxc::compile(src, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + let quad = [-1.0f32, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0]; + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + let px = runner::draw(&vs, &ps, &layout, &quad, 8, &[], &[], 32, [9.0; 4]).unwrap(); + let helpers: Vec<[f32; 4]> = px.iter().copied().filter(|p| p[0] == 1.0).collect(); + let ballot = helpers.iter().filter(|p| p[1] == 1.0).count(); + let bit_or = helpers.iter().filter(|p| p[2] == 1.0).count(); + let quads = px.iter().filter(|p| p[3] == 1.0).count(); + println!("{:?}: {} pixels next to a helper lane; its ballot right in {ballot}, its bit-or in {bit_or}; quads at lanes 4k in {quads} of {}", runner::adapter(), helpers.len(), px.len()); + assert!(!helpers.is_empty(), "no helper lanes along the diagonal"); + assert_eq!(ballot, helpers.len(), "helper lanes without the wave's ballot"); + assert_eq!(quads, px.len(), "quads not at hardware lanes 4k..4k+3"); +} + /// XCL image descriptor (T#, GFX10 layout): BASE_ADDRESS = SRV heap index, FORMAT, TYPE. fn tsharp(index: u32, format: u32, ty: u32) -> [u32; 8] { [index, format << 20, 0, ty << 28, 0, 0, 0, 0] diff --git a/crates/xcl/src/gpu/recomp/x64_masks.rs b/crates/xcl/src/gpu/recomp/x64_masks.rs index 431e57b..0da170d 100644 --- a/crates/xcl/src/gpu/recomp/x64_masks.rs +++ b/crates/xcl/src/gpu/recomp/x64_masks.rs @@ -7,6 +7,8 @@ //! over the SGPRs: a register is *whole-live* after an instruction when some path may read //! its whole value (any SALU / SMEM / VALU scalar operand, a branch on VCCZ, …) before it is //! written again. A mask write whose destination is not whole-live needs no exchange. +//! Pixel shaders use the same analysis: such a mask needs only the reading lane's own bit, not +//! the quad reads that give every helper lane's bit (`ballot_px_local` / `ballot_px`, emit.rs). //! //! After a mask stays in its half the two halves hold different values in its registers, so a //! whole read that is missed here – or a write taken for a full overwrite that is not one – From 0f5b6ff99ae5f90325fcd14dfbfd0f1424dfa5a9 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:11:22 -0700 Subject: [PATCH 25/37] Crash diagnostics: thread dump at the unhandled exception; XCL_TRACE_ALLOC commit tracer From ivall/xcl#164 by @Sr-0w, squashed; conflict resolved by hand. --- crates/xcl/src/alloc_trace.rs | 142 ++++++++++++++++++++++++++++++ crates/xcl/src/eh.rs | 6 ++ crates/xcl/src/hle/d3d12x/real.rs | 10 ++- crates/xcl/src/host.rs | 1 + crates/xcl/src/lib.rs | 1 + 5 files changed, 156 insertions(+), 4 deletions(-) create mode 100644 crates/xcl/src/alloc_trace.rs diff --git a/crates/xcl/src/alloc_trace.rs b/crates/xcl/src/alloc_trace.rs new file mode 100644 index 0000000..b792827 --- /dev/null +++ b/crates/xcl/src/alloc_trace.rs @@ -0,0 +1,142 @@ +//! `XCL_TRACE_ALLOC=1`: who commits big blocks of memory. `ntdll!NtAllocateVirtualMemory` is +//! detoured; every commit of `XCL_TRACE_ALLOC_MIN` bytes or more (default 1 MiB) is counted under +//! its call stack, and the stacks holding the most are logged every 15 s – the title's, XCL's +//! and the driver's allocations alike (they all end in that call). +//! +//! The detour runs inside the heap's own allocations (with the heap lock held): it takes no +//! lock and allocates nothing – the sites are a fixed table filled with atomics. + +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; + +static ORIG: AtomicUsize = AtomicUsize::new(0); +static MIN: AtomicUsize = AtomicUsize::new(1 << 20); + +const FRAMES: usize = 40; +const SLOTS: usize = 4096; + +struct Site { + /// stack hash (0: free) + key: AtomicU64, + /// frames written (by the thread that claimed the slot) + ready: AtomicUsize, + frames: [AtomicUsize; FRAMES], + count: AtomicU64, + bytes: AtomicU64, +} + +#[allow(clippy::declare_interior_mutable_const)] +const EMPTY: Site = Site { + key: AtomicU64::new(0), + ready: AtomicUsize::new(0), + frames: [const { AtomicUsize::new(0) }; FRAMES], + count: AtomicU64::new(0), + bytes: AtomicU64::new(0), +}; +static SITES: [Site; SLOTS] = [EMPTY; SLOTS]; +static LOST: AtomicU64 = AtomicU64::new(0); + +unsafe extern "system" fn hk_alloc(process: isize, base: *mut usize, zero_bits: usize, size: *mut usize, kind: u32, protect: u32) -> i32 { + let orig: unsafe extern "system" fn(isize, *mut usize, usize, *mut usize, u32, u32) -> i32 = std::mem::transmute(ORIG.load(Ordering::Acquire)); + let st = orig(process, base, zero_bits, size, kind, protect); + // the current process (-1), committing, succeeded + if st >= 0 && process == -1 && kind & 0x1000 != 0 && !size.is_null() && *size >= MIN.load(Ordering::Relaxed) { + record(*size as u64); + } + st +} + +unsafe fn record(n: u64) { + let mut frames = [0usize; FRAMES]; + windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace(2, FRAMES as u32, frames.as_mut_ptr() as *mut _, std::ptr::null_mut()); + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for f in frames { + h = (h ^ f as u64).wrapping_mul(0x100_0000_01b3); + } + let h = h | 1; + let mut i = h as usize % SLOTS; + for _ in 0..SLOTS { + let s = &SITES[i]; + let k = s.key.load(Ordering::Acquire); + if k == h { + s.count.fetch_add(1, Ordering::Relaxed); + s.bytes.fetch_add(n, Ordering::Relaxed); + return; + } + if k == 0 && s.key.compare_exchange(0, h, Ordering::AcqRel, Ordering::Acquire).is_ok() { + for (d, f) in s.frames.iter().zip(frames) { + d.store(f, Ordering::Relaxed); + } + s.ready.store(1, Ordering::Release); + s.count.fetch_add(1, Ordering::Relaxed); + s.bytes.fetch_add(n, Ordering::Relaxed); + return; + } + if s.key.load(Ordering::Acquire) == h { + continue; // claimed for this stack just now: counted on the next look + } + i = (i + 1) % SLOTS; + } + LOST.fetch_add(n, Ordering::Relaxed); +} + +fn report() { + let mut top: Vec<(usize, u64, u64)> = SITES + .iter() + .enumerate() + .filter(|(_, s)| s.ready.load(Ordering::Acquire) != 0) + .map(|(i, s)| (i, s.count.load(Ordering::Relaxed), s.bytes.load(Ordering::Relaxed))) + .collect(); + top.sort_by(|a, b| b.2.cmp(&a.2)); + let total: u64 = top.iter().map(|t| t.2).sum(); + let gb = |b: u64| b as f64 / (1u64 << 30) as f64; + crate::xlog_info!( + "alloc trace: {:.2} GB committed in blocks of {} KB or more, {} call stacks ({:.2} GB not placed)", + gb(total), + MIN.load(Ordering::Relaxed) >> 10, + top.len(), + gb(LOST.load(Ordering::Relaxed)) + ); + // by the first module that is not the heap / CRT / Windows' allocator + let mut by_module: std::collections::HashMap = std::collections::HashMap::new(); + for &(i, _, bytes) in &top { + let owner = SITES[i] + .frames + .iter() + .map(|f| f.load(Ordering::Relaxed)) + .take_while(|&f| f != 0) + .map(crate::modules::describe_address) + .find(|d| !["ntdll.dll", "ucrtbase.dll", "KERNELBASE.dll", "KERNEL32.DLL", "msvcrt.dll", "d3d12.dll"].iter().any(|m| d.starts_with(m))) + .map(|d| d.split('+').next().unwrap_or("?").to_string()) + .unwrap_or_else(|| "?".into()); + *by_module.entry(owner).or_default() += bytes; + } + let mut mods: Vec<_> = by_module.into_iter().collect(); + mods.sort_by(|a, b| b.1.cmp(&a.1)); + crate::xlog_info!("alloc trace: by module: {}", mods.iter().take(8).map(|(m, b)| format!("{m} {:.2} GB", gb(*b))).collect::>().join(", ")); + for &(i, count, bytes) in top.iter().take(8) { + let stack: Vec = SITES[i].frames.iter().map(|f| f.load(Ordering::Relaxed)).take_while(|&f| f != 0).map(crate::modules::describe_address).collect(); + let tail: Vec<&String> = stack.iter().filter(|s| !s.starts_with("amdxc64.dll") && !s.starts_with("ntdll.dll")).collect(); + crate::xlog_info!("alloc trace: {:.2} GB in {count} blocks: {} … callers: {:?}", gb(bytes), stack.iter().take(4).cloned().collect::>().join(" < "), tail); + } + crate::log::flush(); +} + +pub fn install() { + if std::env::var_os("XCL_TRACE_ALLOC").is_none() { + return; + } + if let Some(m) = std::env::var("XCL_TRACE_ALLOC_MIN").ok().and_then(|v| v.parse::().ok()) { + MIN.store(m, Ordering::Relaxed); + } + unsafe { + if let Err(e) = crate::hooks::hook("ntdll.dll", "NtAllocateVirtualMemory", hk_alloc as usize, &ORIG) { + crate::xlog_warn!("alloc trace: {e}"); + return; + } + } + crate::xlog_info!("alloc trace: on (commits of {} bytes or more)", MIN.load(Ordering::Relaxed)); + let _ = std::thread::Builder::new().name("xcl-alloc-trace".into()).spawn(|| loop { + std::thread::sleep(std::time::Duration::from_secs(15)); + report(); + }); +} diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index f065bc1..4aa583d 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -110,6 +110,12 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i ); crate::xlog_error!("{msg}"); crate::report::write_final(Some(msg)); + // the other threads now: a title crash handler (Breakpad) can keep the process for + // minutes before it ends (the retail title's watchdog: what was its silent thread doing?) + static DUMPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !DUMPED.swap(true, Ordering::AcqRel) { + dump_threads(); + } crate::log::flush(); } match TITLE_FILTER.load(Ordering::Acquire) { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bb8ae1d..a49ed84 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -541,20 +541,22 @@ pub fn init() -> Result { } } -/// A debug layer message: errors and warnings into the log – the first 8 of each message id -/// (3 000 in all). One cap for all of them (200) was used up in seconds by two per-frame state -/// errors of a retail game, long before the message that came with its device removal. +/// A debug layer message into the log: the first 20 errors and the first 8 warnings of each +/// message id (3 000 in all). One cap for all of them (200) was used up in seconds by two +/// per-frame state errors of a retail game, long before the message that came with its device +/// removal. unsafe extern "system" fn debug_message(_category: D3D12_MESSAGE_CATEGORY, severity: D3D12_MESSAGE_SEVERITY, id: D3D12_MESSAGE_ID, text: windows::core::PCSTR, _context: *mut c_void) { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); static PER_ID: Mutex>> = Mutex::new(None); if severity.0 > D3D12_MESSAGE_SEVERITY_WARNING.0 { return; } + let cap = if severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 { 20 } else { 8 }; { let mut g = PER_ID.lock().unwrap(); let n = g.get_or_insert_with(HashMap::new).entry(id.0).or_insert(0); *n += 1; - if *n > 8 { + if *n > cap { return; } } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 07d5bcf..d1e48c6 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -125,6 +125,7 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::xlog_error!("hook RtlPcToFileHeader: {e} – C++ exceptions in the game may not work"); } crate::eh::install_crash_handler(); + crate::alloc_trace::install(); crate::eh::start_probes(); HOST_MODE.store(true, Ordering::Release); diff --git a/crates/xcl/src/lib.rs b/crates/xcl/src/lib.rs index 6f828ca..ea6b7c4 100644 --- a/crates/xcl/src/lib.rs +++ b/crates/xcl/src/lib.rs @@ -8,6 +8,7 @@ #[macro_use] pub mod log; pub mod manifest; +pub mod alloc_trace; pub mod config; pub mod disasm; pub mod eh; From 8293b752704628b532dbe61e6b741ba743dab5c1 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:12:04 -0700 Subject: [PATCH 26/37] D3D12.X: pipelines in two passes are drawn (console MS via DispatchMesh, VS+GS via Draw*) From ivall/xcl#215 by @RemingtonWilcox, squashed; conflict resolved by hand. --- crates/xcl/src/gpu/recomp/fetch.rs | 289 +++++++++++ crates/xcl/src/gpu/recomp/mod.rs | 1 + crates/xcl/src/hle/d3d12x/bind.rs | 322 +++++++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 11 + crates/xcl/src/hle/d3d12x/mod.rs | 2 + crates/xcl/src/hle/d3d12x/real.rs | 113 ++++- crates/xcl/src/hle/d3d12x/two_pass_tests.rs | 536 ++++++++++++++++++++ 7 files changed, 1250 insertions(+), 24 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/fetch.rs create mode 100644 crates/xcl/src/hle/d3d12x/two_pass_tests.rs diff --git a/crates/xcl/src/gpu/recomp/fetch.rs b/crates/xcl/src/gpu/recomp/fetch.rs new file mode 100644 index 0000000..30b95d5 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/fetch.rs @@ -0,0 +1,289 @@ +//! The vertex fetch of a legacy GS pipeline drawn in two passes. +//! +//! The geometry-mode compute pass (`Mode::Geometry`) reads its ES vertex inputs pre-fetched +//! from `mem`: one float4 (raw bits) per ES input register for each vertex of each triangle, +//! at io[`IO_GS_VERTICES`] (`super::IO_GS_VERTICES`). The console's fetch shader would have +//! made them from the title's vertex buffers; here a small compute shader does, from the +//! pipeline's input layout and the list's vertex and index buffers, before the draw's two +//! passes. +//! +//! Its root signature ([`root_signature`]): b0 = [`CONSTANTS`] root constants (see +//! [`Constants`]), t0 = index buffer, t1..t8 = the vertex buffer slots the layout uses +//! ([`MAX_SLOTS`]), u0 = the fetched vertices. Buffers are bound at a 4-byte aligned address +//! with the byte delta to the view's start and the view's size in the constants: nothing is +//! read past a view (the root descriptors have no bounds). + +use std::fmt::Write; + +/// vertex buffer slots one fetch can read +pub const MAX_SLOTS: usize = 8; +/// root constants of the fetch shader (dwords) +pub const CONSTANTS: u32 = 8 + 4 * MAX_SLOTS as u32; +/// threads per group of the fetch shader (one vertex each) +pub const THREADS: u32 = 64; + +/// One ES input register the fetch fills: from vertex buffer `slot` (index into the fetch's +/// slot list) at byte `offset` of each vertex (or instance), in DXGI format `format`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Element { + pub register: u32, + pub slot: u32, + pub offset: u32, + pub format: u32, + pub per_instance: bool, +} + +/// The fetch shader's root constants. +#[derive(Debug, Clone, Copy, Default)] +#[repr(C)] +pub struct Constants { + /// vertices to fetch (3 per triangle) + pub count: u32, + /// first index (indexed) or first vertex + pub first: u32, + pub base_vertex: i32, + /// bit 0: indexed, bit 1: 16-bit indices + pub flags: u32, + /// index buffer: bytes from the bound address to the view, bytes readable from the bound address + pub ib_delta: u32, + pub ib_bytes: u32, + pub first_instance: u32, + pub pad: u32, + /// per slot: delta, stride, bytes readable, 0 + pub slots: [[u32; 4]; MAX_SLOTS], +} + +impl Constants { + pub fn words(&self) -> Vec { + let mut w = vec![self.count, self.first, self.base_vertex as u32, self.flags, self.ib_delta, self.ib_bytes, self.first_instance, self.pad]; + for s in &self.slots { + w.extend_from_slice(s); + } + w + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Num { + Float, + Unorm, + Snorm, + Uint, + Sint, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Pack { + /// n components of 32 / 16 / 8 bits + Bits(u32), + /// R10G10B10A2 + Rgb10a2, +} + +/// (components, packing, number kind, BGRA order) of a DXGI vertex format. +fn format_info(f: u32) -> Option<(u32, Pack, Num, bool)> { + use Num::*; + use Pack::*; + Some(match f { + 2 => (4, Bits(32), Float, false), + 3 => (4, Bits(32), Uint, false), + 4 => (4, Bits(32), Sint, false), + 6 => (3, Bits(32), Float, false), + 7 => (3, Bits(32), Uint, false), + 8 => (3, Bits(32), Sint, false), + 10 => (4, Bits(16), Float, false), + 11 => (4, Bits(16), Unorm, false), + 12 => (4, Bits(16), Uint, false), + 13 => (4, Bits(16), Snorm, false), + 14 => (4, Bits(16), Sint, false), + 16 => (2, Bits(32), Float, false), + 17 => (2, Bits(32), Uint, false), + 18 => (2, Bits(32), Sint, false), + 24 => (4, Rgb10a2, Unorm, false), + 25 => (4, Rgb10a2, Uint, false), + 28 => (4, Bits(8), Unorm, false), + 30 => (4, Bits(8), Uint, false), + 31 => (4, Bits(8), Snorm, false), + 32 => (4, Bits(8), Sint, false), + 34 => (2, Bits(16), Float, false), + 35 => (2, Bits(16), Unorm, false), + 36 => (2, Bits(16), Uint, false), + 37 => (2, Bits(16), Snorm, false), + 38 => (2, Bits(16), Sint, false), + 41 => (1, Bits(32), Float, false), + 42 => (1, Bits(32), Uint, false), + 43 => (1, Bits(32), Sint, false), + 49 => (2, Bits(8), Unorm, false), + 50 => (2, Bits(8), Uint, false), + 51 => (2, Bits(8), Snorm, false), + 52 => (2, Bits(8), Sint, false), + 54 => (1, Bits(16), Float, false), + 56 => (1, Bits(16), Unorm, false), + 57 => (1, Bits(16), Uint, false), + 58 => (1, Bits(16), Snorm, false), + 59 => (1, Bits(16), Sint, false), + 61 => (1, Bits(8), Unorm, false), + 62 => (1, Bits(8), Uint, false), + 63 => (1, Bits(8), Snorm, false), + 64 => (1, Bits(8), Sint, false), + 87 => (4, Bits(8), Unorm, true), + _ => return None, + }) +} + +/// Whether the fetch can read DXGI format `f`. +pub fn supported(f: u32) -> bool { + format_info(f).is_some() +} + +/// Bytes of one element in DXGI format `f` (for D3D12_APPEND_ALIGNED_ELEMENT). +pub fn bytes(f: u32) -> Option { + format_info(f).map(|(n, pack, _, _)| match pack { + Pack::Bits(b) => n * b / 8, + Pack::Rgb10a2 => 4, + }) +} + +/// HLSL that makes component `i` (raw bits, uint) of the element whose words are w0..w3. +fn component(i: u32, pack: Pack, num: Num) -> String { + let (raw, bits) = match pack { + Pack::Bits(32) => (format!("w{i}"), 32), + Pack::Bits(b) => { + let per_word = 32 / b; + let (w, sh) = (i / per_word, (i % per_word) * b); + (format!("((w{w} >> {sh}u) & {:#x}u)", (1u64 << b) - 1), b) + } + Pack::Rgb10a2 => { + let (sh, b) = [(0, 10), (10, 10), (20, 10), (30, 2)][i as usize]; + (format!("((w0 >> {sh}u) & {:#x}u)", (1u32 << b) - 1), b) + } + }; + let max = ((1u64 << bits) - 1) as f64; + let smax = ((1u64 << (bits - 1)) - 1) as f64; + let sext = |r: &str| if bits == 32 { format!("int({r})") } else { format!("(int({r} << {}u) >> {})", 32 - bits, 32 - bits) }; + match (num, bits) { + (Num::Float, 32) | (Num::Uint, _) => raw, + (Num::Sint, _) => format!("uint({})", sext(&raw)), + (Num::Float, 16) => format!("asuint(f16tof32({raw}))"), + (Num::Float, _) => raw, + (Num::Unorm, _) => format!("asuint(float({raw}) / {max:.1})"), + (Num::Snorm, _) => format!("asuint(max(float({}) / {smax:.1}, -1.0))", sext(&raw)), + } +} + +/// The fetch compute shader for ES input registers `0..registers` (each vertex: `registers` +/// float4s, registers without an element zero). +pub fn hlsl(registers: u32, elements: &[Element]) -> Result { + let mut h = String::new(); + h.push_str("ByteAddressBuffer ib : register(t0);\n"); + for s in 0..MAX_SLOTS { + let _ = writeln!(h, "ByteAddressBuffer vb{s} : register(t{});", s + 1); + } + h.push_str("RWByteAddressBuffer outb : register(u0);\n"); + let _ = writeln!( + h, + "cbuffer C : register(b0) {{ uint count; uint first; int base_vertex; uint flags; uint ib_delta; uint ib_bytes; uint first_instance; uint pad0; uint4 slot[{MAX_SLOTS}]; }};" + ); + // a dword at any byte address, 0 past the readable bytes + h.push_str( + "uint ld(ByteAddressBuffer b, uint a, uint size)\n{\n if (a + 4u > size) return 0u;\n uint s = (a & 3u) * 8u;\n uint lo = b.Load(a & ~3u);\n if (s == 0u) return lo;\n uint hi = (a & ~3u) + 8u <= size ? b.Load((a & ~3u) + 4u) : 0u;\n return (lo >> s) | (hi << (32u - s));\n}\n", + ); + let _ = writeln!(h, "[numthreads({THREADS}, 1, 1)]\nvoid main(uint id : SV_DispatchThreadID)\n{{"); + h.push_str(" if (id >= count) return;\n uint vtx;\n"); + h.push_str(" if ((flags & 1u) != 0u) {\n uint a = ib_delta + (first + id) * ((flags & 2u) != 0u ? 2u : 4u);\n uint w = a + ((flags & 2u) != 0u ? 2u : 4u) <= ib_bytes ? ib.Load(a & ~3u) : 0u;\n uint i = (flags & 2u) != 0u ? ((a & 2u) != 0u ? (w >> 16) : (w & 0xFFFFu)) : w;\n vtx = uint(int(i) + base_vertex);\n } else {\n vtx = first + id;\n }\n"); + let _ = writeln!(h, " uint o = id * {}u;", registers * 16); + for r in 0..registers { + let Some(e) = elements.iter().find(|e| e.register == r) else { + let _ = writeln!(h, " outb.Store4(o + {}u, uint4(0u, 0u, 0u, 0u));", r * 16); + continue; + }; + if e.slot as usize >= MAX_SLOTS { + return Err(format!("register {r}: vertex buffer slot {} of more than {MAX_SLOTS}", e.slot)); + } + let (n, pack, num, bgra) = format_info(e.format).ok_or_else(|| format!("register {r}: vertex format {} not fetched yet", e.format))?; + let words = match pack { + Pack::Bits(b) => (n * b).div_ceil(32), + Pack::Rgb10a2 => 1, + }; + let index = if e.per_instance { "first_instance" } else { "vtx" }; + let s = e.slot; + let _ = writeln!(h, " {{\n uint a = slot[{s}].x + {index} * slot[{s}].y + {}u;", e.offset); + for w in 0..words { + let _ = writeln!(h, " uint w{w} = ld(vb{s}, a + {}u, slot[{s}].z);", 4 * w); + } + let one = if matches!(num, Num::Uint | Num::Sint) { "1u" } else { "0x3F800000u" }; + let mut c: Vec = (0..4).map(|i| if i < n { component(i, pack, num) } else if i == 3 { one.into() } else { "0u".into() }).collect(); + if bgra { + c.swap(0, 2); + } + let _ = writeln!(h, " outb.Store4(o + {}u, uint4({}, {}, {}, {}));\n }}", r * 16, c[0], c[1], c[2], c[3]); + } + h.push_str("}\n"); + Ok(h) +} + +/// The fetch shader's root signature (see the module docs). +pub fn root_signature(dev: &windows::Win32::Graphics::Direct3D12::ID3D12Device) -> Result { + use windows::Win32::Graphics::Direct3D12::*; + let mut params = vec![D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: CONSTANTS } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }]; + for t in 0..=MAX_SLOTS as u32 { + params.push(D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: t, RegisterSpace: 0 } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } + params.push(D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: params.len() as u32, pParameters: params.as_ptr(), ..Default::default() }; + unsafe { + let mut blob = None; + let mut err = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, Some(&mut err)).map_err(|e| format!("serialize the fetch root signature: {e}"))?; + let blob = blob.ok_or("no root signature blob")?; + dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())).map_err(|e| format!("fetch root signature: {e}")) + } +} + +/// root parameter of the index buffer, of vertex buffer slot 0, of the output +pub const PARAM_IB: u32 = 1; +pub const PARAM_VB0: u32 = 2; +pub const PARAM_OUT: u32 = 2 + MAX_SLOTS as u32; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fetch_shader_reads_each_register_once_and_zeroes_the_rest() { + let e = [ + Element { register: 0, slot: 0, offset: 0, format: 6, per_instance: false }, + Element { register: 2, slot: 1, offset: 4, format: 28, per_instance: true }, + ]; + let h = hlsl(3, &e).unwrap(); + assert!(h.contains("uint o = id * 48u;")); + assert!(h.contains("outb.Store4(o + 16u, uint4(0u, 0u, 0u, 0u));"), "{h}"); + // R32G32B32_FLOAT: three words, w = 1.0 + assert!(h.contains("outb.Store4(o + 0u, uint4(w0, w1, w2, 0x3F800000u));"), "{h}"); + // R8G8B8A8_UNORM per instance, one word + assert!(h.contains("slot[1].x + first_instance * slot[1].y + 4u"), "{h}"); + assert!(h.contains("asuint(float(((w0 >> 8u) & 0xffu)) / 255.0)"), "{h}"); + assert!(hlsl(1, &[Element { register: 0, slot: 0, offset: 0, format: 26, per_instance: false }]).is_err(), "R11G11B10 not fetched yet"); + assert!(hlsl(1, &[Element { register: 0, slot: 9, offset: 0, format: 2, per_instance: false }]).is_err()); + assert_eq!(Constants::default().words().len(), CONSTANTS as usize); + } + + #[test] + fn signed_and_bgra_components() { + assert_eq!(component(1, Pack::Bits(16), Num::Sint), "uint((int(((w0 >> 16u) & 0xffffu) << 16u) >> 16))"); + let h = hlsl(1, &[Element { register: 0, slot: 0, offset: 0, format: 87, per_instance: false }]).unwrap(); + assert!(h.contains("uint4(asuint(float(((w0 >> 16u) & 0xffu)) / 255.0), asuint(float(((w0 >> 8u) & 0xffu)) / 255.0), asuint(float(((w0 >> 0u) & 0xffu)) / 255.0)"), "{h}"); + } +} diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 75c9595..82c1f3a 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -53,6 +53,7 @@ pub mod dxc; pub(crate) mod emit; +pub mod fetch; pub mod mesh_dispatch; pub mod mesh_wave; pub mod partial_waves; diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index d8df8e3..97a50db 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -217,6 +217,12 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); + if let Some(tp) = super::real::two_pass_of(pso) { + // the group / vertex counts are in GPU memory: the record buffer cannot be sized here + count(DRAWS_SKIPPED); + note_skipped(format_args!("ExecuteIndirect with a console {} pipeline (two passes) skipped – not done yet", tp.kind)); + return; + } if !gfx && !compute { return pc(this, sig, max, args, args_off, count_buf, count_off); } @@ -315,6 +321,9 @@ fn cpu_rect_expansion(pso: usize) -> bool { /// #12 DrawInstanced pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); + if gs_draw(this, vertices, instances, first_vertex, None, first_instance).is_some() { + return; + } if let Some(list) = graphics_bound(this) { if draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { return; @@ -331,6 +340,10 @@ thread_local! { /// #13 DrawIndexedInstanced pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { + DRAW_ARGS.with(|d| d.set((true, indices, instances, first_index, base_vertex))); + if gs_draw(this, indices, instances, first_index, Some(base_vertex), first_instance).is_some() { + return; + } if let Some(list) = prepare_indexed_draw(this, indices, instances, first_index, base_vertex) { super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, if first_instance != 0 { instances.max(2) } else { instances }); emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); @@ -368,6 +381,13 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); let pso = with(this, |s| s.pso); // a pipeline still being built in the background is waited for (its stand-in draws nothing) + if super::real::two_pass_of(super::pso_async::resolve_wait(pso)).is_some() { + // a draw XCL does not run in two passes (DrawIndexedX): a mesh pipeline draws no + // vertices on the PC + count(DRAWS_SKIPPED); + note_skipped(format_args!("a draw with a pipeline in two passes that is not run that way (DrawIndexedX) skipped")); + return None; + } if !super::real::is_translated_graphics(super::pso_async::resolve_wait(pso)) { count(DRAWS_PC); if super::present::trace_frame() { @@ -815,6 +835,38 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis /// arguments the console's way – compute or graphics) and the argument table in unified /// memory, u1 res, u2… the memory windows; then the pipeline. unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { + // a pipeline still being built in the background is waited for + let real = super::pso_async::resolve_wait(pso); + let views = abi_views(this, real, gfx, None, &[])?; + let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; + let rs = rs as *mut c_void; + let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; + set_abi(list, rs, &views, gfx); + let real = real as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; + list.SetPipelineState(pc); + Ok(()) +} + +/// The ABI root signature `rs` and its six root UAVs `views` on the compute or graphics side. +unsafe fn set_abi(list: &ID3D12GraphicsCommandList, rs: &ID3D12RootSignature, views: &[u64], gfx: bool) { + if gfx { + list.SetGraphicsRootSignature(rs); + for (k, v) in views.iter().enumerate() { + list.SetGraphicsRootUnorderedAccessView(k as u32, *v); + } + } else { + list.SetComputeRootSignature(rs); + for (k, v) in views.iter().enumerate() { + list.SetComputeRootUnorderedAccessView(k as u32, *v); + } + } +} + +/// The GPU addresses of the ABI's root UAVs for the kept arguments (compute or graphics): +/// u0 io (the user SGPRs, `io_patch` written over them), u1 res (`res`, or 256 bytes of its +/// own), u2… the memory windows. +unsafe fn abi_views(this: *mut c_void, real: usize, gfx: bool, res: Option, io_patch: &[(usize, u32)]) -> Result, String> { let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); let first = *windows.first().ok_or("unified memory is not open on the GPU")?; @@ -825,8 +877,6 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); Ok(p as usize) }; - // a pipeline still being built in the background is waited for - let real = super::pso_async::resolve_wait(pso); // a compute shader takes no more arguments from registers than it has (`inline_for`) let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs(real) }; let inline = layout.as_ref().map_or(0, |l| if gfx { l.inline_gfx } else { console_list::inline_for(l, user_sgprs) } as usize).min(args.len()); @@ -837,28 +887,262 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi None => vec![table_at as u32, (table_at >> 32) as u32], }; io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + for &(k, v) in io_patch { + if let Some(w) = io.get_mut(k) { + *w = v; + } + } let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; - let res_at = copy(&[0u8; 256])?; let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); - let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; - let rs = rs as *mut c_void; - let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; - let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); - if gfx { - list.SetGraphicsRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetGraphicsRootUnorderedAccessView(k as u32, v); + let res = match res { + Some(r) => r, + None => va(copy(&[0u8; 256])?), + }; + Ok([va(io_at), res].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))).collect()) +} + +// --------------------------------------------------------------------------------------- +// pipelines in two passes (console MS / NGG and legacy GS: `real::TwoPassPso`) +// --------------------------------------------------------------------------------------- + +/// D3D12's limit on thread groups in one dimension of a dispatch +const MAX_GROUPS: u32 = 65535; + +/// ID3D12GraphicsCommandList6::DispatchMesh on the PC +const PC_DISPATCH_MESH: usize = 79; + +/// Unified memory for this recording in window 0 – what `mem` (u2) holds, the memory a +/// 32-bit console address names – freed when the list's allocator is reset. GPU data only: in +/// the runtime layout window 0 is a sparse window (video memory). +unsafe fn window0_scratch(this: *mut c_void, size: usize) -> Result<*mut u8, String> { + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let size = size.max(16); + let p = if u.is_sparse_window(0) { super::sparse::alloc_in(0, size, 1 << 16).map(|(p, _)| p as *mut u8) } else { u.alloc_in(0, size, 1 << 16) }; + let p = p.ok_or_else(|| format!("window 0 of unified memory is full ({} KB for a two-pass draw)", size >> 10))?; + with(this, |s| s.uma.push(p as usize)); + Ok(p) +} + +/// A UAV barrier on all UAV accesses. +fn uav_barrier_all() -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) }, + } +} + +/// A draw with a pipeline in two passes: the console program as a compute shader over +/// `groups` thread groups (one record each, in memory of this recording), a UAV barrier, then +/// the title's mesh pipeline (pass-through MS + PS) over the records. Both passes get the kept +/// graphics root arguments (`io_patch` written over the user SGPRs). Afterwards the list has +/// the mesh pipeline and its ABI root signature bound, as after any translated draw; the +/// compute side is set again by the next translated dispatch (`bind_abi`), and the title's +/// own root signatures and arguments never reach the PC list. +unsafe fn two_pass(this: *mut c_void, list: &ID3D12GraphicsCommandList, real: usize, tp: &super::real::TwoPassPso, groups: u32, io_patch: &[(usize, u32)]) -> Result<(), String> { + if groups == 0 { + return Ok(()); + } + let mesh_groups = groups.saturating_mul(tp.mesh_groups_per_record.max(1)); + if groups > MAX_GROUPS || mesh_groups > MAX_GROUPS { + return Err(format!("{groups} groups ({mesh_groups} mesh groups) – over D3D12's {MAX_GROUPS} in one dispatch")); + } + let rec = tp.record.record_dwords() * 4; + let res = allocate_upload_memory(this, groups as usize * rec, 256); + if res.is_null() { + return Err(format!("unified memory is full ({} KB of records)", (groups as usize * rec) >> 10)); + } + // a group that allocates no output leaves its counts at 0 (the memory is reused) + for g in 0..groups as usize { + std::ptr::write_bytes(res.add(g * rec), 0, 16); + } + let res_va = super::real::uma_va_of(res as usize).ok_or("record buffer not on the GPU")?; + let views = abi_views(this, real, true, Some(res_va), io_patch)?; + let rs = |p: usize| { + let p = p as *mut c_void; + ID3D12RootSignature::from_raw_borrowed(&p).cloned() + }; + let ps = |p: usize| { + let p = p as *mut c_void; + ID3D12PipelineState::from_raw_borrowed(&p).cloned() + }; + let (crs, cpso) = (rs(tp.compute_rs).ok_or("compute root signature")?, ps(tp.compute).ok_or("compute pipeline")?); + let (mrs, mpso) = (rs(tp.mesh_rs).ok_or("mesh root signature")?, ps(real).ok_or("mesh pipeline")?); + // pass 1: the console program, one record per group + set_abi(list, &crs, &views, false); + list.SetPipelineState(&cpso); + list.Dispatch(groups, 1, 1); + list.ResourceBarrier(&[uav_barrier_all()]); + // pass 2: the records rasterised + set_abi(list, &mrs, &views, true); + list.SetPipelineState(&mpso); + let dispatch_mesh: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(super::real::orig_fn(this, PC_DISPATCH_MESH)); + dispatch_mesh(this, mesh_groups, 1, 1); + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 4 || ((n + 1).is_power_of_two() && n >= 63) { + crate::xlog_info!("D3D12.X: {} draws in two passes so far (latest: console {} over {groups} groups, {mesh_groups} mesh groups)", n + 1, tp.kind); + } + Ok(()) +} + +/// The pipeline bound on `this` (waited for if still being built) and its two-pass parts +/// (None: not such a pipeline). +fn bound_two_pass(this: *mut c_void) -> Option<(usize, std::sync::Arc)> { + let real = super::pso_async::resolve_wait(with(this, |s| s.pso)); + super::real::two_pass_of(real).map(|tp| (real, tp)) +} + +fn note_skipped(what: std::fmt::Arguments) { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: {what}"); + } +} + +/// #126 (#128 on the newer console layout: `real::NEWER_LIST_SLOTS`) DispatchMesh(x, y, z): +/// with a console mesh pipeline bound, its two passes. The slot is inferred, not seen in a +/// title yet: the console list keeps the PC's ID3D12GraphicsCommandList1 at #104–#109 and +/// RSSetShadingRate / RSSetShadingRateImage at #124 / #125, and on the PC DispatchMesh follows +/// them. With any other pipeline bound the call is logged with its arguments (they tell what +/// the method is) and dropped, as by the stub that was there. +pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: u32, z: u32) { + let Some((real, tp)) = bound_two_pass(this).filter(|(_, tp)| tp.kind == "MS") else { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: command list DispatchMesh slot called ({x:#x}, {y:#x}, {z:#x}) without a console mesh pipeline bound (pipeline {:#x}) – dropped", with(this, |s| s.pso)); } - } else { - list.SetComputeRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetComputeRootUnorderedAccessView(k as u32, v); + return; + }; + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this).cloned() else { return }; + // the translated program numbers its group by SV_GroupID.x: a grid is flattened + let groups = (x as u64) * (y as u64) * (z as u64); + if y > 1 || z > 1 { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: DispatchMesh({x}, {y}, {z}) with a console mesh pipeline – drawn as {groups} groups in a row"); } } - let real = real as *mut c_void; - let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; - list.SetPipelineState(pc); - Ok(()) + let r = u32::try_from(groups).map_err(|_| "too many groups".to_string()).and_then(|g| two_pass(this, &list, real, &tp, g, &[])); + match r { + Ok(()) => count(DRAWS), + Err(e) => { + count(DRAWS_SKIPPED); + note_skipped(format_args!("DispatchMesh({x}, {y}, {z}) with a console mesh pipeline skipped: {e}")); + } + } +} + +/// A Draw* with a pipeline in two passes bound (Some: it was – drawn or skipped). A GS +/// pipeline: XCL fetches the triangles' vertices (`recomp::fetch`), then the two passes run +/// over them. `indexed`: the base vertex of an indexed draw. +unsafe fn gs_draw(this: *mut c_void, count_: u32, instances: u32, first: u32, indexed: Option, first_instance: u32) -> Option<()> { + let (real, tp) = bound_two_pass(this)?; + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this).cloned() else { return Some(()) }; + if tp.kind != "GS" { + // a mesh pipeline draws no vertices (on the PC the call is invalid) + count(DRAWS_SKIPPED); + note_skipped(format_args!("Draw* with a console mesh pipeline bound (DispatchMesh draws it) skipped")); + return Some(()); + } + match gs_fetch_and_draw(this, &list, real, &tp, count_, instances, first, indexed, first_instance) { + Ok(()) => count(DRAWS), + Err(e) => { + count(DRAWS_SKIPPED); + note_skipped(format_args!("draw with a console GS pipeline skipped: {e}")); + } + } + Some(()) +} + +#[allow(clippy::too_many_arguments)] +unsafe fn gs_fetch_and_draw( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + real: usize, + tp: &super::real::TwoPassPso, + count_: u32, + instances: u32, + first: u32, + indexed: Option, + first_instance: u32, +) -> Result<(), String> { + use crate::gpu::recomp::fetch; + let f = match &tp.fetch { + Some(Ok(f)) => f, + Some(Err(e)) => return Err(format!("no vertex fetch ({e})")), + None => return Err("no vertex fetch".into()), + }; + let (vbs, ib, topology) = super::list_x::ia_state(this); + if topology.is_some_and(|t| t != windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32) { + return Err(format!("topology {topology:?} (triangle lists only)")); + } + if instances > 1 { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: a draw of {instances} instances with a console GS pipeline – the first only"); + } + } + if !f.missing.is_empty() { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: GS pipeline inputs without an input layout element (zero): {:?}", f.missing); + } + } + let prims = count_ / 3; + if prims == 0 || instances == 0 { + return Ok(()); + } + let groups = prims.div_ceil(crate::gpu::recomp::GS_PRIMS_PER_GROUP); + if groups > MAX_GROUPS { + return Err(format!("{prims} triangles in one draw")); + } + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let vertices = prims * 3; + let vin = window0_scratch(this, vertices as usize * f.registers.max(1) as usize * 16)?; + // io[IO_GS_VERTICES] is an offset in `mem` (u2, window 0) + let vin_offset = vin as usize - u.window(0).0; + let vin_va = super::real::uma_va_of(vin as usize).ok_or("fetched vertices not on the GPU")?; + // the fetch: buffers bound at 4-byte aligned addresses, the rest in the constants + let mut c = fetch::Constants { count: vertices, first, base_vertex: indexed.unwrap_or(0), first_instance, ..Default::default() }; + let aligned = |va: u64| va & !3; + let ib_va = match (indexed, ib) { + (Some(_), Some(v)) => { + let sixteen = v.Format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT; + c.flags = 1 | if sixteen { 2 } else { 0 }; + c.ib_delta = (v.BufferLocation & 3) as u32; + c.ib_bytes = v.SizeInBytes + c.ib_delta; + aligned(v.BufferLocation) + } + (Some(_), None) => return Err("indexed draw without an index buffer".into()), + (None, _) => vin_va, + }; + let mut slot_vas = [vin_va; fetch::MAX_SLOTS]; + for (k, slot) in f.slots.iter().enumerate() { + let v = vbs.get(slot).ok_or_else(|| format!("no vertex buffer at slot {slot}"))?; + if v.BufferLocation == 0 { + return Err(format!("vertex buffer at slot {slot} not on the GPU")); + } + let delta = (v.BufferLocation & 3) as u32; + c.slots[k] = [delta, v.StrideInBytes, v.SizeInBytes + delta, 0]; + slot_vas[k] = aligned(v.BufferLocation); + } + let rs = super::real::fetch_rs().ok_or("no vertex fetch root signature")? as *mut c_void; + let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("fetch root signature")?; + let pso = f.pso as *mut c_void; + let pso = ID3D12PipelineState::from_raw_borrowed(&pso).ok_or("fetch pipeline")?; + list.SetComputeRootSignature(rs); + let words = c.words(); + list.SetComputeRoot32BitConstants(0, words.len() as u32, words.as_ptr() as *const c_void, 0); + list.SetComputeRootShaderResourceView(fetch::PARAM_IB, ib_va); + for (k, va) in slot_vas.iter().enumerate() { + list.SetComputeRootShaderResourceView(fetch::PARAM_VB0 + k as u32, *va); + } + list.SetComputeRootUnorderedAccessView(fetch::PARAM_OUT, vin_va); + list.SetPipelineState(pso); + list.Dispatch(vertices.div_ceil(fetch::THREADS), 1, 1); + list.ResourceBarrier(&[uav_barrier_all()]); + two_pass(this, list, real, tp, groups, &[(crate::gpu::recomp::IO_GS_PRIMS, prims), (crate::gpu::recomp::IO_GS_VERTICES, vin_offset as u32)]) } #[cfg(test)] diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 80f0ce3..5a45bec 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -268,6 +268,17 @@ pub(super) fn rect_list_state(list: *mut c_void) -> Option (std::collections::BTreeMap, Option, Option) { + let g = LISTS.lock().unwrap(); + match g.as_ref().and_then(|m| m.get(&(list as usize))) { + Some(s) => (s.bindings.vertex_buffers.clone(), s.index_buffer, s.bindings.topology), + None => Default::default(), + } +} + /// `pc_va` for other modules. pub(super) fn pc_va_of(va: u64) -> u64 { pc_va(va) diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 3d06198..9c8b2fe 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -28,6 +28,8 @@ pub mod sparse; pub mod title_list; pub mod title_textures; pub mod vram; +#[cfg(test)] +mod two_pass_tests; use std::ffi::c_void; use std::sync::OnceLock; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bb8ae1d..b39d5f7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1021,6 +1021,9 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (90, l::write32_bottom_of_shader_x as usize), (93, l::kickoff_x as usize), (94, l::set_depth_bias_x as usize), + // DispatchMesh after RSSetShadingRate / RSSetShadingRateImage (#124 / #125) as on + // the PC – inferred, see `bind::dispatch_mesh` + (126, b::dispatch_mesh as usize), // console compute/BVH builder extensions (`XboxBvhBuilder.dll`) (146, l::uav_barrier_x as usize), (148, b::allocate_upload_memory as usize), @@ -3830,6 +3833,19 @@ pub struct TwoPassPso { pub mesh_groups_per_record: u32, /// "MS" or "GS" pub kind: &'static str, + /// GS: the vertex fetch in front of the compute pass (Err: why the draws cannot have one) + pub fetch: Option>, +} + +/// The vertex fetch of a GS pipeline (`recomp::fetch`): its compute pipeline state (XCL's, +/// root signature `fetch_rs`), the title's vertex buffer slot of each fetch slot, and the ES +/// input registers each vertex has. +pub struct GsFetch { + pub pso: usize, + pub slots: Vec, + pub registers: u32, + /// some ES input has no element in the input layout (zero) + pub missing: Vec, } impl Drop for TwoPassPso { @@ -3839,6 +3855,86 @@ impl Drop for TwoPassPso { } } +impl Drop for GsFetch { + fn drop(&mut self) { + super::pso_async::release(self.pso); + } +} + +/// The vertex fetch's root signature (`recomp::fetch::root_signature`), made once. +static FETCH_RS: AtomicUsize = AtomicUsize::new(0); + +pub fn fetch_rs() -> Option { + Some(FETCH_RS.load(Ordering::Acquire)).filter(|&p| p != 0) +} + +unsafe fn fetch_rs_for(this: *mut c_void) -> Result { + if let Some(p) = fetch_rs() { + return Ok(p); + } + let dev = ID3D12Device::from_raw_borrowed(&this).ok_or("device")?; + let raw = crate::gpu::recomp::fetch::root_signature(dev)?.into_raw() as usize; + match FETCH_RS.compare_exchange(0, raw, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => Ok(raw), + Err(other) => { + drop(ID3D12RootSignature::from_raw(raw as *mut c_void)); + Ok(other) + } + } +} + +/// The vertex fetch of a GS pipeline from its description's input layout and the ES inputs +/// (ISG1 of the console VS): elements matched by semantic. +unsafe fn gs_fetch(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs: &[u8]) -> Result { + use crate::gpu::recomp::fetch; + let inputs: Vec = crate::gpu::dxbc::signatures(vs).0.into_iter().filter(|e| e.system_value == 0).collect(); + let registers = inputs.iter().map(|e| e.register + 1).max().unwrap_or(0); + let layout: &[D3D12_INPUT_ELEMENT_DESC] = if d.InputLayout.pInputElementDescs.is_null() || d.InputLayout.NumElements == 0 || d.InputLayout.NumElements > 64 { + &[] + } else { + std::slice::from_raw_parts(d.InputLayout.pInputElementDescs, d.InputLayout.NumElements as usize) + }; + // offsets of D3D12_APPEND_ALIGNED_ELEMENT: after the previous element of the slot + let mut ends: HashMap = HashMap::new(); + let mut placed = Vec::new(); + for el in layout { + let name = if el.SemanticName.is_null() { String::new() } else { el.SemanticName.to_string().unwrap_or_default() }; + let f = el.Format.0 as u32; + let at = if el.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT { *ends.get(&el.InputSlot).unwrap_or(&0) } else { el.AlignedByteOffset }; + ends.insert(el.InputSlot, at + fetch::bytes(f).unwrap_or(4)); + placed.push((name, el.SemanticIndex, el.InputSlot, at, f, el.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA)); + } + let (mut slots, mut elements, mut missing) = (Vec::::new(), Vec::new(), Vec::new()); + for e in &inputs { + let Some((_, _, slot, at, f, inst)) = placed.iter().find(|p| p.0.eq_ignore_ascii_case(&e.name) && p.1 == e.index) else { + missing.push(e.semantic()); + continue; + }; + let k = match slots.iter().position(|s| s == slot) { + Some(k) => k, + None => { + slots.push(*slot); + slots.len() - 1 + } + }; + elements.push(fetch::Element { register: e.register, slot: k as u32, offset: *at, format: *f, per_instance: *inst }); + } + let hlsl = fetch::hlsl(registers, &elements)?; + let cs = crate::gpu::recomp::dxc::compile_cached(&hlsl, "main", "cs_6_6")?.0; + let rs = fetch_rs_for(this)?; + let fc: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); + let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs as *mut c_void); + cdesc.CS = bytecode(&cs); + let iid = pc_iid(Kind::PipelineState); + let mut pso: *mut c_void = std::ptr::null_mut(); + let hr = fc(this, &cdesc as *const _ as *const c_void, &iid, &mut pso); + if hr < 0 || pso.is_null() { + return Err(format!("the driver rejected the vertex fetch ({hr:#x})")); + } + Ok(GsFetch { pso: pso as usize, slots, registers, missing }) +} + static TWO_PASS: Mutex>>> = Mutex::new(None); /// The compute pass of a pipeline state XCL built from console MS / GS code. @@ -3929,7 +4025,7 @@ fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option> /// Create the mesh pipeline (`stream`, RS and shaders already in it) and the compute pass; /// the title gets the mesh pipeline state. #[allow(clippy::too_many_arguments)] -unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, kind: &'static str, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { +unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, kind: &'static str, fetch: Option>, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let Some(rs) = abi_rs_for(this, &tp.samplers) else { return E_INVALIDARG }; let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let desc: [usize; 2] = [stream.0.len(), stream.0.as_ptr() as usize]; @@ -3953,7 +4049,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: return E_INVALIDARG; } note_pso_rs(*ppv, mesh_rs); - TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); + TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind, fetch })); let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); if n < 5 || n % 1000 == 0 { crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (compute {} B + mesh {} B DXIL)", tp.cs.len(), tp.ms.len()); @@ -4035,7 +4131,7 @@ unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: * out.raw(*ty, payload, palign == 8); } } - Some(finish_two_pass(this, &out, tp, rs, "MS", riid, ppv)) + Some(finish_two_pass(this, &out, tp, rs, "MS", None, riid, ppv)) } /// A graphics PSO with a console VS + GS: the GS pipeline in two passes, as a mesh pipeline @@ -4106,7 +4202,12 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE if d.Flags.0 != 0 { out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, &d.Flags); } - finish_two_pass(this, &out, tp, rs, "GS", riid, ppv) + // the vertex fetch: a failure only keeps this pipeline's draws from running (logged there) + let fetch = gs_fetch(this, d, vs); + if let Err(e) = &fetch { + note_translation_error(format!("VS+GS vertex fetch: {e}")); + } + finish_two_pass(this, &out, tp, rs, "GS", Some(fetch), riid, ppv) } /// Rewrite a pipeline state stream with stand-in shaders. None if not possible. @@ -4615,7 +4716,9 @@ pub(super) static QUEUE_SHIFTED: AtomicBool = AtomicBool::new(false); static QUEUE_OLDER: AtomicBool = AtomicBool::new(false); /// command list slots of the newer layout → the older layout's slot of the same method -const NEWER_LIST_SLOTS: [(usize, usize); 21] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (139, 10)]; +/// (128, 126): DispatchMesh, if the shift reaches it – not seen yet; `bind::dispatch_mesh` drops +/// a call without a console mesh pipeline bound. +const NEWER_LIST_SLOTS: [(usize, usize); 22] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (128, 126), (139, 10)]; /// The title called device method `slot`, which only runtimes with the newer layouts have (a retail game /// records its first lists before any queue call could tell). diff --git a/crates/xcl/src/hle/d3d12x/two_pass_tests.rs b/crates/xcl/src/hle/d3d12x/two_pass_tests.rs new file mode 100644 index 0000000..941f21a --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/two_pass_tests.rs @@ -0,0 +1,536 @@ +//! Pipelines in two passes drawn end to end without a game: synthetic console containers (an +//! NGG mesh program; the ES variant of a VS + a GS) go through the backend device's pipeline +//! hooks, the draws are recorded through the console command list's methods (`bind`, +//! `list_x`) on a list made as for a title, and the render target is read back. +//! +//! Skipped (passing) without a D3D12 device with mesh shaders, unified memory on the GPU or DXC. + +use std::ffi::c_void; +use std::sync::Mutex; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::{bind, device_x, list_x, real, title_list}; +use crate::gpu::rdna2::encode; +use crate::gpu::recomp::dxc; +use crate::gpu::xbox::tests::{container, dxil_part, fssm}; + +/// The tests share the backend device and its counters. +static SERIAL: Mutex<()> = Mutex::new(()); + +const SIZE: u32 = 32; +const CLEAR: [f32; 4] = [-1.0, -1.0, -1.0, -1.0]; +/// VALU source code of v0 +const V: u64 = 256; + +fn f(x: f32) -> u32 { + x.to_bits() +} + +/// The backend device, when it can run these tests. +fn ready() -> Option { + if dxc::location().is_err() { + println!("no DXC – skipping"); + return None; + } + if super::backend() != super::Backend::Real { + println!("no real D3D12 device – skipping"); + return None; + } + if real::uma_window_vas().is_empty() { + println!("unified memory is not open on the GPU – skipping"); + return None; + } + let raw = real::device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }?.clone(); + let mut o7 = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let mesh = unsafe { 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; + if !mesh { + println!("GPU without mesh shaders – skipping"); + return None; + } + Some(dev) +} + +/// A v1 signature part (ISG1 / OSG1): (name, index, system value, component type, register). +fn signature(elements: &[(&str, u32, u32, u32, u32)]) -> Vec { + let mut d = Vec::new(); + d.extend_from_slice(&(elements.len() as u32).to_le_bytes()); + d.extend_from_slice(&8u32.to_le_bytes()); + let names_at = 8 + 32 * elements.len() as u32; + let mut names = Vec::new(); + for &(name, index, sv, ct, reg) in elements { + d.extend_from_slice(&0u32.to_le_bytes()); // stream + d.extend_from_slice(&(names_at + names.len() as u32).to_le_bytes()); + d.extend_from_slice(&index.to_le_bytes()); + d.extend_from_slice(&sv.to_le_bytes()); + d.extend_from_slice(&ct.to_le_bytes()); + d.extend_from_slice(®.to_le_bytes()); + d.extend_from_slice(&[0xF, 0xF, 0, 0]); + d.extend_from_slice(&0u32.to_le_bytes()); // min precision + names.extend_from_slice(name.as_bytes()); + names.push(0); + } + d.extend_from_slice(&names); + d +} + +/// A PSV0 part: `r` = the runtime info (48 bytes). +fn psv0(r: &[u8; 48]) -> Vec { + let mut part = 48u32.to_le_bytes().to_vec(); + part.extend_from_slice(r); + part.extend_from_slice(&0u32.to_le_bytes()); // resources + part +} + +/// A console shader container of DXIL kind `kind` with one FSSM (hardware stage `hw`). +fn console(kind: u32, hw: u8, code: &[u8], isg1: &[u8], osg1: &[u8], psv: Option>) -> Vec { + let dxil = dxil_part(kind, &[fssm(code, &[(hw, kind as u8)])]); + let mut parts: Vec<(&[u8; 4], &[u8])> = vec![(b"SFI0", &[0; 8]), (b"ISG1", isg1), (b"OSG1", osg1)]; + if let Some(p) = &psv { + parts.push((b"PSV0", p)); + } + parts.push((b"HASH", &[0; 20])); + parts.push((b"DXIL", &dxil)); + container(&parts) +} + +fn prog(list: &[(&str, &str, Vec<(&str, u64)>, Option)], end: bool) -> Vec { + let mut v = Vec::new(); + for (n, e, fl, l) in list { + v.extend(encode(n, e, fl, *l).unwrap_or_else(|x| panic!("{n}: {x}"))); + } + if end { + v.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + } + v +} + +/// RTS0 v2 with one parameter of `n` root constants (inline: the user SGPRs from s8). +fn rts0_constants(n: u32) -> Vec { + let words: [u32; 12] = [2, 1, 24, 0, 0, 0, 1, 0, 36, 0, 0, n]; + words.iter().flat_map(|w| w.to_le_bytes()).collect() +} + +/// A list made as for a title (wrapped, adopted by `bind` / `list_x`), with a render target, +/// viewport and scissor set on the PC list; `record` records the draw through the console +/// methods; then the target is read back. +struct Target { + dev: ID3D12Device, + alloc: ID3D12CommandAllocator, + raw_list: *mut c_void, + backing: *mut c_void, + rt: ID3D12Resource, + _heap: ID3D12DescriptorHeap, +} + +impl Target { + unsafe fn new(dev: &ID3D12Device) -> Target { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let mut raw_list: *mut c_void = std::ptr::null_mut(); + let iid = windows_sys::core::GUID::from_u128(0x5b160d0f_ac1b_4185_8ba8_b3ae42a5a455); + let hr = device_x::create_command_list_pc(dev.as_raw(), 0, D3D12_COMMAND_LIST_TYPE_DIRECT.0 as u32, alloc.as_raw() as usize, 0, &iid, &mut raw_list); + assert!(hr >= 0 && !raw_list.is_null(), "CreateCommandList: {hr:#x}"); + let backing = title_list::backing(raw_list).expect("a title's list"); + 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).unwrap(); + let rt = rt.unwrap(); + let heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }).unwrap(); + let rtv = heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&rt, None, rtv); + let list = ID3D12GraphicsCommandList::from_raw_borrowed(&backing).unwrap(); + 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 }]); + Target { dev: dev.clone(), alloc, raw_list, backing, rt, _heap: heap } + } + + /// Close, run and read back the target (one RGBA32F texel per pixel, row by row). + unsafe fn finish(self) -> Vec<[f32; 4]> { + let dev = &self.dev; + let list = ID3D12GraphicsCommandList::from_raw_borrowed(&self.backing).unwrap().clone(); + let tex = self.rt.GetDesc(); + 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 desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: total, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut rb: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).unwrap(); + let rb = rb.unwrap(); + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(&self.rt), + Subresource: 0, + StateBefore: D3D12_RESOURCE_STATE_RENDER_TARGET, + StateAfter: D3D12_RESOURCE_STATE_COPY_SOURCE, + }), + }, + }]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::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: std::mem::transmute_copy(&self.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.Close().unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + let t0 = std::time::Instant::now(); + while fence.GetCompletedValue() < 1 { + assert!(t0.elapsed().as_secs() < 20, "the GPU did not finish (device removed: {:?})", dev.GetDeviceRemovedReason()); + std::thread::yield_now(); + } + assert!(dev.GetDeviceRemovedReason().is_ok(), "device removed: {:?}", dev.GetDeviceRemovedReason()); + let mut q = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut q)).unwrap(); + 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)]); + } + } + rb.Unmap(0, None); + // the list goes as a title's does (its unified memory with its allocator) + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(self.raw_list as *const *const usize)).add(2)); + release(self.raw_list); + drop(self.alloc); + px + } +} + +/// Is pixel centre (x, y) (pixels, y down) inside triangle `t` given in clip space (y up)? +fn inside(t: [[f32; 2]; 3], x: usize, y: usize, margin: f32) -> bool { + let p = |v: [f32; 2]| ((v[0] + 1.0) * 0.5 * SIZE as f32, (1.0 - v[1]) * 0.5 * SIZE as f32); + let (a, b, c) = (p(t[0]), p(t[1]), p(t[2])); + let (qx, qy) = (x as f32 + 0.5, y as f32 + 0.5); + let area = (b.0 - a.0) * (c.1 - a.1) - (c.0 - a.0) * (b.1 - a.1); + let l1 = ((b.0 - qx) * (c.1 - qy) - (c.0 - qx) * (b.1 - qy)) / area; + let l2 = ((c.0 - qx) * (a.1 - qy) - (a.0 - qx) * (c.1 - qy)) / area; + let l3 = 1.0 - l1 - l2; + l1.min(l2).min(l3) > margin +} + +/// Console NGG program (the console's style: wave index from s3, group from v5 >> 7, +/// GS_ALLOC_REQ for 3 vertices and 1 triangle, exp pos0 / param0 / prim) in an MS container + +/// a PC PS, through `CreatePipelineState`; drawn by the console list's DispatchMesh with two +/// groups: each group's triangle (shifted right by its group) with param0.x = the group. +#[test] +fn gpu_console_mesh_pipeline_draws_through_dispatch_mesh() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let Some(dev) = ready() else { return }; + let exp = |tgt: u64, en: u64, v: [u64; 4], done: u64| ("EXP", "ENC_EXP", vec![("TGT", tgt), ("EN", en), ("VSRC0", v[0]), ("VSRC1", v[1]), ("VSRC2", v[2]), ("VSRC3", v[3]), ("DONE", done)], None); + let mut list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("S_BFE_U32", "ENC_SOP2", vec![("SDST", 0), ("SSRC0", 3), ("SSRC1", 255)], Some(0x40018)), // wave index + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", 128)], None), + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", V)], None), + ("V_LSHL_ADD_U32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 0), ("SRC1", 134), ("SRC2", V)], None), // thread in group + ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 1), ("SRC0", V + 5)], None), + ("S_LSHR_B32", "ENC_SOP2", vec![("SDST", 1), ("SSRC0", 1), ("SSRC1", 135)], None), // group = v5 >> 7 + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 124), ("SSRC0", 255)], Some(1 << 12 | 3)), // 1 primitive, 3 vertices + ("S_SENDMSG", "ENC_SOPP", vec![("SIMM16", 9)], None), + ("S_BARRIER", "ENC_SOPP", vec![], None), + ("V_CMPX_GT_U32", "ENC_VOPC", vec![("SRC0", 131), ("VSRC1", 0)], None), // threads 0..2 + ("BUFFER_LOAD_DWORDX4", "ENC_MUBUF", vec![("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 20), ("SRC0", 1)], None), + ("V_ADD_F32", "ENC_VOP2", vec![("VDST", 10), ("SRC0", V + 20), ("VSRC1", 10)], None), // x += group + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 14), ("SRC0", V + 20)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 15), ("SRC0", V)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 16), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 17), ("SRC0", 242)], None), + ]; + list.push(exp(12, 0xF, [10, 11, 12, 13], 1)); + list.push(exp(32, 0xF, [14, 15, 16, 17], 0)); + list.push(("S_MOV_B64", "ENC_SOP1", vec![("SDST", 126), ("SSRC0", 193)], None)); + list.push(("V_CMPX_EQ_U32", "ENC_VOPC", vec![("SRC0", 128), ("VSRC1", 0)], None)); // thread 0 + list.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 21), ("SRC0", 255)], Some(1 << 10 | 2 << 20))); + list.push(exp(20, 1, [21, 0, 0, 0], 1)); + let code = prog(&list, true); + let mut r = [0u8; 48]; + r[12..14].copy_from_slice(&128u16.to_le_bytes()); // max vertices + r[14..16].copy_from_slice(&128u16.to_le_bytes()); // max primitives + r[24] = 13; // mesh + r[27] = 2; // triangles + r[36..40].copy_from_slice(&128u32.to_le_bytes()); // numthreads + r[40..44].copy_from_slice(&1u32.to_le_bytes()); + r[44..48].copy_from_slice(&1u32.to_le_bytes()); + let ms = console(13, 7, &code, &signature(&[]), &signature(&[("SV_Position", 0, 1, 3, 0), ("TEXCOORD", 0, 0, 3, 1)]), Some(psv0(&r))); + assert!(crate::gpu::recomp::pso::console_mesh(&ms, None, true).is_ok(), "{:?}", crate::gpu::recomp::pso::console_mesh(&ms, None, true).err()); + let ps = dxc::compile("struct V { float4 pos : SV_Position; float4 p0 : TEXCOORD0; };\nfloat4 main(V v) : SV_Target0 { return v.p0; }\n", "main", "ps_6_6", &[]).unwrap(); + + unsafe { + // the title's mesh pipeline: its root signature, MS (console), PS, state + let game_rs: ID3D12RootSignature = { + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap(); + let ser = ser.unwrap(); + dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap() + }; + #[repr(C, align(8))] + struct Sub { + ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, + v: T, + } + #[repr(C)] + struct Stream { + rs: Sub<*mut c_void>, + ms: Sub, + ps: Sub, + rast: Sub, + depth: Sub, + rt: Sub, + } + let code = |b: &[u8]| D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as _, BytecodeLength: b.len() }; + let mut rt = D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 1, ..Default::default() }; + rt.RTFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + let st = Stream { + rs: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, v: game_rs.as_raw() }, + ms: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, v: code(&ms) }, + ps: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, v: code(&ps) }, + rast: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, v: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() } }, + depth: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, v: D3D12_DEPTH_STENCIL_DESC::default() }, + rt: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, v: rt }, + }; + let d2: ID3D12Device2 = dev.cast().unwrap(); + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: std::mem::size_of::(), pPipelineStateSubobjectStream: &st as *const _ as *mut _ }; + let pso: ID3D12PipelineState = d2.CreatePipelineState(&desc).unwrap_or_else(|e| panic!("{e}: {:?}", real::stats().translation_errors)); + let real_pso = super::pso_async::resolve_wait(pso.as_raw() as usize); + let tp = real::two_pass_of(real_pso).unwrap_or_else(|| panic!("no two-pass parts: {:?}", real::stats().translation_errors)); + assert_eq!(tp.kind, "MS"); + + // the vertex table (3 float4) in title memory, its V# in s[16:19] (root constants 8..11) + let u = crate::gpu::uma::get().unwrap(); + let table = u.alloc(1 << 16, 1 << 16).unwrap() as usize; + for (i, (x, y)) in [(-1.0f32, -1.0f32), (-1.0, 1.0), (0.0, -1.0)].iter().enumerate() { + std::ptr::copy_nonoverlapping([f(*x), f(*y), f(0.0), f(1.0)].as_ptr(), (table as *mut u32).add(4 * i), 4); + } + let mut constants = [0u32; 12]; + constants[8..12].copy_from_slice(&[table as u32, ((table >> 32) as u32 & 0xFFFF) | 16 << 16, 3, 0]); + let rs_key = 0x7400_0010usize; + super::console_list::note_root_signature(rs_key, &rts0_constants(12)); + + let t = Target::new(&dev); + let before = bind::counts_snapshot(); + bind::set_pipeline_state(t.backing, pso.as_raw()); + bind::set_graphics_root_signature(t.backing, rs_key as *mut c_void); + bind::set_graphics_root_constants(t.backing, 0, 12, constants.as_ptr(), 0); + bind::dispatch_mesh(t.backing, 2, 1, 1); + let after = bind::counts_snapshot(); + // (other tests count too: the pixels below are what tells) + assert!(after[0] > before[0], "the DispatchMesh ran as a translated draw"); + let px = t.finish(); + u.free(table); + + // group g: (-1 + g, -1), (-1 + g, 1), (g, -1); param0 = (g, vertex, 0, 1) + let (mut hit, mut clear) = ([0usize; 2], 0usize); + for y in 0..SIZE as usize { + for x in 0..SIZE as usize { + let p = px[y * SIZE as usize + x]; + let mut covered = false; + for g in 0..2 { + let gf = g as f32; + if inside([[-1.0 + gf, -1.0], [-1.0 + gf, 1.0], [gf, -1.0]], x, y, 0.02) { + assert_eq!((p[0], p[2], p[3]), (gf, 0.0, 1.0), "pixel ({x},{y}) in group {g}'s triangle: {p:?}"); + hit[g] += 1; + covered = true; + } + } + let near = (0..2).any(|g| inside([[-1.0 + g as f32, -1.0], [-1.0 + g as f32, 1.0], [g as f32, -1.0]], x, y, -0.05)); + if !covered && !near { + assert_eq!(p, CLEAR, "pixel ({x},{y}) outside both triangles"); + clear += 1; + } + } + } + println!("two-pass MS draw: {hit:?} pixels in the two triangles, {clear} clear"); + assert!(hit[0] > 80 && hit[1] > 80 && clear > 300, "{hit:?} / {clear}"); + } +} + +/// A legacy GS pipeline: the ES variant of a console VS (POSITION → LDS, s_setpc into the GS) +/// + a GS (each triangle → a 4-vertex strip, the parallelogram a, b, c, b + c − a; TEXCOORD0 = +/// (primitive, vertex)) + a PC PS, through `CreateGraphicsPipelineState`; drawn by the console +/// list's DrawInstanced from a vertex buffer in title memory (two triangles) and by its +/// DrawIndexedInstanced (the second triangle through 16-bit indices). +#[test] +fn gpu_console_gs_pipeline_draws_through_draw_instanced() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let Some(dev) = ready() else { return }; + let e = |n: &'static str, enc: &'static str, f: Vec<(&'static str, u64)>| (n, enc, f, None::); + // ES: vertex (v9..v12) → LDS at lane·32, then into the GS + let es = prog( + &[ + e("V_MBCNT_LO_U32_B32", "ENC_VOP3", vec![("VDST", 20), ("SRC0", 193), ("SRC1", 128)]), + e("V_MBCNT_HI_U32_B32", "ENC_VOP3", vec![("VDST", 20), ("SRC0", 193), ("SRC1", V + 20)]), + e("V_LSHLREV_B32", "ENC_VOP2", vec![("VDST", 21), ("SRC0", 133), ("VSRC1", 20)]), + e("DS_WRITE2_B32", "ENC_DS", vec![("ADDR", 21), ("DATA0", 9), ("DATA1", 10), ("OFFSET0", 0), ("OFFSET1", 1)]), + e("DS_WRITE2_B32", "ENC_DS", vec![("ADDR", 21), ("DATA0", 11), ("DATA1", 12), ("OFFSET0", 2), ("OFFSET1", 3)]), + e("S_BARRIER", "ENC_SOPP", vec![]), + e("S_SETPC_B64", "ENC_SOP1", vec![("SSRC0", 6)]), + ], + false, + ); + // GS: EXEC = primitives of this wave (s3[15:8]), vertices from LDS, parallelogram strip + let mut gs: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("S_BFE_U32", "ENC_SOP2", vec![("SDST", 0), ("SSRC0", 3), ("SSRC1", 255)], Some(0x80008)), + ("S_BFM_B64", "ENC_SOP2", vec![("SDST", 126), ("SSRC0", 0), ("SSRC1", 128)], None), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", vec![("VDST", 20), ("SRC0", 193), ("SRC1", 128)], None), + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", vec![("VDST", 20), ("SRC0", 193), ("SRC1", V + 20)], None), + ("V_LSHLREV_B32", "ENC_VOP2", vec![("VDST", 30), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_AND_B32", "ENC_VOP2", vec![("VDST", 30), ("SRC0", 255), ("VSRC1", 30)], Some(0x3FFFC)), + ("V_LSHRREV_B32", "ENC_VOP2", vec![("VDST", 31), ("SRC0", 144), ("VSRC1", 0)], None), + ("V_LSHLREV_B32", "ENC_VOP2", vec![("VDST", 31), ("SRC0", 130), ("VSRC1", 31)], None), + ("V_LSHLREV_B32", "ENC_VOP2", vec![("VDST", 32), ("SRC0", 130), ("VSRC1", 1)], None), + ("DS_READ2_B32", "ENC_DS", vec![("VDST", 40), ("ADDR", 30), ("OFFSET0", 0), ("OFFSET1", 1)], None), + ("DS_READ2_B32", "ENC_DS", vec![("VDST", 42), ("ADDR", 31), ("OFFSET0", 0), ("OFFSET1", 1)], None), + ("DS_READ2_B32", "ENC_DS", vec![("VDST", 44), ("ADDR", 32), ("OFFSET0", 0), ("OFFSET1", 1)], None), + ]; + for (d, a, b) in [(46u64, 42u64, 44u64), (47, 43, 45)] { + gs.push(("V_ADD_F32", "ENC_VOP2", vec![("VDST", d), ("SRC0", V + a), ("VSRC1", b)], None)); + gs.push(("V_SUB_F32", "ENC_VOP2", vec![("VDST", d), ("SRC0", V + d), ("VSRC1", d - 6)], None)); // − x0 / − y0 + } + // output base: s2 + lane · (4 vertices · 32 bytes) + gs.push(("V_MAD_U32_U24", "ENC_VOP3", vec![("VDST", 50), ("SRC0", V + 20), ("SRC1", 255), ("SRC2", 2)], Some(128))); + gs.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 51), ("SRC0", 240)], None)); // 0.5 + gs.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 52), ("SRC0", 242)], None)); // 1.0 + for (k, (x, y)) in [(40u64, 41u64), (42, 43), (44, 45), (46, 47)].into_iter().enumerate() { + let o = 8 * k as u64; + gs.push(("DS_WRITE2_B32", "ENC_DS", vec![("ADDR", 50), ("DATA0", x), ("DATA1", y), ("OFFSET0", o), ("OFFSET1", o + 1)], None)); + gs.push(("DS_WRITE2_B32", "ENC_DS", vec![("ADDR", 50), ("DATA0", 51), ("DATA1", 52), ("OFFSET0", o + 2), ("OFFSET1", o + 3)], None)); + gs.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 53), ("SRC0", 128 + k as u64)], None)); + gs.push(("DS_WRITE2_B32", "ENC_DS", vec![("ADDR", 50), ("DATA0", 2), ("DATA1", 53), ("OFFSET0", o + 4), ("OFFSET1", o + 5)], None)); + gs.push(("S_SENDMSG", "ENC_SOPP", vec![("SIMM16", 0x22)], None)); // emit + } + gs.push(("S_SENDMSG", "ENC_SOPP", vec![("SIMM16", 0x12)], None)); // cut + gs.push(("S_SENDMSG", "ENC_SOPP", vec![("SIMM16", 0x3)], None)); // GS done + let gs = prog(&gs, true); + let vs_blob = console(1, 2, &es, &signature(&[("POSITION", 0, 0, 3, 0)]), &signature(&[("SV_Position", 0, 1, 3, 0), ("TEXCOORD", 0, 0, 3, 1)]), None); + let mut r = [0u8; 48]; + r[0..4].copy_from_slice(&3u32.to_le_bytes()); // triangles in + r[4..8].copy_from_slice(&5u32.to_le_bytes()); // triangle strip out + r[24] = 2; // geometry + r[26..28].copy_from_slice(&4u16.to_le_bytes()); // max vertex count + let gs_blob = console(2, 3, &gs, &signature(&[]), &signature(&[("SV_Position", 0, 1, 3, 0), ("TEXCOORD", 0, 0, 1, 1)]), Some(psv0(&r))); + let ps = dxc::compile("struct V { float4 pos : SV_Position; nointerpolation uint4 p0 : TEXCOORD0; };\nfloat4 main(V v) : SV_Target0 { return float4(1.0, (float)v.p0.x, (float)v.p0.y, 1.0); }\n", "main", "ps_6_6", &[]).unwrap(); + + unsafe { + let code = |b: &[u8]| D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as _, BytecodeLength: b.len() }; + let elems = [D3D12_INPUT_ELEMENT_DESC { + SemanticName: windows::core::s!("POSITION"), + Format: DXGI_FORMAT_R32G32B32_FLOAT, + AlignedByteOffset: 0, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + ..Default::default() + }]; + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + VS: code(&vs_blob), + GS: code(&gs_blob), + PS: code(&ps), + SampleMask: u32::MAX, + InputLayout: D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elems.as_ptr(), NumElements: 1 }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + d.RasterizerState.DepthClipEnable = true.into(); + d.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + d.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&d).unwrap_or_else(|e| panic!("{e}: {:?}", real::stats().translation_errors)); + let real_pso = super::pso_async::resolve_wait(pso.as_raw() as usize); + let tp = real::two_pass_of(real_pso).unwrap_or_else(|| panic!("no two-pass parts: {:?}", real::stats().translation_errors)); + assert_eq!(tp.kind, "GS"); + assert!(matches!(&tp.fetch, Some(Ok(f)) if f.registers == 1 && f.slots == [0] && f.missing.is_empty()), "vertex fetch: {:?}", tp.fetch.as_ref().map(|r| r.as_ref().map(|f| (f.registers, f.slots.clone())).map_err(|e| e.clone()))); + + // two triangles (xyz, 12-byte stride) in title memory, then 16-bit indices 3, 4, 5 + let tris: [[[f32; 2]; 3]; 2] = [[[-0.9, -0.9], [-0.5, -0.9], [-0.9, -0.5]], [[0.1, 0.1], [0.5, 0.1], [0.1, 0.5]]]; + let u = crate::gpu::uma::get().unwrap(); + let vb = u.alloc(1 << 16, 1 << 16).unwrap() as usize; + for (k, v) in tris.iter().flatten().enumerate() { + std::ptr::copy_nonoverlapping([v[0], v[1], 0.5f32].as_ptr(), (vb as *mut f32).add(3 * k), 3); + } + let ib = vb + 0x1000; + std::ptr::copy_nonoverlapping([3u16, 4, 5].as_ptr(), (ib + 2) as *mut u16, 3); // at an odd 2-byte offset + + let draw = |indexed: bool| -> Vec<[f32; 4]> { + let t = Target::new(&dev); + bind::set_pipeline_state(t.backing, pso.as_raw()); + list_x::ia_set_topology_x(t.backing, windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + let view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: vb as u64, SizeInBytes: 6 * 12, StrideInBytes: 12 }; + list_x::ia_set_vertex_buffers_x(t.backing, 0, 1, &view); + let before = bind::counts_snapshot(); + if indexed { + let iv = D3D12_INDEX_BUFFER_VIEW { BufferLocation: (ib + 2) as u64, SizeInBytes: 6, Format: DXGI_FORMAT_R16_UINT }; + list_x::ia_set_index_buffer_x(t.backing, &iv); + bind::draw_indexed_instanced(t.backing, 3, 1, 0, 0, 0); + } else { + bind::draw_instanced(t.backing, 6, 1, 0, 0); + } + let after = bind::counts_snapshot(); + assert!(after[0] > before[0], "a translated draw"); + t.finish() + }; + // the parallelogram of triangle (a, b, c): a, b, c, b + c − a + let quad = |t: [[f32; 2]; 3]| -> [[[f32; 2]; 3]; 2] { + let d = [t[1][0] + t[2][0] - t[0][0], t[1][1] + t[2][1] - t[0][1]]; + [[t[0], t[1], t[2]], [t[2], t[1], d]] + }; + let check = |px: &[[f32; 4]], drawn: &[(usize, [[f32; 2]; 3])]| { + let (mut hit, mut clear) = (vec![0usize; drawn.len()], 0usize); + for y in 0..SIZE as usize { + for x in 0..SIZE as usize { + let p = px[y * SIZE as usize + x]; + let mut near = false; + for (k, (prim, t)) in drawn.iter().enumerate() { + let q = quad(*t); + if q.iter().any(|h| inside(*h, x, y, 0.02)) { + assert_eq!((p[0], p[1], p[3]), (1.0, *prim as f32, 1.0), "pixel ({x},{y}) in primitive {prim}'s parallelogram: {p:?}"); + hit[k] += 1; + } + near |= q.iter().any(|h| inside(*h, x, y, -0.05)); + } + if !near { + assert_eq!(p, CLEAR, "pixel ({x},{y}) outside every parallelogram"); + clear += 1; + } + } + } + println!("two-pass GS draw: {hit:?} pixels in the parallelograms, {clear} clear"); + assert!(hit.iter().all(|&h| h > 10) && clear > 400, "{hit:?} / {clear}"); + }; + check(&draw(false), &[(0, tris[0]), (1, tris[1])]); + // indexed: one triangle, primitive 0 of the draw, from vertices 3..5 + check(&draw(true), &[(0, tris[1])]); + u.free(vb); + } +} From e38ca3d3bdae62e5ae511cef9f5f6048a447b49a Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:12:28 -0700 Subject: [PATCH 27/37] DXC memory gate: reserve only the running compiles' growth, no stampede after a minute From ivall/xcl#139 by @hexgeon1, squashed; conflict resolved by hand. --- HANDOFF.md | 9 +- crates/xcl/src/gpu/recomp/dxc.rs | 191 +++++++++++++++++++++++++---- crates/xcl/src/gpu/recomp/tests.rs | 149 ++++++++++++++++++++++ 3 files changed, 325 insertions(+), 24 deletions(-) diff --git a/HANDOFF.md b/HANDOFF.md index 118948d..32e6150 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1415,7 +1415,12 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76 call; it stays 2 s after the last one). XDefiant from an empty cache: ~1750 shaders in ~2 min 15 s. Before, `dxc::wait_for_memory` held each compile up to a minute while less than 6 GB of commit was left, and with XDefiant's own ~10 GB committed only ~4 GB were: its last ~160 shaders came a few a minute (it looked hung at - ~1600). Now a compile goes at once with 6 GB left, else alone (one at a time). After a cold-cache run + ~1600). Now a compile goes at once with 6 GB left, else alone (one at a time). Since 2026-11-23: at once while + commit covers 6 GB + 300 MB per running compile (their current use is already out of the available commit, so only + their growth is reserved; #113 reserved 1 GB each on top: with 8.1 GB free, Minecraft's 716 programs, 15 threads, + 12.7–15.2 s → 6.4–6.7 s, 5.3–5.6 s with no gate); the count only rises from the value a decision saw (no burst on + one reading); after a minute's wait one compile per minute goes in regardless (it was every waiting one); waiters + wake when a compile ends (`may_start`, `gate_tests`). Driver PSO compiles are still not gated. After a cold-cache run XDefiant's logo / UI text was missing at times. Cold-cache runs (empty `XCL_DXIL_CACHE`, 1 756 shaders) show the logo at ~70 s and the text ~15 s later, by themselves; draws wait for pipelines still being built (`resolve_wait` in `bind::graphics_bound`, 0 draws with stand-ins). The text missing for good (also warm) on @@ -1626,7 +1631,7 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76 - **Ending a run without a stuck process**: a host killed from outside with GPU work in flight stayed in the driver holding 12–16 GB. `XCL_RUN_SECONDS=n` ends the title itself: every fence the title created is signalled to the maximum (GPU waits on future values complete), the queues drain, then TerminateProcess (`real::end_title`). Shader - compiles: at most 6 at once and they wait while the system has < 6 GB of commit left (`dxc::wait_for_memory`). + compiles: `dxc::compile_threads` at once, gated by commit left (`dxc::wait_for_memory`). - **Window**: titles create their window with CreateWindowExA / RegisterClassExA but DefWindowProcW (its title showed as CJK characters); `hle::user` makes them Unicode calls. The window stays white (console titles never paint it). - Diagnostics: `XCL_TRACE_FRAME=1` (what console code does with each presented resource; render-target binds, UAV diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index b769d80..1562c9a 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -386,49 +386,114 @@ pub fn compile_threads() -> usize { }) } +/// What `wait_for_memory` lets compiles in through: the compiles running, its lock (holding +/// when a compile last went in by waiting `ESCAPE_AFTER`) and the wake-up when one ends. +struct Gate { + running: std::sync::atomic::AtomicUsize, + last_escape: Mutex>, + freed: std::sync::Condvar, +} + /// GB of commit `wait_for_memory` keeps free besides the compiles: 6 for a running title (its /// own allocations), less without one (`set_memory_reserve`: `xcl shaders --precompile`). -static RESERVE_GB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(6); +static RESERVE_GB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(COMMIT_FLOOR >> 30); /// The commit `wait_for_memory` keeps free besides the compiles (no title running: less). pub fn set_memory_reserve(gb: u64) { RESERVE_GB.store(gb, std::sync::atomic::Ordering::Relaxed); } -/// Compiles running on the DXC workers (`wait_for_memory` lets them in). -static WORKING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +impl Gate { + const fn new() -> Gate { + Gate { running: std::sync::atomic::AtomicUsize::new(0), last_escape: Mutex::new(None), freed: std::sync::Condvar::new() } + } +} + +/// The DXC workers' gate. +static GATE: Gate = Gate::new(); /// A compile let in by `wait_for_memory`, until it is dropped. -pub struct MemorySlot; +pub struct MemorySlot(&'static Gate); impl Drop for MemorySlot { fn drop(&mut self) { - WORKING.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + self.0.running.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + // under the gate's lock: a waiter between its decision and its wait does not miss it + let _lock = self.0.last_escape.lock().unwrap_or_else(|e| e.into_inner()); + self.0.freed.notify_all(); } } -/// Before a compile: with 6 GB of commit left or more, plus 1 GB for every compile already -/// running (each can still grow to ~0.7 GB), at once; with less, one compile at a -/// time – it goes when no other is running (and after a minute in any case). Each compile used -/// to wait the minute while commit was short: with XDefiant's own 10 GB committed, 4 GB were -/// left, and its last cold-cache shaders came a few a minute. +/// The system's available commit (None when Windows does not say). +fn available_commit() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPageFile) +} + +/// Commit left for the rest of the system (the title above all) while compiles run. +/// Default: 6 GB (`set_memory_reserve` lowers it when no title runs). +const COMMIT_FLOOR: u64 = 6 << 30; + +/// The commit floor in effect (`RESERVE_GB`). +fn commit_floor() -> u64 { + RESERVE_GB.load(std::sync::atomic::Ordering::Relaxed) << 30 +} + +/// Commit a running compile may still add: what it already uses is in the system's available +/// commit, so this is only its growth to come – a typical retail compile peaks at 0.1–0.3 GB +/// (#113). It was 1 GB on top of that count: with 8.5 GB of commit free (a desktop with a +/// browser and chat open) about three compiles ran and the other workers polled – Minecraft's +/// 716 programs took 12.5 s on 16 threads instead of 4.9 s. +const COMMIT_PER_COMPILE: u64 = 300 << 20; + +/// A compile that has waited this long goes in even when commit is short – one per interval, +/// so a hung compile cannot stop the others for good but the waiting ones do not all start at +/// once (they did: after a minute every waiting worker went in). +const ESCAPE_AFTER: std::time::Duration = std::time::Duration::from_secs(60); + +/// Whether a compile may start: `avail` the system's available commit (None: unknown), +/// `running` the compiles running now, `waited` how long this one has waited, `escape_free` +/// no other compile went in by waiting `ESCAPE_AFTER` within the last interval. +fn may_start(avail: Option, running: usize, waited: std::time::Duration, escape_free: bool) -> bool { + let Some(avail) = avail else { return true }; + // enough commit for the floor and for what the running ones may still grow; with less, one + // compile at a time (it goes when no other is running) + avail >= commit_floor() + COMMIT_PER_COMPILE * running as u64 || running == 0 || (waited >= ESCAPE_AFTER && escape_free) +} + +/// Before a compile: in at once while commit covers `COMMIT_FLOOR` plus `COMMIT_PER_COMPILE` +/// for each compile running; with less, one compile at a time, and a compile that has waited +/// `ESCAPE_AFTER` goes in regardless, one per interval. Each compile used to wait the minute +/// while commit was short: with XDefiant's own 10 GB committed, 4 GB were left, and its last +/// cold-cache shaders came a few a minute. pub fn wait_for_memory() -> MemorySlot { + admit(&GATE, available_commit) +} + +/// `wait_for_memory` through `gate`, with the available commit from `commit` (read again for +/// every decision; a test gives it a fixed one). +fn admit(gate: &'static Gate, commit: impl Fn() -> Option) -> MemorySlot { use std::sync::atomic::Ordering; - use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let start = std::time::Instant::now(); + let mut last_escape = gate.last_escape.lock().unwrap_or_else(|e| e.into_inner()); loop { - let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; - m.dwLength = std::mem::size_of::() as u32; - let need = (RESERVE_GB.load(Ordering::Relaxed) << 30) + ((WORKING.load(Ordering::Acquire) as u64) << 30); - let plenty = unsafe { GlobalMemoryStatusEx(&mut m) } == 0 || m.ullAvailPageFile >= need; - if plenty || start.elapsed().as_secs() >= 60 { - WORKING.fetch_add(1, Ordering::AcqRel); - return MemorySlot; - } - if WORKING.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire).is_ok() { - return MemorySlot; + let avail = commit(); + let waited = start.elapsed(); + let escape_free = last_escape.is_none_or(|t| t.elapsed() >= ESCAPE_AFTER); + let running = gate.running.load(Ordering::Acquire); + // the count goes up only from the value the decision saw: workers deciding at the same + // moment cannot all go in on one reading of the commit + if may_start(avail, running, waited, escape_free) && gate.running.compare_exchange(running, running + 1, Ordering::AcqRel, Ordering::Acquire).is_ok() { + let plenty = avail.is_none_or(|a| a >= commit_floor() + COMMIT_PER_COMPILE * running as u64); + if !plenty && running != 0 { + *last_escape = Some(std::time::Instant::now()); + } + return MemorySlot(gate); } - std::thread::sleep(std::time::Duration::from_millis(50)); + // woken when a compile ends; the commit can also change without one, so look again soon + last_escape = gate.freed.wait_timeout(last_escape, std::time::Duration::from_millis(50)).unwrap_or_else(|e| e.into_inner()).0; } } @@ -888,6 +953,88 @@ pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec, compile_cached_in(&cache_dir(), src, entry, profile) } +#[cfg(test)] +mod gate_tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; + + const GB: u64 = 1 << 30; + + #[test] + fn compiles_start_while_commit_covers_the_floor_and_the_running_ones_growth() { + let now = Duration::ZERO; + // 8.5 GB free (the desktop that #113's 1 GB per compile held to three): eight running + // still leave room for a ninth + let free = 17 * GB / 2; + assert!(may_start(Some(free), 8, now, true)); + assert!(!may_start(Some(free), 9, now, true)); + assert!(may_start(Some(64 * GB), 63, now, true)); + // no reading: in + assert!(may_start(None, 100, now, false)); + } + + #[test] + fn short_commit_lets_one_compile_at_a_time_and_one_escape_per_interval() { + let short = 4 * GB; + assert!(may_start(Some(short), 0, Duration::ZERO, true), "alone, a compile always goes"); + assert!(!may_start(Some(short), 1, Duration::from_secs(10), true)); + assert!(may_start(Some(short), 1, ESCAPE_AFTER, true), "a minute's wait goes in"); + assert!(!may_start(Some(short), 1, ESCAPE_AFTER * 5, false), "but not while another just escaped"); + } + + /// Workers that decide at the same moment do not all go in: the count only rises from + /// the value each decision saw. A gate of its own (other tests' compiles share the real one) + /// and a fixed commit, read at every decision as the real one is: room for exactly three. + #[test] + fn concurrent_admissions_reach_and_never_exceed_what_the_commit_allows() { + static TEST_GATE: Gate = Gate::new(); + let cap = 3; + let commit = || Some(COMMIT_FLOOR + COMMIT_PER_COMPILE * (cap as u64 - 1)); + let (now, peak, filled) = (AtomicUsize::new(0), AtomicUsize::new(0), std::sync::atomic::AtomicBool::new(false)); + std::thread::scope(|s| { + for _ in 0..32 { + s.spawn(|| { + for _ in 0..10 { + let _slot = admit(&TEST_GATE, commit); + let n = now.fetch_add(1, Ordering::SeqCst) + 1; + peak.fetch_max(n, Ordering::SeqCst); + // the first ones in stay until the cap is full: it is reached for sure + let t0 = std::time::Instant::now(); + while !filled.load(Ordering::SeqCst) && now.load(Ordering::SeqCst) < cap && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(1)); + } + filled.store(true, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(1)); + now.fetch_sub(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!(peak.into_inner(), cap, "running at once with room for {cap}"); + assert_eq!(TEST_GATE.running.load(Ordering::SeqCst), 0, "every slot given back"); + } + + /// The real gate with the machine's commit: 32 workers through it all finish (no lost + /// wake-up, no slot kept), whatever the commit is. + #[test] + fn the_real_gate_lets_every_worker_through() { + let done = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..32 { + s.spawn(|| { + for _ in 0..5 { + let _slot = wait_for_memory(); + std::thread::sleep(Duration::from_millis(1)); + } + done.fetch_add(1, Ordering::SeqCst); + }); + } + }); + assert_eq!(done.into_inner(), 32); + } +} + #[cfg(test)] mod cache_tests { use super::*; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 9fd1765..75f17a5 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -8246,3 +8246,152 @@ fn gpu_padded_compute_groups_look_the_same_to_the_program() { assert!(tg_size[0] == tg_size[1] && tg_size[0] == tg_size[2], "{dims:?}, wave{lanes}: TG_SIZE with and without padding"); } } + +/// DXC cost of a folder of console shader containers (`XCL_BENCH_DIR`): every program +/// translated (`XCL_BENCH_SPLIT=1`: the split wave64 form, `XCL_BENCH_WINDOWS=n`: n memory windows), then +/// compiled on `XCL_BENCH_THREADS` threads (default: the DXC pool's) with `XCL_DXC_ARGS`. +/// Prints translate time, HLSL bytes and digest, DXC wall time, sum of per-shader times and +/// DXIL bytes. `XCL_BENCH_NO_DXC=1`: translation and digest only. +#[test] +#[ignore] +fn dxc_bench_folder() { + let Ok(dir) = std::env::var("XCL_BENCH_DIR") else { return }; + let split = std::env::var("XCL_BENCH_SPLIT").is_ok_and(|v| v == "1"); + // `XCL_BENCH_WINDOWS=4`: the memory windows of a running title (`Uma::for_runtime`) + let windows = std::env::var("XCL_BENCH_WINDOWS").ok().and_then(|v| v.parse().ok()).unwrap_or(1u32); + let args = std::env::var("XCL_DXC_ARGS").unwrap_or_default(); + let extra: Vec<&str> = args.split_whitespace().collect(); + let mut files: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).collect(); + files.sort(); + // `XCL_BENCH_SLICE=k/n`: every n-th file from the k-th (processes side by side) + if let Some((k, n)) = std::env::var("XCL_BENCH_SLICE").ok().and_then(|v| v.split_once('/').and_then(|(k, n)| Some((k.parse::().ok()?, n.parse::().ok()?)))) { + files = files.into_iter().skip(k).step_by(n.max(1)).collect(); + } + if let Ok(out) = std::env::var("XCL_BENCH_HLSL_OUT") { + let _ = std::fs::create_dir_all(&out); + } + let t0 = std::time::Instant::now(); + let mut jobs: Vec<(String, String, &'static str)> = Vec::new(); + // `XCL_BENCH_HLSL=1`: the folder holds saved HLSL (`..hlsl`) instead + let hlsl_dir = std::env::var("XCL_BENCH_HLSL").is_ok_and(|v| v == "1"); + for path in files.iter().filter(|_| hlsl_dir) { + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + let profile = ["vs_6_6", "ps_6_6", "cs_6_6"].into_iter().find(|p| name.contains(p)).unwrap_or("cs_6_6"); + let stem = name.strip_suffix(".hlsl").and_then(|n| n.strip_suffix(profile)).and_then(|n| n.strip_suffix('.')).unwrap_or(&name).to_string(); + jobs.push((stem, std::fs::read_to_string(path).unwrap(), profile)); + } + for path in files.iter().filter(|_| !hlsl_dir) { + let Ok(blob) = std::fs::read(path) else { continue }; + let Some(sh) = crate::gpu::xbox::parse(&blob) else { continue }; + for f in &sh.fssm { + let Some(mode) = super::interface(&blob, &sh, f) else { continue }; + let profile = match &mode { + Mode::Vertex(_) => "vs_6_6", + Mode::Pixel(_) => "ps_6_6", + Mode::Compute(_) => "cs_6_6", + _ => continue, + }; + for p in &f.programs { + let code = &f.data[p.offset..p.offset + p.len]; + let opt = Options { mode: mode.clone(), wave64: super::detect_wave64(code), split_wave64: split, mem_windows: windows, ..Default::default() }; + let Ok(t) = translate(code, &opt) else { continue }; + if t.complete() { + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + if let Ok(out) = std::env::var("XCL_BENCH_HLSL_OUT") { + let _ = std::fs::write(std::path::Path::new(&out).join(format!("{name}.{profile}.hlsl")), &t.hlsl); + } + jobs.push((name, t.hlsl, profile)); + } + } + } + } + let translate_s = t0.elapsed().as_secs_f64(); + let mut digest = 0xcbf2_9ce4_8422_2325u64; + for (_, h, p) in &jobs { + for b in h.bytes().chain(p.bytes()).chain([0]) { + digest ^= b as u64; + digest = digest.wrapping_mul(0x100_0000_01b3); + } + } + let bytes: usize = jobs.iter().map(|j| j.1.len()).sum(); + let distinct: std::collections::HashSet<(&str, &str)> = jobs.iter().map(|j| (j.1.as_str(), j.2)).collect(); + println!( + "programs {}, distinct HLSL {}, HLSL {:.1} MB, digest {digest:016x}, translate {translate_s:.2} s (one thread)", + jobs.len(), + distinct.len(), + bytes as f64 / 1048576.0 + ); + if std::env::var("XCL_BENCH_NO_DXC").is_ok() { + return; + } + let threads = std::env::var("XCL_BENCH_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or_else(super::dxc::compile_threads); + let next = std::sync::atomic::AtomicUsize::new(0); + let results: std::sync::Mutex> = Default::default(); + let dxil_digest = std::sync::atomic::AtomicU64::new(0); + let t1 = std::time::Instant::now(); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| loop { + let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let Some((name, h, p)) = jobs.get(i) else { break }; + let t = std::time::Instant::now(); + let r = super::dxc::compile(h, "main", p, &extra); + let secs = t.elapsed().as_secs_f64(); + let n = r.as_ref().map_or(0, |b| b.len()); + // DXIL digest per program, combined by name below (order-free) + let mut d = 0xcbf2_9ce4_8422_2325u64; + for &b in r.as_deref().unwrap_or(&[]).iter().chain(name.as_bytes()).chain(p.as_bytes()) { + d ^= b as u64; + d = d.wrapping_mul(0x100_0000_01b3); + } + dxil_digest.fetch_xor(d, std::sync::atomic::Ordering::Relaxed); + if let Err(e) = &r { + println!(" {name}: {}", e.lines().find(|l| l.contains("error")).unwrap_or("")); + } + results.lock().unwrap().push((secs, h.len(), n, name.clone())); + }); + } + }); + let wall = t1.elapsed().as_secs_f64(); + if let Ok(out) = std::env::var("XCL_BENCH_TIMES") { + let t: String = results.lock().unwrap().iter().map(|(s, l, _, n)| format!("{n} {s:.4} {l} +")).collect(); + let _ = std::fs::write(out, t); + } + let mut r = results.into_inner().unwrap(); + r.sort_by(|a, b| a.0.total_cmp(&b.0)); + let sum: f64 = r.iter().map(|x| x.0).sum(); + let dxil: usize = r.iter().map(|x| x.2).sum(); + let failed = r.iter().filter(|x| x.2 == 0).count(); + let q = |f: f64| r[((r.len() - 1) as f64 * f) as usize].0; + println!( + "DXC {extra:?} threads {threads}: wall {wall:.2} s, {:.0} programs/s, per-program sum {sum:.1} s (median {:.3}, p90 {:.3}, max {:.2}), DXIL {:.1} MB (digest {:016x}), failed {failed}", + r.len() as f64 / wall, + q(0.5), + q(0.9), + q(1.0), + dxil as f64 / 1048576.0, + dxil_digest.into_inner() + ); + for (secs, len, _, name) in r.iter().rev().take(3) { + println!(" {secs:.2} s, HLSL {} KB: {name}", len / 1024); + } + // cost by size: ms per HLSL KB in size buckets (is DXC linear in the source?) + let mut buckets = std::collections::BTreeMap::::new(); + for (secs, len, _, _) in &r { + let b = buckets.entry((*len / 1024).next_power_of_two()).or_default(); + b.0 += 1; + b.1 += secs; + b.2 += len; + } + for (kb, (n, secs, len)) in buckets { + println!(" size <= {kb} KB: {n} programs, {:.1} ms each, {:.2} ms/KB", secs * 1e3 / n as f64, secs * 1e3 / (len as f64 / 1024.0)); + } + unsafe { + use windows_sys::Win32::System::ProcessStatus::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + let mut c: PROCESS_MEMORY_COUNTERS = std::mem::zeroed(); + c.cb = std::mem::size_of::() as u32; + GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c, c.cb); + println!(" peak commit {} MB", c.PeakPagefileUsage >> 20); + } +} From c1cc1ddc1989aa2a1830e1c380c921553574665e Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:12:01 -0700 Subject: [PATCH 28/37] Memory windows from the descriptor heap (no per-access switch); NVIDIA OOM fallback; physical-page fixes From ivall/xcl#187 by @RemingtonWilcox, squashed; conflict resolved by hand. --- crates/xcl/src/gpu/recomp/aperture_tests.rs | 880 ++++++++++++++++++++ crates/xcl/src/gpu/recomp/emit.rs | 22 +- crates/xcl/src/gpu/recomp/mod.rs | 24 +- crates/xcl/src/gpu/recomp/pso.rs | 38 +- crates/xcl/src/gpu/recomp/runner.rs | 57 +- crates/xcl/src/gpu/recomp/tests.rs | 15 +- crates/xcl/src/hle/d3d12x/bind.rs | 1 + crates/xcl/src/hle/d3d12x/console_heap.rs | 36 +- crates/xcl/src/hle/d3d12x/console_list.rs | 9 + crates/xcl/src/hle/d3d12x/list_x.rs | 77 +- crates/xcl/src/hle/d3d12x/real.rs | 82 +- crates/xcl/src/hle/kernelx.rs | 79 +- crates/xcl/src/shaders.rs | 9 +- crates/xcl/tests/gpu_compute_e2e.rs | 42 + 14 files changed, 1347 insertions(+), 24 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/aperture_tests.rs diff --git a/crates/xcl/src/gpu/recomp/aperture_tests.rs b/crates/xcl/src/gpu/recomp/aperture_tests.rs new file mode 100644 index 0000000..7a433e7 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/aperture_tests.rs @@ -0,0 +1,880 @@ +//! Experiment E1 (memory aperture): can one binding reach a reserved buffer far above 4 GiB? +//! +//! The memory windows are four root UAVs of 4 GiB each, because a `ByteAddressBuffer` offset +//! is a 32-bit `uint`. A *structured* view with a 2048-byte row addresses +//! `row · 2048 + byte`: 2^32 rows reach 8 TiB through one binding, so a shader could reach all +//! of title memory without a per-access `switch` over windows. This test checks that the +//! drivers actually compute that address beyond 4 GiB, through a root UAV and through a +//! descriptor-heap view, on a 16 GiB reserved buffer with tiles mapped at 0, 4 GiB + 64 KiB, +//! 13 GiB and the last 64 KiB. A tile at 64 KiB (where a 32-bit truncation of 4 GiB + 64 KiB +//! would land) must stay untouched. + +use std::mem::{transmute_copy, ManuallyDrop}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D::*; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::Graphics::Dxgi::*; + +const GIB: u64 = 1 << 30; +const TILE: u64 = 0x1_0000; +/// aperture size +const SIZE: u64 = 16 * GIB; +/// tiles written by the shader (byte offsets in the aperture) +const TILES: [u64; 4] = [0, 4 * GIB + TILE, 13 * GIB, SIZE - TILE]; +/// a 32-bit truncation of `TILES[1]` lands here: must stay zero +const ALIAS: u64 = TILE; +/// dwords per lane and tile the shader writes (one every 4 KiB of the tile) +const STEPS: u64 = 16; +const LANES: u64 = 64; + +fn shader(heap: bool) -> String { + let (decl, get) = if heap { + ("", "RWStructuredBuffer ap = ResourceDescriptorHeap[0];") + } else { + ("RWStructuredBuffer ap : register(u0);", "") + }; + format!( + r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), UAV(u0), UAV(u1), RootConstants(num32BitConstants=4, b0)" +struct XclRow {{ uint d[512]; }}; +{decl} +RWByteAddressBuffer outb : register(u1); +cbuffer C : register(b0) {{ uint pass_; uint probe; uint pad0; uint pad1; }}; +// (hi, lo) of a 64-bit aperture offset → row and byte +uint xcl_row(uint hi, uint lo) {{ return (hi << 21) | (lo >> 11); }} +static const uint THI[4] = {{ {h0}u, {h1}u, {h2}u, {h3}u }}; +static const uint TLO[4] = {{ {l0}u, {l1}u, {l2}u, {l3}u }}; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint l : SV_GroupThreadID) {{ + {get} + for (uint t = 0; t < 4; t++) {{ + for (uint j = 0; j < {steps}u; j++) {{ + uint lo = TLO[t] + j * 4096u + l * 4u; + uint row = xcl_row(THI[t], lo); + uint byte = lo & 2047u; + uint v = 0x80000000u | (t << 24) | (j << 16) | l; + if (pass_ == 0u) {{ + ap[row].d[byte >> 2] = v; + }} else {{ + outb.Store(((t * {steps}u + j) * 64u + l) * 4u, ap[row].d[byte >> 2]); + }} + }} + }} + if (pass_ == 1u && l == 0u) {{ + // probe: a dword past the end of row 0 of tile 0 (d[512] = row 1, d[0]?) + outb.Store(4u * 4u * {steps}u * 64u, ap[0].d[511u + probe]); + }} +}} +"#, + h0 = TILES[0] >> 32, + h1 = TILES[1] >> 32, + h2 = TILES[2] >> 32, + h3 = TILES[3] >> 32, + l0 = TILES[0] as u32, + l1 = TILES[1] as u32, + l2 = TILES[2] as u32, + l3 = TILES[3] as u32, + steps = STEPS, + ) +} + +fn expected(t: u64, j: u64, l: u64) -> u32 { + 0x8000_0000 | (t << 24 | j << 16 | l) as u32 +} + +fn buf(dev: &ID3D12Device, size: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES, uav: bool) -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: if uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + }; + let mut r: Option = None; + unsafe { dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap() }; + r.unwrap() +} + +fn barrier_uav(r: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: unsafe { transmute_copy(r) } }) }, + } +} + +fn transition(r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: unsafe { transmute_copy(r) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } +} + +fn device() -> Option<(ID3D12Device, String)> { + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + if sel == crate::gpu::adapter::Selector::Warp { + return None; + } + let (a, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next()?; + let dev = crate::gpu::agility::create_device(&a, D3D_FEATURE_LEVEL_12_0).ok()?; + Some((dev, crate::gpu::adapter::name(&desc))) + } +} + +/// One run (root UAV or heap view): the words read back through the shader and the tiles' +/// contents copied straight out of the aperture. +unsafe fn run(dev: &ID3D12Device, heap_view: bool) -> Result<(Vec, Vec>), String> { + let dxil = super::dxc::compile(&shader(heap_view), "main", "cs_6_6", &[])?; + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("root signature: {e}"))?; + 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(|e| format!("pipeline: {e}"))?; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).map_err(|e| e.to_string())?; + // the aperture: a 16 GiB reserved buffer + let mut ap: Option = None; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: SIZE, + 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, + ..Default::default() + }; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut ap).map_err(|e| format!("16 GiB reserved buffer: {e}"))?; + let ap = ap.unwrap(); + let mapped: Vec = TILES.iter().copied().chain([ALIAS]).collect(); + let mut tiles: Option = None; + dev.CreateHeap( + &D3D12_HEAP_DESC { + SizeInBytes: TILE * mapped.len() as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, + }, + &mut tiles, + ) + .map_err(|e| e.to_string())?; + let tiles = tiles.unwrap(); + let coords: Vec = mapped.iter().map(|&o| D3D12_TILED_RESOURCE_COORDINATE { X: (o / TILE) as u32, ..Default::default() }).collect(); + let regions: Vec = mapped.iter().map(|_| D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }).collect(); + let flags = vec![D3D12_TILE_RANGE_FLAG_NONE; mapped.len()]; + let offsets: Vec = (0..mapped.len() as u32).collect(); + let counts = vec![1u32; mapped.len()]; + queue.UpdateTileMappings(&ap, coords.len() as u32, Some(coords.as_ptr()), Some(regions.as_ptr()), &tiles, flags.len() as u32, Some(flags.as_ptr()), Some(offsets.as_ptr()), Some(counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE); + + let out_words = 4 * STEPS * LANES + 1; + let out = buf(dev, out_words * 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true); + let rb_bytes = out_words * 4 + TILE * mapped.len() as u64; + let rb = buf(dev, rb_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + // shader-visible heap: [0] = the aperture as a structured UAV of 2048-byte rows + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 1, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }) + .map_err(|e| e.to_string())?; + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: (SIZE / 2048) as u32, StructureByteStride: 2048, CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_NONE }, + }, + }; + dev.CreateUnorderedAccessView(&ap, None::<&ID3D12Resource>, Some(&uav), dh.GetCPUDescriptorHandleForHeapStart()); + + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(|e| e.to_string())?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).map_err(|e| e.to_string())?; + // fresh tiles hold whatever the heap had: clear them first (copy from a zeroed buffer) + let zero = buf(dev, TILE, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false); + let mut p = std::ptr::null_mut(); + zero.Map(0, None, Some(&mut p)).map_err(|e| e.to_string())?; + std::ptr::write_bytes(p as *mut u8, 0, TILE as usize); + zero.Unmap(0, None); + for &o in &mapped { + list.CopyBufferRegion(&ap, o, &zero, 0, TILE); + } + list.ResourceBarrier(&[ + transition(&ap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + transition(&out, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]); + list.SetDescriptorHeaps(&[Some(dh.clone())]); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, ap.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, out.GetGPUVirtualAddress()); + for pass in 0..2u32 { + list.SetComputeRoot32BitConstants(2, 2, [pass, 1u32].as_ptr() as _, 0); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[barrier_uav(&ap), barrier_uav(&out)]); + } + list.ResourceBarrier(&[ + transition(&ap, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + ]); + list.CopyBufferRegion(&rb, 0, &out, 0, out_words * 4); + for (i, &o) in mapped.iter().enumerate() { + list.CopyBufferRegion(&rb, out_words * 4 + i as u64 * TILE, &ap, o, TILE); + } + list.Close().map_err(|e| e.to_string())?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(|e| e.to_string())?)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| e.to_string())?; + queue.Signal(&fence, 1).map_err(|e| e.to_string())?; + crate::gpu::fence::wait(&fence, 1, dev, None, 20_000).map_err(|e| format!("{e}"))?; + let mut q = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut q)).map_err(|e| e.to_string())?; + let all = std::slice::from_raw_parts(q as *const u32, (rb_bytes / 4) as usize).to_vec(); + rb.Unmap(0, None); + let read = all[..out_words as usize].to_vec(); + let tiles = (0..mapped.len()).map(|i| all[out_words as usize + i * (TILE as usize / 4)..][..TILE as usize / 4].to_vec()).collect(); + Ok((read, tiles)) +} + +/// Not an assertion: what the GPU does (RTX 3090, driver 616.92: both bindings fail above +/// 4 GiB – the structured row · stride wraps at 2^32 and a heap view's byte size is 32 bits – +/// so a single aperture binding cannot replace the windows; `gpu_raw_window_view_reaches_its_top` +/// is the form XCL uses). +#[test] +fn gpu_aperture_structured_rows_above_4_gib() { + let Some((dev, name)) = device() else { + println!("no GPU – skipping"); + return; + }; + if super::dxc::location().is_err() { + println!("no DXC – skipping"); + return; + } + let mut va = D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT::default(); + unsafe { dev.CheckFeatureSupport(D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT, &mut va as *mut _ as _, std::mem::size_of_val(&va) as u32).unwrap() }; + println!("{name}: GPU VA bits per resource {}, per process {}", va.MaxGPUVirtualAddressBitsPerResource, va.MaxGPUVirtualAddressBitsPerProcess); + let mut fails = Vec::new(); + for heap_view in [false, true] { + let how = if heap_view { "heap view" } else { "root UAV" }; + let (read, tiles) = match unsafe { run(&dev, heap_view) } { + Ok(r) => r, + Err(e) => { + fails.push(format!("{how}: {e}")); + continue; + } + }; + let mut bad = 0; + for t in 0..4u64 { + for j in 0..STEPS { + for l in 0..LANES { + let want = expected(t, j, l); + let got_read = read[((t * STEPS + j) * LANES + l) as usize]; + let got_mem = tiles[t as usize][((j * 4096 + l * 4) / 4) as usize]; + if got_read != want || got_mem != want { + if bad < 5 { + println!("{how}: tile {t} step {j} lane {l}: read {got_read:#x}, memory {got_mem:#x}, want {want:#x}"); + } + bad += 1; + } + } + } + } + let alias_dirty = tiles[4].iter().filter(|&&w| w != 0).count(); + let probe = read[(4 * STEPS * LANES) as usize]; + println!( + "{how}: {bad} wrong words of {}, alias tile dirty words {alias_dirty}; d[512] of row 0 reads {probe:#x} (row 1 d[0] = {:#x})", + 4 * STEPS * LANES, + tiles[0][512] + ); + if bad > 0 || alias_dirty > 0 { + fails.push(format!("{how}: {bad} wrong words, {alias_dirty} words in the alias tile")); + } + } + println!("{name}: structured aperture {}", if fails.is_empty() { "works".to_string() } else { format!("fails: {fails:?}") }); +} + +/// The heap-window form (`Options::heap_windows`) on a real sparse window: a 4 GiB reserved +/// buffer seen through `runner::raw_window_uav` reaches its last tile, which the sparse windows +/// hand out (a reservation across two windows covers it), up to its last dword but one. +#[test] +fn gpu_raw_window_view_reaches_its_top() { + let Some((dev, name)) = device() else { return }; + if super::dxc::location().is_err() { + return; + } + let top = (4 * GIB) - TILE; // the window's last tile + let src = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), UAV(u0)" +RWByteAddressBuffer outb : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint l : SV_GroupThreadID) { + RWByteAddressBuffer w = ResourceDescriptorHeap[NonUniformResourceIndex(0u)]; + w.Store(0xFFFF0000u + 4u * l, 0x5A000000u | l); + w.Store(4u * l, 0xA5000000u | l); + if (l < 63u) w.Store(0xFFFFFF00u + 4u * l, 0x3C000000u | l); + DeviceMemoryBarrier(); + outb.Store(8u * l, w.Load(0xFFFF0000u + 4u * l)); + outb.Store(8u * l + 4u, w.Load(4u * l)); + outb.Store(512u + 4u * l, l < 63u ? w.Load(0xFFFFFF00u + 4u * l) : 0u); +} +"#; + unsafe { + let dxil = super::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + 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() + }) + .unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 4 * GIB, + 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, + ..Default::default() + }; + let mut win: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut win).unwrap(); + let win = win.unwrap(); + let mut heap: Option = None; + dev.CreateHeap(&D3D12_HEAP_DESC { SizeInBytes: 2 * TILE, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }, &mut heap).unwrap(); + let heap = heap.unwrap(); + let coords = [0u64, top].map(|o| D3D12_TILED_RESOURCE_COORDINATE { X: (o / TILE) as u32, ..Default::default() }); + let regions = [D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }; 2]; + let flags = [D3D12_TILE_RANGE_FLAG_NONE; 2]; + queue.UpdateTileMappings(&win, 2, Some(coords.as_ptr()), Some(regions.as_ptr()), &heap, 2, Some(flags.as_ptr()), Some([0u32, 1].as_ptr()), Some([1u32; 2].as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE); + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 1, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }) + .unwrap(); + dev.CreateUnorderedAccessView(&win, None::<&ID3D12Resource>, Some(&super::runner::raw_window_uav(4 * GIB)), dh.GetCPUDescriptorHandleForHeapStart()); + let out = buf(&dev, 768, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb = buf(&dev, 768 + 256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap(); + list.SetDescriptorHeaps(&[Some(dh.clone())]); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, out.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[ + transition(&win, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + ]); + list.CopyBufferRegion(&rb, 0, &out, 0, 768); + list.CopyBufferRegion(&rb, 768, &win, top, 256); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + let mut q = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut q)).unwrap(); + let w = std::slice::from_raw_parts(q as *const u32, 256).to_vec(); + rb.Unmap(0, None); + for l in 0..64usize { + assert_eq!(w[2 * l], 0x5A00_0000 | l as u32, "{name}: lane {l}, the window's top tile through the heap view"); + assert_eq!(w[2 * l + 1], 0xA500_0000 | l as u32, "{name}: lane {l}, the window's first tile"); + assert_eq!(w[192 + l], 0x5A00_0000 | l as u32, "{name}: lane {l}, the top tile in memory"); + if l < 63 { + assert_eq!(w[128 + l], 0x3C00_0000 | l as u32, "{name}: lane {l}, the window's last dwords"); + } + } + } +} + +/// Where does each path wrap? One 16 GiB reserved buffer, tiles at 64 KiB (A) and +/// 4 GiB + 64 KiB (B), each pre-filled by the shader through a root UAV whose *VA* already +/// points past 4 GiB (so no shader offset above 4 GiB): then (1) a raw read through a root UAV +/// at VA + 4 GiB, (2) a structured read of row 0x200020 through a root UAV at VA, (3) the copy +/// engine at offset 4 GiB + 64 KiB. +#[test] +fn gpu_aperture_probe_where_it_wraps() { + let Some((dev, name)) = device() else { return }; + if super::dxc::location().is_err() { + return; + } + let src = r#" +#define RS "UAV(u0), UAV(u1), UAV(u2), UAV(u3)" +struct XclRow { uint d[512]; }; +RWByteAddressBuffer lo4 : register(u0); // VA + 0 +RWByteAddressBuffer hi4 : register(u1); // VA + 4 GiB +RWStructuredBuffer rows : register(u2); // VA + 0, rows of 2 KiB +RWByteAddressBuffer outb : register(u3); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + lo4.Store(0x10000, 0xAAAAu); + hi4.Store(0x10000, 0xBBBBu); + DeviceMemoryBarrier(); + outb.Store(0, lo4.Load(0x10000)); + outb.Store(4, hi4.Load(0x10000)); + outb.Store(8, rows[0x200020u].d[0]); // 4 GiB + 64 KiB as row · 2048 + outb.Store(12, rows[0x20u].d[0]); // 64 KiB as row · 2048 + rows[0x200020u].d[1] = 0xCCCCu; // write through the structured path +} +"#; + unsafe { + let dxil = super::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + 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() + }) + .unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: SIZE, + 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, + ..Default::default() + }; + let mut ap: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut ap).unwrap(); + let ap = ap.unwrap(); + let mut heap: Option = None; + dev.CreateHeap(&D3D12_HEAP_DESC { SizeInBytes: 2 * TILE, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }, &mut heap).unwrap(); + let heap = heap.unwrap(); + let at = [ALIAS, 4 * GIB + TILE]; + let coords: Vec<_> = at.iter().map(|&o| D3D12_TILED_RESOURCE_COORDINATE { X: (o / TILE) as u32, ..Default::default() }).collect(); + let regions = [D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }; 2]; + let flags = [D3D12_TILE_RANGE_FLAG_NONE; 2]; + let offs = [0u32, 1]; + let counts = [1u32; 2]; + queue.UpdateTileMappings(&ap, 2, Some(coords.as_ptr()), Some(regions.as_ptr()), &heap, 2, Some(flags.as_ptr()), Some(offs.as_ptr()), Some(counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE); + let out = buf(&dev, 256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb = buf(&dev, 256 + 2 * 16, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap(); + let va = ap.GetGPUVirtualAddress(); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, va); + list.SetComputeRootUnorderedAccessView(1, va + 4 * GIB); + list.SetComputeRootUnorderedAccessView(2, va); + list.SetComputeRootUnorderedAccessView(3, out.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[ + transition(&ap, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + ]); + list.CopyBufferRegion(&rb, 0, &out, 0, 256); + list.CopyBufferRegion(&rb, 256, &ap, ALIAS, 16); + list.CopyBufferRegion(&rb, 272, &ap, 4 * GIB + TILE, 16); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + let mut q = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut q)).unwrap(); + let w = std::slice::from_raw_parts(q as *const u32, (256 + 32) / 4).to_vec(); + rb.Unmap(0, None); + println!("{name}: raw VA+0 @64K = {:#x} (want AAAA), raw VA+4G @64K = {:#x} (want BBBB)", w[0], w[1]); + println!("structured row 0x200020 = {:#x} (want BBBB), row 0x20 = {:#x} (want AAAA)", w[2], w[3]); + println!("copy @64K = {:x?} (want AAAA, 0..), copy @4G+64K = {:x?} (want BBBB, CCCC..)", &w[64..68], &w[68..72]); + // a second submission (nothing cached from the stores) reads both tiles back through + // the raw root UAVs: tells a wrapped tile mapping from a wrapping copy engine + let src2 = r#" +#define RS "UAV(u0), UAV(u1), UAV(u2), UAV(u3)" +RWByteAddressBuffer lo4 : register(u0); +RWByteAddressBuffer hi4 : register(u1); +RWByteAddressBuffer unused : register(u2); +RWByteAddressBuffer outb : register(u3); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { outb.Store4(0, uint4(lo4.Load2(0x10000), hi4.Load2(0x10000))); } +"#; + let dxil2 = super::dxc::compile(src2, "main", "cs_6_6", &[]).unwrap(); + let rs2: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil2).unwrap(); + let pso2: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs2), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil2.as_ptr() as _, BytecodeLength: dxil2.len() }, + ..Default::default() + }) + .unwrap(); + let out2 = buf(&dev, 256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb2 = buf(&dev, 256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + alloc.Reset().unwrap(); + list.Reset(&alloc, &pso2).unwrap(); + list.ResourceBarrier(&[transition(&ap, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + list.SetComputeRootSignature(&rs2); + list.SetComputeRootUnorderedAccessView(0, va); + list.SetComputeRootUnorderedAccessView(1, va + 4 * GIB); + list.SetComputeRootUnorderedAccessView(2, va); + list.SetComputeRootUnorderedAccessView(3, out2.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[transition(&out2, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&rb2, 0, &out2, 0, 256); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 2).unwrap(); + crate::gpu::fence::wait(&fence, 2, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + let mut q = std::ptr::null_mut(); + rb2.Map(0, None, Some(&mut q)).unwrap(); + let w2 = std::slice::from_raw_parts(q as *const u32, 4).to_vec(); + rb2.Unmap(0, None); + println!("second submission: VA+0 @64K = {:x?}, VA+4G @64K = {:x?}", &w2[0..2], &w2[2..4]); + } +} + +/// Experiment E2: DXC + driver time of one large synthetic compute program (~20 000 +/// instructions, ~2 800 memory accesses: s_load, buffer load / store, global load) with one +/// window, four windows through the root-UAV `switch`, and four windows from the descriptor +/// heap. A random literal per run keeps the driver's pipeline cache out of it. Run alone: +/// `cargo test --release -p xcl --lib e2_window_compile_time -- --ignored --nocapture` +#[test] +#[ignore] +fn e2_window_compile_time() { + use crate::gpu::rdna2::encode; + let Some((dev, name)) = device() else { return }; + if super::dxc::location().is_err() { + return; + } + let blocks: usize = std::env::var("XCL_E2_BLOCKS").ok().and_then(|v| v.parse().ok()).unwrap_or(700); + let reps: usize = std::env::var("XCL_E2_REPS").ok().and_then(|v| v.parse().ok()).unwrap_or(3); + let program = |salt: u32| -> Vec { + let mut v = Vec::new(); + let mut e = |n: &str, enc: &str, f: &[(&str, u64)], l: Option| v.extend(encode(n, enc, f, l).unwrap_or_else(|x| panic!("{n}: {x}"))); + e("S_MOV_B32", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 255)], Some(salt)); + for i in 0..blocks as u64 { + e("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 2), ("OFFSET", (i * 16) & 0xFFFF)], None); + e("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 2), ("SOFFSET", 128), ("IDXEN", 1)], None); + e("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 6), ("ADDR", 4), ("SADDR", 0x7D), ("OFFSET", (i * 4) & 0x7FF)], None); + for k in 0..12u64 { + e("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 256 + 1 + (k & 1) * 5), ("VSRC1", 2)], None); + e("V_MUL_LO_U16", "ENC_VOP3", &[("VDST", 3), ("SRC0", 256 + 2), ("SRC1", 30)], None); + } + e("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 2), ("VADDR", 0), ("SRSRC", 2), ("SOFFSET", 128), ("IDXEN", 1)], None); + } + e("S_ENDPGM", "ENC_SOPP", &[], None); + v + }; + let rs = super::pso::abi_root_signature(&dev, false).unwrap(); + let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 4, ..Default::default() }; + let forms = [("1 window", 1, false), ("4 windows, switch", 4, false), ("4 windows, heap", 4, true)]; + let mut seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u32; + println!("{name}: {blocks} blocks ({} instructions), {reps} runs each", 1 + blocks * 28); + for (label, windows, heap) in forms { + let (mut dxc_t, mut drv_t, mut sizes) = (Vec::new(), Vec::new(), (0, 0)); + for _ in 0..reps { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let t = super::translate(&program(seed), &super::Options { mode: super::Mode::Compute(cs.clone()), mem_windows: windows, heap_windows: heap, split_wave64: super::runner::split_wave64(), ..Default::default() }).unwrap(); + let t0 = std::time::Instant::now(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + dxc_t.push(t0.elapsed().as_secs_f64()); + let t1 = std::time::Instant::now(); + let _pso: ID3D12PipelineState = unsafe { + 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() + }) + } + .unwrap(); + drv_t.push(t1.elapsed().as_secs_f64()); + sizes = (t.hlsl.len(), dxil.len()); + } + let med = |v: &mut Vec| { + v.sort_by(|a, b| a.partial_cmp(b).unwrap()); + v[v.len() / 2] + }; + let (d, r) = (med(&mut dxc_t), med(&mut drv_t)); + println!("{label:>18}: HLSL {:>8} B, DXIL {:>8} B, DXC {d:6.2} s, driver {r:6.2} s, total {:6.2} s (DXC {dxc_t:.2?}, driver {drv_t:.2?})", sizes.0, sizes.1, d + r); + } +} + +/// Experiment E1b, run alone (it turns on the debug layer for the process): +/// `cargo test --release -p xcl --lib e1b_raw_views_under_debug_layer -- --ignored --nocapture`. +/// (1) a raw view of 4 GiB - 64 KiB over a 4 GiB reserved window (the heap-window form; one +/// audit expected the 2^27-element typed-buffer cap to reject it), (2) a raw 1 GiB view whose +/// FirstElement starts past 4 GiB in a 16 GiB reserved buffer (another audit's 1 GiB slices): +/// both written and read through `ResourceDescriptorHeap`, with what the debug layer says. +#[test] +#[ignore] +fn e1b_raw_views_under_debug_layer() { + unsafe { + match crate::gpu::agility::configuration_interface::(&CLSID_D3D12Debug) { + Ok(d) => d.EnableDebugLayer(), + Err(e) => { + println!("no debug layer: {e}"); + return; + } + } + } + let Some((dev, name)) = device() else { return }; + let src = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), UAV(u0), RootConstants(num32BitConstants=4, b0)" +RWByteAddressBuffer outb : register(u0); +cbuffer C : register(b0) { uint slot; uint at; uint tag; uint pad; }; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint l : SV_GroupThreadID) { + RWByteAddressBuffer w = ResourceDescriptorHeap[NonUniformResourceIndex(slot)]; + w.Store(at + 4u * l, tag | l); + DeviceMemoryBarrier(); + outb.Store(4u * l, w.Load(at + 4u * l)); +} +"#; + unsafe { + let dxil = super::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + 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() + }) + .unwrap(); + let q: ID3D12InfoQueue = dev.cast().expect("info queue (debug layer on)"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let reserved = |bytes: u64| { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + 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, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut r).unwrap(); + r.unwrap() + }; + let win = reserved(4 * GIB); + let big = reserved(16 * GIB); + let mut heap: Option = None; + dev.CreateHeap(&D3D12_HEAP_DESC { SizeInBytes: 3 * TILE, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }, &mut heap).unwrap(); + let heap = heap.unwrap(); + // window: its last covered tile; big: 5 GiB + 64 KiB (the slice's offset 64 KiB) and its 32-bit alias + let map = |r: &ID3D12Resource, at: u64, tile: u32| { + let c = D3D12_TILED_RESOURCE_COORDINATE { X: (at / TILE) as u32, ..Default::default() }; + let s = D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }; + queue.UpdateTileMappings(r, 1, Some(&c), Some(&s), &heap, 1, Some(&D3D12_TILE_RANGE_FLAG_NONE), Some(&tile), Some(&1), D3D12_TILE_MAPPING_FLAG_NONE); + }; + map(&win, 4 * GIB - 2 * TILE, 0); + map(&big, 5 * GIB + TILE, 1); + map(&big, GIB + TILE, 2); + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 2, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }) + .unwrap(); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let h0 = dh.GetCPUDescriptorHandleForHeapStart(); + let before = q.GetNumStoredMessages(); + dev.CreateUnorderedAccessView(&win, None::<&ID3D12Resource>, Some(&super::runner::raw_window_uav(4 * GIB)), h0); + let mut slice = super::runner::raw_window_uav(GIB); + slice.Anonymous.Buffer.FirstElement = 5 * GIB / 4; + dev.CreateUnorderedAccessView(&big, None::<&ID3D12Resource>, Some(&slice), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h0.ptr + inc }); + let after_views = q.GetNumStoredMessages(); + let out = buf(&dev, 512, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb = buf(&dev, 512, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap(); + list.SetDescriptorHeaps(&[Some(dh.clone())]); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, out.GetGPUVirtualAddress()); + // slot 0: top tile of the window (offset 0xFFFE0000); slot 1: offset 64 KiB of the slice at 5 GiB + list.SetComputeRoot32BitConstants(1, 3, [0u32, 0xFFFE_0000, 0x5A00_0000].as_ptr() as _, 0); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&rb, 0, &out, 0, 256); + list.ResourceBarrier(&[transition(&out, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + list.SetComputeRoot32BitConstants(1, 3, [1u32, 0x1_0000, 0x6B00_0000].as_ptr() as _, 0); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&rb, 256, &out, 0, 256); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + // the 32-bit alias of the slice's tile (1 GiB + 64 KiB) through a copy (offsets below + // 4 GiB copy correctly): untouched, or did the slice wrap? + let rb2 = buf(&dev, 256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + alloc.Reset().unwrap(); + list.Reset(&alloc, None).unwrap(); + list.ResourceBarrier(&[transition(&big, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&rb2, 0, &big, GIB + TILE, 256); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 2).unwrap(); + crate::gpu::fence::wait(&fence, 2, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let w = std::slice::from_raw_parts(p as *const u32, 128).to_vec(); + rb.Unmap(0, None); + rb2.Map(0, None, Some(&mut p)).unwrap(); + let alias = std::slice::from_raw_parts(p as *const u32, 64).to_vec(); + rb2.Unmap(0, None); + let n = q.GetNumStoredMessages(); + println!("{name}: debug layer messages: {} at view creation, {} in all", after_views - before, n); + for i in 0..n { + let mut len = 0usize; + let _ = q.GetMessage(i, None, &mut len); + let mut b = vec![0u8; len]; + let m = b.as_mut_ptr() as *mut D3D12_MESSAGE; + if q.GetMessage(i, Some(m), &mut len).is_ok() { + let m = &*m; + println!(" [{:?}] {}", m.Severity, std::ffi::CStr::from_ptr(m.pDescription as _).to_string_lossy()); + } + } + let win_ok = (0..64).all(|l| w[l] == 0x5A00_0000 | l as u32); + let slice_ok = (0..64).all(|l| w[64 + l] == 0x6B00_0000 | l as u32); + let alias_clean = alias.iter().all(|&x| x == 0); + println!("4 GiB - 64 KiB raw view, top tile: {}", if win_ok { "ok" } else { "WRONG" }); + println!("1 GiB raw slice at FirstElement 5 GiB: read back {}, 32-bit alias tile {}", if slice_ok { "ok" } else { "WRONG" }, if alias_clean { "untouched" } else { "WRITTEN (the slice wrapped at 4 GiB)" }); + println!("first words: window {:#x}, slice {:#x}, alias {:#x}", w[0], w[64], alias[0]); + } +} + +/// Experiment E1c, run alone (debug layer): can a heap view reach a sparse window's last +/// 64 KiB tile, which the windows hand out? Over a 4 GiB reserved window with only its last +/// tile mapped: (0) the 4 GiB - 64 KiB view, (1) 2^30 - 1 elements (4 GiB - 4 bytes, the +/// largest byte size a 32-bit field holds), (2) exactly 2^30 elements, (3) a 64 KiB view of +/// the last tile alone. Each slot is written and read at the start of the tile and at its +/// last dwords. +/// `cargo test --release -p xcl --lib e1c_window_view_last_tile -- --ignored --nocapture`. +#[test] +#[ignore] +fn e1c_window_view_last_tile() { + unsafe { + match crate::gpu::agility::configuration_interface::(&CLSID_D3D12Debug) { + Ok(d) => d.EnableDebugLayer(), + Err(e) => { + println!("no debug layer: {e}"); + return; + } + } + } + let Some((dev, name)) = device() else { return }; + let src = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), UAV(u0), RootConstants(num32BitConstants=4, b0)" +RWByteAddressBuffer outb : register(u0); +cbuffer C : register(b0) { uint slot; uint at; uint tag; uint pad; }; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint l : SV_GroupThreadID) { + RWByteAddressBuffer w = ResourceDescriptorHeap[NonUniformResourceIndex(slot)]; + w.Store(at + 4u * l, tag | l); + DeviceMemoryBarrier(); + outb.Store(4u * l, w.Load(at + 4u * l)); +} +"#; + unsafe { + let dxil = super::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + 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() }) + .unwrap(); + let q: ID3D12InfoQueue = dev.cast().expect("info queue (debug layer on)"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 4 * GIB, + 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, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut r).unwrap(); + let win = r.unwrap(); + let mut heap: Option = None; + dev.CreateHeap(&D3D12_HEAP_DESC { SizeInBytes: TILE, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }, &mut heap).unwrap(); + let heap = heap.unwrap(); + let c = D3D12_TILED_RESOURCE_COORDINATE { X: ((4 * GIB - TILE) / TILE) as u32, ..Default::default() }; + let s = D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }; + queue.UpdateTileMappings(&win, 1, Some(&c), Some(&s), &heap, 1, Some(&D3D12_TILE_RANGE_FLAG_NONE), Some(&0), Some(&1), D3D12_TILE_MAPPING_FLAG_NONE); + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 4, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }) + .unwrap(); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let h0 = dh.GetCPUDescriptorHandleForHeapStart(); + let view = |first: u64, n: u32| D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Buffer: D3D12_BUFFER_UAV { FirstElement: first, NumElements: n, StructureByteStride: 0, CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_RAW } }, + }; + let views = [view(0, ((4 * GIB - TILE) / 4) as u32), view(0, (1u32 << 30) - 1), view(0, 1u32 << 30), view((4 * GIB - TILE) / 4, (TILE / 4) as u32)]; + let mut created = Vec::new(); + for (k, v) in views.iter().enumerate() { + let before = q.GetNumStoredMessages(); + dev.CreateUnorderedAccessView(&win, None::<&ID3D12Resource>, Some(v), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h0.ptr + k * inc }); + created.push(q.GetNumStoredMessages() - before); + } + // (slot, offset in the view): the first dwords of the tile, then its last dwords + let top = 0xFFFF_0000u32; + let runs: Vec<(u32, u32)> = (0..3u32).flat_map(|k| [(k, top), (k, 0xFFFF_FF00)]).chain([(3, 0), (3, 0xFF00)]).collect(); + let out = buf(&dev, 256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb = buf(&dev, 256 * runs.len() as u64, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap(); + list.SetDescriptorHeaps(&[Some(dh.clone())]); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, out.GetGPUVirtualAddress()); + for (i, &(slot, at)) in runs.iter().enumerate() { + list.SetComputeRoot32BitConstants(1, 3, [slot, at, (0x10 + i as u32) << 24].as_ptr() as _, 0); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&rb, 256 * i as u64, &out, 0, 256); + list.ResourceBarrier(&[transition(&out, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + } + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let w = std::slice::from_raw_parts(p as *const u32, 64 * runs.len()).to_vec(); + rb.Unmap(0, None); + let names = ["4 GiB - 64 KiB", "2^30 - 1 elements", "2^30 elements", "last tile alone"]; + println!("{name}: debug-layer messages at creation per view: {created:?}"); + for (i, &(slot, at)) in runs.iter().enumerate() { + let good = (0..64).filter(|&l| w[64 * i + l] == ((0x10 + i as u32) << 24) | l as u32).count(); + println!(" {:<18} at {at:#010x}: {good}/64 lanes read back", names[slot as usize]); + } + let n = q.GetNumStoredMessages(); + for i in 0..n.min(10) { + let mut len = 0usize; + let _ = q.GetMessage(i, None, &mut len); + let mut b = vec![0u8; len]; + let m = b.as_mut_ptr() as *mut D3D12_MESSAGE; + if q.GetMessage(i, Some(m), &mut len).is_ok() { + println!(" [{:?}] {}", (*m).Severity, std::ffi::CStr::from_ptr((*m).pDescription as _).to_string_lossy()); + } + } + } +} diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 0d6baa0..b9fbc24 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4642,7 +4642,8 @@ impl Em { } } if windows > 1 { - h = windowed(&h, windows); + let coherent = if matches!(self.opt.mode, Mode::Compute(_)) { "globallycoherent " } else { "" }; + h = windowed(&h, windows, self.opt.heap_windows.then_some(coherent)); } h } @@ -5018,7 +5019,9 @@ const LOADX4_ONE_WINDOW: &str = "uint4 xcl_loadx4(uint4 a) { return uint4(mem.Lo /// Several memory windows: every `mem.Method(` of the program (and of the preludes) becomes /// an accessor `xcl_mMethod(` that switches on `xcl_w` between `mem` and `mem1`.., whose /// definitions replace the placeholder. -fn windowed(h: &str, windows: u32) -> String { +/// `heap`: Some(storage class) – the accessors take window k from the descriptor heap +/// (`Options::heap_windows`) instead of switching over the root UAVs. +fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String { let mut out = String::with_capacity(h.len() + 8192); let mut rest = h; while let Some(i) = rest.find("mem.") { @@ -5036,11 +5039,11 @@ fn windowed(h: &str, windows: u32) -> String { } } out.push_str(rest); - out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows), 1) + out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows, heap), 1) } /// The accessor functions: one per `mem` method (and overload) the translator emits. -fn mem_accessors(windows: u32) -> String { +fn mem_accessors(windows: u32, heap: Option<&str>) -> String { let mut sigs: Vec<(&str, String, &str, &str)> = vec![ ("uint", "Load".into(), "uint a", "a"), ("uint2", "Load2".into(), "uint a", "a"), @@ -5065,6 +5068,17 @@ fn mem_accessors(windows: u32) -> String { } } let mut s = String::new(); + if let Some(coherent) = heap { + // one access: window k is descriptor MEM_HEAP_BASE + k (a window the program does not + // have reads window 0, as the switch's default did) + let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + (xcl_w < {windows}u ? xcl_w : 0u))]", super::MEM_HEAP_BASE); + let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ XCL_MW; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}"); + for (ret, name, params, args) in sigs { + let r = if ret == "void" { "" } else { "return " }; + let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ XCL_MW; {r}m.{name}({args}); }}"); + } + return s; + } let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_w) {{ "); for k in 1..windows { let _ = write!(s, "case {k}u: return uint4(mem{k}.Load(a.x), mem{k}.Load(a.y), mem{k}.Load(a.z), mem{k}.Load(a.w)); "); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 75c9595..5c348c9 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -62,6 +62,16 @@ pub use emit::mesh_passthrough; pub mod runner; #[cfg(test)] mod tests; +#[cfg(test)] +mod aperture_tests; + +/// First descriptor of the memory windows in the shader-visible heap (`Options::heap_windows`): +/// window k is raw UAV `MEM_HEAP_BASE + k`. +pub const MEM_HEAP_BASE: u32 = 0; + +/// Flag in a memory-windows count (`pso::mem_windows`, the translation caches' keys): +/// `Options::heap_windows`. `translate` takes it out of `mem_windows`. +pub const HEAP_WINDOWS: u32 = 0x100; pub mod upper_lanes; use std::collections::{BTreeMap, BTreeSet}; @@ -491,6 +501,11 @@ pub struct Options { /// then exactly the single-window form); 2..4 add `mem1`.. (u3..) and pick the window of /// every access from the high address bits pub mem_windows: u32, + /// with `mem_windows` > 1: reach window k through descriptor `MEM_HEAP_BASE + k` of the + /// shader-visible heap (a raw UAV of the window, `ResourceDescriptorHeap`) – one access per + /// site instead of a `switch` over the root UAVs `mem`, `mem1`.., which inlines every + /// access once per window (HANDOFF: twice the DXC + driver time with 4 windows) + pub heap_windows: bool, /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) pub structured: bool, @@ -516,7 +531,7 @@ pub enum PadWaves { 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, pad_waves: PadWaves::WhereSeen } + Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true, pad_waves: PadWaves::WhereSeen } } } @@ -1313,6 +1328,13 @@ fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> BTreeMap Result { + let normalized; + let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { + normalized = Options { mem_windows: opt.mem_windows & !HEAP_WINDOWS, heap_windows: true, ..opt.clone() }; + &normalized + } else { + opt + }; let mut insts: Vec = Vec::new(); let mut off = 0usize; while off + 4 <= code.len() { diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 9d02109..ca0d463 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -91,9 +91,43 @@ pub fn fspx(blob: &[u8]) -> Option> { Some(Fspx { threads, rsrc1: u32_at(head, 0x14)?, rsrc2: u32_at(head, 0x18)?, code: &code[..4 * (end + 1)] }) } -/// Memory windows of the title's unified memory (1 without it). +/// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when +/// shaders take them from the descriptor heap (`heap_windows`). pub fn mem_windows() -> u32 { - crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32) + let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); + if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) { + n | super::HEAP_WINDOWS + } else { + n + } +} + +thread_local! { + /// this thread translates in the switch form (`in_switch_form`) + static SWITCH_FORM: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Run `f` with this thread's translations in the switch form over root UAVs (`mem_windows` +/// without `HEAP_WINDOWS`, so other cache keys): for a pipeline the driver would not build with +/// heap windows. The root signature and the binds are the same for both forms. +pub fn in_switch_form(f: impl FnOnce() -> R) -> R { + struct Restore(bool); + impl Drop for Restore { + fn drop(&mut self) { + SWITCH_FORM.with(|s| s.set(self.0)); + } + } + let _restore = Restore(SWITCH_FORM.with(|s| s.replace(true))); + f() +} + +/// Whether translated shaders reach the memory windows through the shared descriptor heap +/// (`Options::heap_windows`; descriptors `MEM_HEAP_BASE`.. made by `console_heap::set_window_views`) +/// instead of a `switch` over root UAVs. On unless `XCL_HEAP_WINDOWS=0` or the views could not +/// be made (no shared heap: then the switch, as before). +pub fn heap_windows() -> bool { + static ENV: OnceLock = OnceLock::new(); + *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").map_or(true, |v| v != "0")) && !crate::hle::d3d12x::console_heap::window_views_failed() } /// A static sampler of a translated program: (S#, comparison) – see `Translation`. diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 81128e4..7ebe475 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1248,6 +1248,7 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result Result, Some(&raw_window_uav(size as u64)), h); + } + list.SetDescriptorHeaps(&[Some(dh.clone())]); 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.SetComputeRootUnorderedAccessView(2 + k as u32, bufs.get(k).unwrap_or(&mem_buf).GetGPUVirtualAddress()); } list.Dispatch(1, 1, 1); let mut after = vec![transition(&res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]; @@ -1303,6 +1322,22 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result D3D12_UNORDERED_ACCESS_VIEW_DESC { + let bytes = bytes.min((1u64 << 32) - 4); + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: (bytes / 4) as u32, StructureByteStride: 0, CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_RAW }, + }, + } +} + /// Create a committed resource from a description (validation of decoded descriptors). pub fn try_create_texture(desc: &D3D12_RESOURCE_DESC) -> Result<(), String> { with_gpu(|gpu| { @@ -1399,7 +1434,25 @@ fn dispatch_with( 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, &[], &[])?; + let bound = bind_resources(dev, &list, &[], &[])?; + // A PSO built by the backend's hook uses the runtime's window count: with heap windows + // (`Options::heap_windows`) its accesses go to ResourceDescriptorHeap[MEM_HEAP_BASE + w], + // so every window slot is a raw view of `mem` (no textures here to share the heap with). + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: super::MEM_HEAP_BASE + 4, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .map_err(werr)?; + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + for k in 0..4usize { + let mut h = dh.GetCPUDescriptorHandleForHeapStart(); + h.ptr += (super::MEM_HEAP_BASE as usize + k) * inc; + dev.CreateUnorderedAccessView(&mem_buf, None::<&ID3D12Resource>, Some(&raw_window_uav(mem_bytes)), h); + } + list.SetDescriptorHeaps(&[Some(dh.clone()), Some(bound._heaps[1].clone())]); list.SetComputeRootSignature(rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 4d77c06..fc379af 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3747,6 +3747,17 @@ fn gpu_mesh_mode_reads_memory_windows() { /// accesses in window 0. #[test] fn gpu_memory_windows_above_4_gib() { + memory_windows_above_4_gib(false); +} + +/// The same program with the windows taken from the descriptor heap (`Options::heap_windows`): +/// same results, and no `switch` over windows in the HLSL. +#[test] +fn gpu_memory_windows_from_the_heap() { + memory_windows_above_4_gib(true); +} + +fn memory_windows_above_4_gib(heap: bool) { if !gpu_ready() { return; } @@ -3777,8 +3788,10 @@ fn gpu_memory_windows_above_4_gib() { let p = prog(&refs); let one = translate(&p, &Options::default()).unwrap(); assert!(!one.hlsl.contains("mem1") && !one.hlsl.contains("xcl_w =") && !one.hlsl.contains("xcl_m"), "one window: the single-window HLSL"); - let t = translate(&p, &on_gpu(Options { mem_windows: 2, ..Default::default() })).unwrap(); + let t = translate(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() })).unwrap(); assert!(t.hlsl.contains("RWByteAddressBuffer mem1 : register(u3)")); + assert_eq!(t.hlsl.contains("switch (xcl_w)"), !heap, "heap windows: no switch over windows"); + assert_eq!(t.hlsl.contains("ResourceDescriptorHeap[NonUniformResourceIndex(0u + (xcl_w"), heap); let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); let hi = |a: u64| (a >> 32) as u32; let mut st = KernelState::default(); diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index d8df8e3..4fad713 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -815,6 +815,7 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis /// arguments the console's way – compute or graphics) and the argument table in unified /// memory, u1 res, u2… the memory windows; then the pipeline. unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { + super::list_x::ensure_view_heap(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); let first = *windows.first().ok_or("unified memory is not open on the GPU")?; diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 176973e..e2599fc 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -27,6 +27,7 @@ use std::sync::Mutex; +use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; /// bytes of a CBV/SRV/UAV slot (T# / V#) and of a sampler slot (S#) @@ -157,13 +158,46 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { inc: dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), heap, cap, - next: 0, + // the memory windows' raw UAVs (`set_window_views`) come first + next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_WINDOWS as u32, free: Vec::new(), }); } true } +static WINDOW_VIEWS_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Whether the memory windows could not be put in the shared heap (`set_window_views`): +/// translated shaders then switch over root UAVs (`pso::heap_windows`). +pub fn window_views_failed() -> bool { + WINDOW_VIEWS_FAILED.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The memory windows' buffers `(resource, bytes)` as raw UAVs at `MEM_HEAP_BASE + k` of the +/// shared heap, made now if need be (`Options::heap_windows`: shaders take window k from there). +/// A window without a buffer gets window 0's. False (and the shaders keep the switch): no +/// shared heap. +pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) -> bool { + let ok = !windows.is_empty() && windows[0].0 != 0 && shared_heap(dev) && { + let g = GLOBAL.lock().unwrap(); + let s = g.as_ref().unwrap(); + for k in 0..crate::gpu::uma::MAX_WINDOWS { + let (raw, bytes) = windows.get(k).copied().filter(|w| w.0 != 0).unwrap_or(windows[0]); + let raw = raw as *mut std::ffi::c_void; + let Some(r) = ID3D12Resource::from_raw_borrowed(&raw) else { continue }; + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (s.cpu + (crate::gpu::recomp::MEM_HEAP_BASE as u64 + k as u64) * s.inc as u64) as usize }; + s.dev.CreateUnorderedAccessView(r, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(bytes as u64)), at); + } + true + }; + if !ok { + WINDOW_VIEWS_FAILED.store(true, std::sync::atomic::Ordering::Relaxed); + crate::xlog_warn!("memory windows: not in the shared descriptor heap – translated shaders switch over the windows' root UAVs"); + } + ok +} + /// `count` descriptors of the shared heap: the index of the first. None: no shared heap, or /// no room left in it. fn reserve_global(count: u32) -> Option { diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 9556874..3c7f1fe 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -695,6 +695,8 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let mut layout: Option> = None; let mut table: Vec = Vec::new(); let mut pso: Option<*const ConsolePso> = None; + // heap windows (`pso::heap_windows`): a dispatch needs the shared heap even when the list set none + let mut heaps_set = false; let chunks: Vec> = st.chunks.iter().map(|(c, used)| c[..*used].chunks(4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).collect()).collect(); 'chunks: for words in &chunks { let mut at = 0usize; @@ -720,6 +722,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { } } list.SetDescriptorHeaps(&heaps); + heaps_set = true; at += 2 + 2 * n; } else if w0 == TRANSITIONS_MARKER { let n = get(1) as usize; @@ -830,6 +833,12 @@ pub unsafe fn close(obj: *mut c_void) -> Result { Some(r) => list.SetComputeRootSignature(r), None => list.SetComputeRootSignature(rs.as_ref().ok_or("no XCL ABI root signature")?), } + if !heaps_set && crate::gpu::recomp::pso::heap_windows() { + if let Some(g) = super::console_heap::global_heap() { + list.SetDescriptorHeaps(&[Some(g)]); + heaps_set = true; + } + } list.SetComputeRootUnorderedAccessView(0, va(io_at)); list.SetComputeRootUnorderedAccessView(1, va(res_at)); for k in 0..4 { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 80f0ce3..c211b99 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1914,15 +1914,39 @@ pub(super) unsafe fn pc_heaps(n: u32, heaps: *const usize) -> Vec(this, 28)(this, 1, raw.as_ptr()); + } +} + /// console #32 SetDescriptorHeaps (PC #28) pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n: u32, heaps: *const usize) { const PC_SET_DESCRIPTOR_HEAPS: usize = 28; let f = pc::(this, PC_SET_DESCRIPTOR_HEAPS); - if heaps.is_null() || super::console_heap::global_heap().is_none() { - if !heaps.is_null() { - let given = std::slice::from_raw_parts(heaps, n as usize).to_vec(); - with_bindings(this, |b| b.heaps = given); - } + if heaps.is_null() || n == 0 { + // no heaps: nothing bound any more (`ensure_view_heap` binds the shared heap again + // before a translated draw or dispatch reads the memory windows from it) + with_bindings(this, |b| b.heaps.clear()); + return f(this, n, heaps); + } + if super::console_heap::global_heap().is_none() { + let given = std::slice::from_raw_parts(heaps, n as usize).to_vec(); + with_bindings(this, |b| b.heaps = given); return f(this, n, heaps); } let h = pc_heaps(n, heaps); @@ -3097,6 +3121,47 @@ mod tests { }); } + /// SetDescriptorHeaps(0, NULL) unbinds every heap: the list must not still count the + /// shared heap as bound, or a translated draw after it reads the memory windows + /// (`ResourceDescriptorHeap[0..3]`) from no heap at all. + #[test] + fn unbinding_all_heaps_lets_the_shared_heap_be_bound_again() { + #[repr(C)] + struct FakeList { + vt: *const usize, + calls: Mutex>>, + } + unsafe extern "system" fn fake_set_heaps(this: *mut c_void, n: u32, heaps: *const usize) { + let v = if heaps.is_null() { Vec::new() } else { std::slice::from_raw_parts(heaps, n as usize).to_vec() }; + (*(this as *const FakeList)).calls.lock().unwrap().push(v); + } + let mut orig_vt = [0usize; 64]; + orig_vt[28] = fake_set_heaps as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeList { vt: unsafe { ext_vt.as_ptr().add(1) }, calls: Mutex::new(Vec::new()) }); + let list = &*fake as *const FakeList as *mut c_void; + with_bindings(list, |b| b.heaps = vec![0x1234_0000]); + unsafe { + set_descriptor_heaps_x(list, 0, std::ptr::null()); + let mut bound = Vec::new(); + with_bindings(list, |b| bound = b.heaps.clone()); + assert!(bound.is_empty(), "no heap is bound after SetDescriptorHeaps(0, NULL)"); + assert_eq!(fake.calls.lock().unwrap().last(), Some(&Vec::new())); + ensure_view_heap(list); + with_bindings(list, |b| bound = b.heaps.clone()); + match super::super::console_heap::global_heap() { + Some(g) if crate::gpu::recomp::pso::heap_windows() => { + assert_eq!(bound, vec![g.as_raw() as usize], "the shared heap is bound again"); + assert_eq!(fake.calls.lock().unwrap().last(), Some(&vec![g.as_raw() as usize])); + } + _ => assert!(bound.is_empty()), + } + } + LISTS.lock().unwrap().as_mut().map(|m| m.remove(&(list as usize))); + } + #[test] fn draw_indexed_x_routes_through_bind_and_restores_index_buffer() { #[repr(C)] @@ -3122,12 +3187,14 @@ mod tests { } unsafe extern "system" fn fake_noop_ptr(_this: *mut c_void, _p: *mut c_void) {} unsafe extern "system" fn fake_noop_uav(_this: *mut c_void, _slot: u32, _va: u64) {} + unsafe extern "system" fn fake_set_heaps(_this: *mut c_void, _n: u32, _heaps: *const usize) {} let mut orig_vt = [0usize; 64]; orig_vt[1] = fake_add_ref as usize; orig_vt[2] = fake_release as usize; orig_vt[13] = fake_draw_indexed as usize; orig_vt[25] = fake_noop_ptr as usize; // SetPipelineState + orig_vt[28] = fake_set_heaps as usize; // SetDescriptorHeaps (memory windows from the heap) orig_vt[30] = fake_noop_ptr as usize; // SetGraphicsRootSignature orig_vt[42] = fake_noop_uav as usize; // SetGraphicsRootUnorderedAccessView orig_vt[43] = fake_set_ib as usize; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bb8ae1d..28acc57 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -33,7 +33,7 @@ use windows_sys::core::GUID; use super::layout::{self, Iface}; use crate::stubs; -use crate::util::{HRESULT, E_INVALIDARG, E_NOINTERFACE, S_FALSE, S_OK}; +use crate::util::{HRESULT, E_INVALIDARG, E_NOINTERFACE, E_OUTOFMEMORY, S_FALSE, S_OK}; const DLL: &str = "d3d12_xs.dll"; const EXTRA_SLOTS: usize = 64; @@ -359,6 +359,13 @@ unsafe fn open_uma(device: &ID3D12Device) { w0_va ); *UMA_HEAPS.lock().unwrap() = heaps; + // shaders take the windows from the shared descriptor heap (`pso::heap_windows`) + if n > 1 && crate::gpu::recomp::pso::heap_windows() { + let views: Vec<(usize, usize)> = bufs.iter().enumerate().map(|(k, b)| (b.0, u.window(k).1)).collect(); + if super::console_heap::set_window_views(device, &views) { + crate::xlog_info!("D3D12.X: memory windows from the shared descriptor heap (no per-access switch)"); + } + } *UMA_BUFFER.lock().unwrap() = bufs; } @@ -3154,10 +3161,10 @@ fn note_fallback(what: &str, hr: HRESULT, ok: bool) { type PsoFn = unsafe extern "system" fn(*mut c_void, *const c_void, *const GUID, *mut *mut c_void) -> HRESULT; unsafe fn finish_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let mut hr = f(this, desc, riid, ppv); + let mut hr = driver_pso(f, this, desc, riid, ppv); if hr == E_NOINTERFACE { let iid = pc_iid(Kind::PipelineState); - hr = f(this, desc, &iid, ppv); + hr = driver_pso(f, this, desc, &iid, ppv); } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { adopt(*ppv, Kind::PipelineState); @@ -3165,6 +3172,57 @@ unsafe fn finish_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *co hr } +thread_local! { + /// the driver ran out of memory on a pipeline with heap windows (`with_switch_fallback`) + static HEAP_WINDOW_OOM: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// heap-window driver calls still to fail with E_OUTOFMEMORY (`inject_heap_window_oom`) +static INJECTED_OOM: AtomicU64 = AtomicU64::new(0); +/// pipelines built in the switch form after the driver refused them with heap windows +static SWITCH_FORM_RETRIES: AtomicU64 = AtomicU64::new(0); + +/// Tests: the next `n` driver pipeline calls with heap windows fail with E_OUTOFMEMORY without +/// reaching the driver (0 stops it), as NVIDIA 616.92 refuses some big retail programs (#156). +#[doc(hidden)] +pub fn inject_heap_window_oom(n: u64) { + INJECTED_OOM.store(n, Ordering::SeqCst); +} + +/// Pipelines built in the switch form because the driver refused them with heap windows. +pub fn switch_form_retries() -> u64 { + SWITCH_FORM_RETRIES.load(Ordering::Relaxed) +} + +/// A driver pipeline call; E_OUTOFMEMORY while this thread translates with heap windows is +/// noted for `with_switch_fallback`. +unsafe fn driver_pso(f: PsoFn, this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let heap = crate::gpu::recomp::pso::mem_windows() & crate::gpu::recomp::HEAP_WINDOWS != 0; + let injected = heap && INJECTED_OOM.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)).is_ok(); + let hr = if injected { E_OUTOFMEMORY } else { f(this, desc, riid, ppv) }; + if hr == E_OUTOFMEMORY && heap { + HEAP_WINDOW_OOM.with(|o| o.set(true)); + } + hr +} + +/// Build a translated pipeline (`build`: a `translated_*` path); when the driver ran out of +/// memory on it with heap windows, translate it again in the switch form and build that. +/// NVIDIA 616.92 refuses some big programs whose heap index depends on the window with +/// E_OUTOFMEMORY in under a second, and builds the same programs in the switch form (#156). +fn with_switch_fallback(mut build: impl FnMut() -> R) -> R { + HEAP_WINDOW_OOM.with(|o| o.set(false)); + let r = build(); + if !HEAP_WINDOW_OOM.with(|o| o.replace(false)) { + return r; + } + let n = SWITCH_FORM_RETRIES.fetch_add(1, Ordering::Relaxed); + if n < 5 || n % 100 == 0 { + crate::xlog_warn!("D3D12.X: the driver ran out of memory on a pipeline with heap windows – building it in the switch form ({} so far)", n + 1); + } + crate::gpu::recomp::pso::in_switch_form(build) +} + thread_local! { /// translation errors noted during a cached-only attempt (`attempt`) static ATTEMPT_NOTES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; @@ -3182,6 +3240,10 @@ fn attempt(f: impl FnOnce() -> R) -> (R, bool) { } fn note_translation_error(e: String) { + // a refusal `with_switch_fallback` builds again in the switch form (it says so itself) + if HEAP_WINDOW_OOM.with(|o| o.get()) { + return; + } if crate::gpu::recomp::dxc::in_cached_only() { ATTEMPT_NOTES.with(|n| n.borrow_mut().push(e)); return; @@ -3332,6 +3394,10 @@ fn wait_for_commit() { } unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { + with_switch_fallback(|| translated_compute_pso_once(this, f, desc, riid, ppv)) +} + +unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return None; @@ -3388,6 +3454,10 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi } unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) +} + +unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return None; @@ -3944,7 +4014,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: cdesc.CS = bytecode(&tp.cs); let iid = pc_iid(Kind::PipelineState); let mut compute: *mut c_void = std::ptr::null_mut(); - let hc = fc(this, &cdesc as *const _ as *const c_void, &iid, &mut compute); + let hc = driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute); if hc < 0 || compute.is_null() { note_translation_error(format!("the driver rejected the compute pass of the console {kind} ({hc:#x})")); let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(*ppv as *const *const usize)).add(2)); @@ -3964,6 +4034,10 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: /// CreatePipelineState with a console MS: Some(hr) when it was a console mesh pipeline /// (translated, or E_INVALIDARG – console bytecode must not reach the driver). unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + with_switch_fallback(|| translated_mesh_stream_once(this, desc, riid, ppv)) +} + +unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { use crate::gpu::recomp::pso::{console_mesh, is_console}; if !crate::gpu::shader::readable(desc as usize, 16) { return None; diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 0a84078..a543e0b 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -998,8 +998,12 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } - // freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes - if let Some(away) = AWAY.lock().unwrap().as_mut() { + // freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes. + // `AWAY` stays held while the homes go (the order AWAY → PHYS_BLOCKS, as in the map calls): + // a map, read or write of these pages on another thread must not reach a home released + // under it (a plain home is MEM_RELEASEd). + let mut held = AWAY.lock().unwrap(); + if let Some(away) = held.as_mut() { for i in 0..n { if let Some(at) = away.page.remove(&*arr.add(i)) { away.at.remove(&at); @@ -1025,8 +1029,20 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: } else { mem::VirtualFree(home as *mut c_void, 0, mem::MEM_RELEASE); } + } else { + // the block lives on: the freed page's home gives its memory back now (a lazy home + // is committed again when the page number is used: `home_again`) + let at = home + (page - first) * PHYS_PAGE; + if lazy_home(at) && committed_page(at) { + if u.is_sparse(at) { + crate::hle::d3d12x::sparse::decommitted(at, PHYS_PAGE); + } + mem::VirtualFree(at as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT); + } } } + drop(g); + drop(held); 1 } @@ -1835,6 +1851,65 @@ mod tests { } } + /// Freeing one page of a block that lives on gives that page's home back at once (a lazy + /// home: a sparse window's or plain memory); its sibling keeps its home and contents. + #[test] + fn a_freed_page_gives_its_home_back() { + unsafe { + if crate::gpu::uma::get().is_none() { + 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 homes = [page_home(pages[0]).unwrap(), page_home(pages[1]).unwrap()]; + if !lazy_home(homes[0]) { + return; // a coherent-window home is committed as a whole + } + assert!(write_physical_pages(&pages, 0, &[1u8; 2 * PHYS_PAGE])); + assert!(committed_page(homes[0]) && committed_page(homes[1])); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr()), 1); + assert!(!committed_page(homes[0]), "the freed page's home is decommitted"); + assert!(committed_page(homes[1]) && page_home(pages[1]) == Some(homes[1]), "its sibling stays"); + let mut back = [0u8; 4]; + assert!(read_physical_pages(&pages[1..], 0, &mut back) && back == [1; 4]); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr().add(1)), 1); + assert!(page_home(pages[1]).is_none()); + } + } + + /// Allocating, mapping, reading and freeing from several threads at once: + /// `FreeTitlePhysicalPages` holds `AWAY` while it releases homes, so no thread resolves a + /// page to a home being released. + #[test] + fn physical_pages_from_several_threads() { + if crate::gpu::uma::get().is_none() { + return; + } + let threads: Vec<_> = (0..4) + .map(|t| { + std::thread::spawn(move || unsafe { + for k in 0..64u32 { + 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 tag = (t << 16 | k).to_le_bytes(); + assert!(write_physical_pages(&pages, 8, &tag)); + let r = MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, pages.as_mut_ptr()); + assert!(!r.is_null()); + let mut back = [0u8; 4]; + assert!(read_physical_pages(&pages, 8, &mut back)); + assert_eq!(back, tag); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + } + #[test] fn physical_pages_in_uma() { unsafe { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 9baf1d1..81b221a 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -715,7 +715,10 @@ pub fn run(path: &Path, args: &[String]) -> i32 { if args.iter().any(|a| a == "--precompile") { let only = args.iter().position(|a| a == "--only").and_then(|i| args.get(i + 1)).map(|s| s.to_ascii_lowercase()); let pipelines = args.iter().any(|a| a == "--pipelines"); - return precompile(&input, opt("--limit").unwrap_or(usize::MAX), opt("--windows").unwrap_or(4) as u32, opt("--split").map(|v| v != 0), only.as_deref(), pipelines, t0); + // the runtime's key: heap windows unless `XCL_HEAP_WINDOWS=0` (`pso::mem_windows`) + let windows = opt("--windows").unwrap_or(4) as u32; + let windows = if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows }; + return precompile(&input, opt("--limit").unwrap_or(usize::MAX), windows, opt("--split").map(|v| v != 0), only.as_deref(), pipelines, t0); } let agg = analyze(&input, recomp_on, compile, iface_on); drop(input); @@ -999,9 +1002,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let graphics_split = split.unwrap_or_else(recomp::runner::graphics_wave32); let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w)); println!( - "precompiling {n} shaders into {} ({} compile threads; {windows} memory windows{})", + "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), recomp::dxc::compile_threads(), + windows & !recomp::HEAP_WINDOWS, + if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" }, if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } ); if let Some(p) = pipelines { diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 587c489..7e3f0d0 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -135,7 +135,12 @@ fn console_wave64_compute_through_the_pso_hook_dispatch_and_read_back() { let raw = real::device_raw(); let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }.unwrap().clone(); println!("backend device: {}", real::stats().adapter); + mirror_program_through_the_hook(&dev); +} +/// Hand the wave64 mirror program to the CreateComputePipelineState hook, dispatch the +/// pipeline it built and check every thread's output. +fn mirror_program_through_the_hook(dev: &ID3D12Device) { // user SGPRs 2, TGID_X + TGID_Y, thread ids v0 + v1 let blob = console_cs(&program(), 2 << 1 | 1 << 7 | 1 << 8 | 1 << 11, [16, 8, 1]); assert!(xcl::gpu::xbox::is_xbox(&blob), "expected a console container"); @@ -182,6 +187,43 @@ fn console_wave64_compute_through_the_pso_hook_dispatch_and_read_back() { } } +/// A driver that refuses a pipeline with heap windows (E_OUTOFMEMORY, as NVIDIA 616.92 does +/// with some big retail programs, #156) gets the program again in the switch form, and the +/// pipeline from it runs correctly. The refusals are injected (`real::inject_heap_window_oom`). +#[test] +fn heap_window_out_of_memory_falls_back_to_the_switch_form() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if xcl::gpu::recomp::dxc::location().is_err() { + println!("no DXC – skipping"); + runner::skip_test("no DXC"); + return; + } + if xcl::hle::d3d12x::backend() != xcl::hle::d3d12x::Backend::Real { + println!("no real D3D12 device – skipping"); + runner::skip_test("no GPU"); + return; + } + let raw = real::device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }.unwrap().clone(); + if xcl::gpu::recomp::pso::mem_windows() & xcl::gpu::recomp::HEAP_WINDOWS == 0 { + println!("no heap windows (XCL_HEAP_WINDOWS=0 or no shared heap) – skipping"); + runner::skip_test("no heap windows"); + return; + } + struct StopInjecting; + impl Drop for StopInjecting { + fn drop(&mut self) { + real::inject_heap_window_oom(0); + } + } + let _stop = StopInjecting; + // every heap-window build fails, also the background one behind a stand-in + real::inject_heap_window_oom(u64::MAX); + let before = real::switch_form_retries(); + mirror_program_through_the_hook(&dev); + assert!(real::switch_form_retries() > before, "the pipeline was not rebuilt in the switch form"); +} + /// Cold DXIL cache: `CreateComputePipelineState` returns a stand-in immediately and compiles /// the real compute PSO on the background worker. The real PSO (and NOT the stand-in) must be /// registered in `TRANSLATED_COMPUTE` once the background build completes. From c90ed708454b8d22a4ed214f7b4669956d662a54 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:12:03 -0700 Subject: [PATCH 29/37] A memory line at every crash and while the title runs: process and system commit, video memory, what the title asked for From ivall/xcl#194 by @gbuyssens, squashed; conflict resolved by hand. --- HANDOFF.md | 50 +++++++++++ crates/xcl/src/eh.rs | 8 +- crates/xcl/src/hle/d3d12x/sparse.rs | 8 ++ crates/xcl/src/hle/kernelx.rs | 25 +++++- crates/xcl/src/host.rs | 1 + crates/xcl/src/lib.rs | 1 + crates/xcl/src/memstat.rs | 129 ++++++++++++++++++++++++++++ 7 files changed, 217 insertions(+), 5 deletions(-) create mode 100644 crates/xcl/src/memstat.rs diff --git a/HANDOFF.md b/HANDOFF.md index 118948d..be7e91c 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1838,6 +1838,56 @@ SHA-NI is not emulated (also missing on those CPUs): add it if a title's code by size at every submit; a page guard (read-only until the first CPU write, `kernelx::lazy`) was tried and reverted pending measurement past the menus. +## Console CPU instructions the PC lacks (2026-11-23) +A title on an Intel CPU before Ice Lake / Alder Lake dies with 0xC000001D (illegal instruction) in its own code +right after its first `CreateShaderResourceView` (the first descriptor written into title memory). `insn.rs` decodes +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 +(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`. +- With both emulated a title shows its first frame on an i5/i7 Coffee Lake + RTX 3060 too (`first game frame + shown (3840x2160)`), then dies on an assert right after `chad.dll!XDspConnectWithMaximumStreamLimit` returned the + stub's E_NOTIMPL. `chad.dll` (the console's audio DSP offload, `XDsp*`) is routed to `acphal` now: every XDsp + function is acknowledged (S_OK; Connect writes a fake handle into its last pointer argument – the signatures are not + published, the first call of each is logged with its arguments). `XCL_TRACE_IMPORTS=chad` traces stubs named by + prefix too (arguments and result), for the next unknown DLL. + +## The memory wall, and the texture computer's slot 10 (2026-11-23) +With chad.dll acknowledged the title on the i5/i7 + RTX 3060 (32 GB) runs far past its first frame (local user, +~2000 graphics pipelines, mesh shaders, the video-memory arena), then dies writing to address 0 in its thread start-up +code (`+0x2215c35`, `rbx = rbp = 0`) – a path every other thread took. Its own crash reporter says why: `memory.load_percent +84`, `system.memory.swap.free 801176` of `48801508` KB. The page file (48 GB) is full, the commit charge about 75 GB; the +three `graphics PSO rejected (0x8007000e)` just before are the driver's E_OUTOFMEMORY. An allocation returned NULL. +- `memstat.rs`: one line, `memory: process commit … (working set …); system commit … of …, … of RAM free (… % load); + video … of … local, … of … shared; the title asked for graphics …, Windows …, heaps …, physical pages …; sparse windows + … tiles (…) in … pools`, logged at every crash (`eh::unhandled_filter`), when the process ends with an error, and from + a thread whenever the process's commit grew by a GiB (every 30 s at most). "The title asked for" are gross counters + (`memstat::note` in kernelx's commit paths: sparse / UMA graphics memory, Windows commits, XMemAlloc heaps, the + homes of physical pages); video memory is `IDXGIAdapter3::QueryVideoMemoryInfo` (local, and the non-local segment: + system memory the driver spills into when the pools of title memory outgrow the card – on a 12 GB card every GiB of + title memory beyond it costs a second GiB of commit). The next run says whose memory it is. +- The crash line has the code bytes at RIP for every exception now (`(code bytes: …)`), not only illegal instructions. +- `xg_xs.dll` of a GDK (an older one: no `XGSuggestSwizzleMode`), disassembled: `XGCreateTextureComputer` is + `(desc, out)` → the factory at `+0x5dd0`; the computer's vtable (at `+0x50b68`, referenced from `+0x1852`) has 13 slots. + #10 is **GetResourceTiling** – `ID3D12Device::GetResourceTiling`'s six arguments, for the computer's resource: it reads + `*pNumSubresourceTilings`, writes a `D3D12_PACKED_MIP_INFO` (12 bytes), a `D3D12_TILE_SHAPE` (12), `D3D12_SUBRESOURCE_TILING`s + (12 each, indexed by D3D12 subresource skipping the packed levels). E_FAIL "Resource does not have a 64KB swizzle mode + compatible with tiled resources" unless the mode is 8–11 / 16–19 / 24–27; E_NOTIMPL "Texture1D and Texture3D is not + implemented yet"; the standard tile in elements by their size (256×256 … 64×64 for 1 … 16 bytes, halved per MSAA + doubling), reported in texels; a level's tiling is its padded size over the tile, its start tile the level's offset + in 64 KiB tiles plus the slice's; the packed levels one tile at the first one's offset. `xg::get_resource_tiling` + does this (test `resource_tiling_of_a_64kb_texture`). The guess merged from ivall/xcl#169 (GetSubresourceLayout / + Offset, sniffing which arguments are pointers) is gone: with the real arguments it answered E_INVALIDARG by luck (the + "plane" was the low half of a pointer) and would have written 0x70 bytes over a 12-byte tile shape otherwise. + #11 is `GetDescriptor(UINT plane, void* descriptor)`: "pDescriptor cannot be NULL", "PlaneIndex must be less than 3", + copies the plane's 32-byte hardware texture descriptor (not modelled, still a stub). #12 returns a flag byte of the + resource (bit 27 of a dword at `+0x2818`). A title's texture streaming calls #10 for every texture it places in a + tiled pool (179 calls in one run). +- Scripts for the DLL (in the session's scratch, not the repo): a PE reader (`fo(va)`, `q(va)`), a scan of `.rdata` for + runs of code pointers (vtables), `x86_64-w64-mingw32-objdump -d -M intel --start-address … --stop-address …`. + ## Next steps (priority) Little is left to do without the exe – the rest needs an actual run of the game. 1. Once the user has a legal game exe: `xcl inspect`, `xcl run`, analysis of `report.json` diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 4aa583d..9c2be4d 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -76,9 +76,9 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i }; extra = format!(" ({op} at address {:#x})", rec.ExceptionInformation[1]); } - if rec.ExceptionCode as u32 == ILLEGAL_INSTRUCTION { - extra = format!(" (code bytes: {})", code_at(addr)); - } + // the faulting instruction, for any exception: the registers alone rarely say what was + // dereferenced (an access violation in a title's thread start-up: which field of what) + extra.push_str(&format!(" (code bytes: {})", code_at(addr))); let ctx = (*info).ContextRecord; let regs = if ctx.is_null() { String::new() @@ -109,6 +109,7 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i modules::describe_address(addr) ); crate::xlog_error!("{msg}"); + crate::memstat::log(); crate::report::write_final(Some(msg)); // the other threads now: a title crash handler (Breakpad) can keep the process for // minutes before it ends (the retail title's watchdog: what was its silent thread doing?) @@ -137,6 +138,7 @@ unsafe extern "system" fn hk_nt_terminate_process(h: isize, status: i32) -> i32 let (tid, stack) = (windows_sys::Win32::System::Threading::GetCurrentThreadId(), stack_callers_n(&probe as *const usize as usize, 16)); if status != 0 { crate::xlog_error!("process ends with status {status:#x} (thread {tid}); on the stack: {stack}"); + crate::memstat::log(); dump_threads(); } else { crate::xlog_info!("process ends (thread {tid}); on the stack: {stack}"); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 22683de..8acd3d8 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1317,6 +1317,14 @@ impl State { } } +/// (tiles of title memory with video memory, pool heaps holding them) for the memory line +/// (None: no sparse windows, or the state is busy – a crash report must not wait for it). +pub fn stats() -> Option<(usize, usize)> { + let g = STATE.try_lock().ok()?; + let s = g.as_ref()?; + Some((s.mapped.len(), s.pools.len())) +} + /// The sparse windows' tiles with video memory as sorted (start, end) runs: where a CPU write /// has to reach the GPU. pub fn mapped_ranges() -> Vec<(usize, usize)> { diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 0a84078..fe8cd76 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -173,6 +173,7 @@ const PAGE_GPU_X: u32 = 0x2_0000; unsafe fn commit_sparse(a: usize, n: usize, p: u32) -> *mut c_void { let q = mem::VirtualAlloc(a as *const c_void, n, mem::MEM_COMMIT, sanitize_protect(p)); if !q.is_null() { + crate::memstat::note(crate::memstat::GRAPHICS, n); crate::hle::d3d12x::sparse::committed(q as usize, n); } q @@ -217,10 +218,12 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: }; let rounded = size.max(1).div_ceil(align) * align; if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc(rounded, align) { + crate::memstat::note(crate::memstat::GRAPHICS, rounded); trace_mem("VirtualAlloc (graphics, sparse VRAM)", 0, rounded, t as u64, p, q); return q as *mut c_void; } if let Some(q) = uma.and_then(|u| u.alloc(rounded, align)) { + crate::memstat::note(crate::memstat::GRAPHICS, rounded); trace_mem("VirtualAlloc (graphics, UMA)", 0, rounded, t as u64, p, q as usize); return q as *mut c_void; } @@ -286,7 +289,11 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: return q; } } - let q = mem::VirtualAlloc(addr, size, sanitize_alloc_type(t), sanitize_protect(p)); + let kind = sanitize_alloc_type(t); + let q = mem::VirtualAlloc(addr, size, kind, sanitize_protect(p)); + if !q.is_null() && kind & mem::MEM_COMMIT != 0 { + crate::memstat::note(crate::memstat::WINDOWS, size); + } trace_mem("VirtualAlloc", addr as usize, size, t as u64, p, q as usize); q } @@ -468,6 +475,9 @@ pub unsafe extern "system" fn XMemAllocDefault(size: usize, attrs: u64) -> *mut let a = XAllocAttrs::decode(attrs); if a.memory_type == 0 { let q = aligned_heap_alloc(size, 1usize << a.alignment.clamp(4, usize::BITS - 2)); + if !q.is_null() { + crate::memstat::note(crate::memstat::HEAP, size); + } trace_mem("XMemAlloc", 0, size, attrs, 0, q as usize); return q; } @@ -477,14 +487,20 @@ pub unsafe extern "system" fn XMemAllocDefault(size: usize, attrs: u64) -> *mut }; // Graphics memory types live in the sparse VRAM pool (fallback to coherent UMA, then Windows). if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc(rounded, align) { + crate::memstat::note(crate::memstat::GRAPHICS, rounded); trace_mem("XMemAlloc (graphics, sparse VRAM)", 0, rounded, attrs, 0, q); return q as *mut c_void; } if let Some(q) = crate::gpu::uma::get().and_then(|u| u.alloc(rounded, align)) { + crate::memstat::note(crate::memstat::GRAPHICS, rounded); trace_mem("XMemAlloc (graphics, UMA)", 0, rounded, attrs, 0, q as usize); return q as *mut c_void; } - mem::VirtualAlloc(std::ptr::null(), rounded, mem::MEM_COMMIT | mem::MEM_RESERVE, mem::PAGE_READWRITE) + let q = mem::VirtualAlloc(std::ptr::null(), rounded, mem::MEM_COMMIT | mem::MEM_RESERVE, mem::PAGE_READWRITE); + if !q.is_null() { + crate::memstat::note(crate::memstat::WINDOWS, rounded); + } + q } pub unsafe extern "system" fn XMemFreeDefault(p: *mut c_void, attrs: u64) { @@ -877,6 +893,7 @@ unsafe fn home_again(home: usize) -> Option { if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(home)) { crate::hle::d3d12x::sparse::committed(home, PHYS_PAGE); } + crate::memstat::note(crate::memstat::PHYSICAL, PHYS_PAGE); } Some(home) } @@ -898,6 +915,7 @@ unsafe fn commit_homes(home: usize, n: usize) -> bool { if u.is_sparse(home) { crate::hle::d3d12x::sparse::committed(home, len); } + crate::memstat::note(crate::memstat::PHYSICAL, len); true } @@ -1101,6 +1119,9 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); return std::ptr::null_mut(); } + if fresh { + crate::memstat::note(crate::memstat::PHYSICAL, PHYS_PAGE); + } if committed_page(home) { std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PHYS_PAGE); move_home_away(away, home); diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index d1e48c6..4d4bf80 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -127,6 +127,7 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::eh::install_crash_handler(); crate::alloc_trace::install(); crate::eh::start_probes(); + crate::memstat::start(); HOST_MODE.store(true, Ordering::Release); let main = match crate::loader::load_main(&boot.exe_path) { diff --git a/crates/xcl/src/lib.rs b/crates/xcl/src/lib.rs index ea6b7c4..26d1362 100644 --- a/crates/xcl/src/lib.rs +++ b/crates/xcl/src/lib.rs @@ -9,6 +9,7 @@ pub mod log; pub mod manifest; pub mod alloc_trace; +pub mod memstat; pub mod config; pub mod disasm; pub mod eh; diff --git a/crates/xcl/src/memstat.rs b/crates/xcl/src/memstat.rs new file mode 100644 index 0000000..b085da5 --- /dev/null +++ b/crates/xcl/src/memstat.rs @@ -0,0 +1,129 @@ +//! Where the process's memory goes: one line for the log – at a crash, when the process ends +//! with an error, and while the title runs whenever its commit charge has grown by a GiB +//! (at most every 30 s). A title that runs out of memory dies in an allocation of its own, +//! far from the cause (a write to address 0 in a thread's start-up, a PSO the driver refuses +//! with E_OUTOFMEMORY); the line says whose memory it is: the process's commit against the +//! system's limit, the video memory in use (local, and the system memory the driver spills +//! into), what the title asked kernelx for (graphics memory, Windows allocations, heaps) and +//! the tiles of title memory that have video memory. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::ID3D12Device; +use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter3, IDXGIFactory4, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, DXGI_QUERY_VIDEO_MEMORY_INFO}; +use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; +use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// Kinds of memory the title asks kernelx for (`note`). +pub const GRAPHICS: usize = 0; +pub const WINDOWS: usize = 1; +pub const HEAP: usize = 2; +pub const PHYSICAL: usize = 3; + +/// Bytes the title asked for since the start, by kind (gross: frees are not taken off). +static TITLE: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// The title committed `bytes` of `kind` (`GRAPHICS`: memory that gets video memory – the +/// sparse windows, UMA; `WINDOWS`: an ordinary VirtualAlloc commit; `HEAP`: XMemAlloc; +/// `PHYSICAL`: the homes of its physical pages). +pub fn note(kind: usize, bytes: usize) { + TITLE[kind].fetch_add(bytes as u64, Ordering::Relaxed); +} + +fn gib(b: u64) -> String { + format!("{:.1} GiB", b as f64 / (1u64 << 30) as f64) +} + +/// (commit charge, working set) of the process +fn process() -> Option<(u64, u64)> { + unsafe { + let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); + c.cb = std::mem::size_of::() as u32; + (K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb) != 0).then_some((c.PrivateUsage as u64, c.WorkingSetSize as u64)) + } +} + +/// (commit in use, commit limit, physical memory free, load %) of the system +fn system() -> Option<(u64, u64, u64, u32)> { + unsafe { + let mut m: MEMORYSTATUSEX = std::mem::zeroed(); + m.dwLength = std::mem::size_of::() as u32; + (GlobalMemoryStatusEx(&mut m) != 0).then_some((m.ullTotalPageFile.saturating_sub(m.ullAvailPageFile), m.ullTotalPageFile, m.ullAvailPhys, m.dwMemoryLoad)) + } +} + +static ADAPTER: Mutex> = Mutex::new(None); + +/// The device's adapter, found once (None: no device yet, or the lock is held – a crash in a +/// thread that holds it must not wait on it). +fn adapter() -> Option { + let mut g = ADAPTER.try_lock().ok()?; + if g.is_none() { + let raw = crate::hle::d3d12x::real::device_raw(); + if raw.is_null() { + return None; + } + let dev: &ID3D12Device = unsafe { ID3D12Device::from_raw_borrowed(&raw)? }; + let luid = unsafe { dev.GetAdapterLuid() }; + let factory: IDXGIFactory4 = unsafe { CreateDXGIFactory1() }.ok()?; + *g = unsafe { factory.EnumAdapterByLuid::(luid) }.ok(); + } + g.clone() +} + +/// ((in use, budget) local video memory, (in use, budget) non-local: system memory the driver uses) +fn video() -> Option<((u64, u64), (u64, u64))> { + let a = adapter()?; + let mut local = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + unsafe { a.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut local) }.ok()?; + unsafe { a.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) }.ok()?; + Some(((local.CurrentUsage, local.Budget), (shared.CurrentUsage, shared.Budget))) +} + +/// The line: `memory: process commit 61.2 GiB (working set 24.1 GiB); system commit 74.9 of +/// 79.5 GiB, 5.1 GiB of RAM free (84 % load); video 11.3 of 11.6 GiB local, 18.0 of 15.9 GiB +/// shared; the title asked for graphics 20.1 GiB, Windows 1.2 GiB, heaps 3.4 GiB; sparse +/// windows 180224 tiles (11.0 GiB) in 176 pools`. +pub fn line() -> String { + let mut parts = Vec::new(); + if let Some((commit, ws)) = process() { + parts.push(format!("process commit {} (working set {})", gib(commit), gib(ws))); + } + if let Some((used, limit, free, load)) = system() { + parts.push(format!("system commit {} of {}, {} of RAM free ({load} % load)", gib(used), gib(limit), gib(free))); + } + if let Some(((lu, lb), (su, sb))) = video() { + parts.push(format!("video {} of {} local, {} of {} shared", gib(lu), gib(lb), gib(su), gib(sb))); + } + let t = TITLE.each_ref().map(|a| a.load(Ordering::Relaxed)); + parts.push(format!("the title asked for graphics {}, Windows {}, heaps {}, physical pages {}", gib(t[GRAPHICS]), gib(t[WINDOWS]), gib(t[HEAP]), gib(t[PHYSICAL]))); + if let Some((tiles, pools)) = crate::hle::d3d12x::sparse::stats() { + parts.push(format!("sparse windows {tiles} tiles ({}) in {pools} pools", gib((tiles as u64) << 16))); + } + format!("memory: {}", parts.join("; ")) +} + +/// The log line now (a crash, the process ending with an error). +pub fn log() { + crate::xlog_info!("{}", line()); +} + +/// A thread that logs the line whenever the process's commit charge has grown by a GiB since +/// the last line, looking every 30 s. +pub fn start() { + let _ = std::thread::Builder::new().name("xcl-memstat".into()).spawn(|| { + let mut last = 0u64; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + let Some((commit, _)) = process() else { continue }; + if commit >= last + (1 << 30) { + last = commit; + log(); + } + } + }); +} From 10659e50d94766f25638ea4bd7e5aa9fe1b2fc1a Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:14:33 -0700 Subject: [PATCH 30/37] Rebrand to Bathyal: bathyal.exe, CLI help and version, launcher window and messages, README, issue templates, scripts The crate, module paths, XCL_* settings and the %LOCALAPPDATA%\XCL data folder keep XCL's names, so upstream changes merge cleanly and existing caches stay valid. --- .github/ISSUE_TEMPLATE/config.yml | 4 ++-- .github/ISSUE_TEMPLATE/game.yml | 8 +++---- AGENTS.md | 7 +++--- README.md | 37 ++++++++++++++++--------------- crates/xcl/Cargo.toml | 2 +- crates/xcl/src/launcher.rs | 12 +++++----- crates/xcl/src/main.rs | 26 +++++++++++----------- crates/xcl/tests/disasm_e2e.rs | 2 +- crates/xcl/tests/e2e.rs | 6 ++--- scripts/block-egress.ps1 | 4 ++-- scripts/run-title.ps1 | 8 +++---- 11 files changed, 59 insertions(+), 57 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 27832b5..fd413a2 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,5 @@ blank_issues_enabled: true contact_links: - name: GPU test results - url: https://github.com/ivall/xcl/issues/42 - about: Results of the test suite on your GPU go to issue #42, not a new issue. + url: https://github.com/T-Crypt/bathyal/issues + about: Results of the test suite on your GPU: open an issue titled "GPU results: ". diff --git a/.github/ISSUE_TEMPLATE/game.yml b/.github/ISSUE_TEMPLATE/game.yml index 591a8f7..94e6315 100644 --- a/.github/ISSUE_TEMPLATE/game.yml +++ b/.github/ISSUE_TEMPLATE/game.yml @@ -7,7 +7,7 @@ body: value: | Every run writes a report and a log to `%LOCALAPPDATA%\XCL\\logs\` (`report.json`, `xcl.log`; the previous run's are `report.prev.json`, `xcl.prev.log`). They say most of what is needed – please attach both. - Do not attach or link game files, dumps or anything from a game package. XCL works only on unpacked games you own and does not help with DRM. + Do not attach or link game files, dumps or anything from a game package. Bathyal works only on unpacked games you own and does not help with DRM. - type: input id: game attributes: @@ -26,7 +26,7 @@ body: - type: input id: xcl attributes: - label: XCL version + label: Bathyal version description: The release, or the commit you built (`git rev-parse --short HEAD`). validations: required: true @@ -41,7 +41,7 @@ body: id: windows attributes: label: Windows version - description: "`winver` – and whether the D3D12 Agility SDK is next to xcl.exe (Windows 10)." + description: "`winver` – and whether the D3D12 Agility SDK is next to bathyal.exe (Windows 10)." placeholder: "Windows 11 24H2 (26100.4061)" validations: required: true @@ -56,5 +56,5 @@ body: id: console attributes: label: Console output - description: What `xcl run` printed at the start and after the game exited. + description: What `bathyal run` printed at the start and after the game exited. render: text diff --git a/AGENTS.md b/AGENTS.md index f0b50c8..44e0929 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,13 +24,13 @@ A title's executable is untrusted code until it has proven itself. Before its fi 1. Check its SHA-256 against a source you trust. 2. Keep it out of the read-only package folder; build a game folder with `scripts\setup-game-folder.ps1`. -3. Block its egress: `scripts\block-egress.ps1` (outbound block on `xcl.exe`; the title runs inside it). +3. Block its egress: `scripts\block-egress.ps1` (outbound block on `bathyal.exe`; the title runs inside it). 4. Run on a machine with no personal accounts or sensitive data when you can. ## Build, test, run (Windows) ```powershell -cargo build --release --workspace # target\release\xcl.exe +cargo build --release --workspace # target\release\bathyal.exe .\scripts\test.ps1 # cargo build + cargo test --workspace .\scripts\run-title.ps1 -Game D:\games\title # precompiles caches once, then runs; logs in %LOCALAPPDATA%\bathyal\runs ``` @@ -43,7 +43,8 @@ git fetch xcl git merge xcl/main # on a branch; keep our README header and NOTICE.md ``` -Binary, crate and `XCL_*` names stay XCL's so these merges stay clean. +The program is `bathyal.exe`. The crate, module paths, `XCL_*` settings and the `%LOCALAPPDATA%\XCL` data +folder keep XCL's names so these merges stay clean; rename them only together with upstream. ## Notes carried over from Leonida diff --git a/README.md b/README.md index 47f5698..e45055e 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,16 @@ Bathyal is a fork of [XCL](https://github.com/ivall/xcl) by ivall and its contributors, under the same GPL-2.0 license (see [`NOTICE.md`](NOTICE.md)). It follows XCL's `main` and adds work focused on NVIDIA -GPUs (32-lane waves) and on running newer retail titles further. The binary, crate and `XCL_*` settings -keep XCL's names so upstream changes merge cleanly. +GPUs (32-lane waves) and on running newer retail titles further. The program is `bathyal.exe`; the crate, +the `XCL_*` settings and the `%LOCALAPPDATA%\XCL` data folder keep XCL's names so upstream changes merge +cleanly and existing caches stay valid. This repository holds code only: no game files, shaders, assets, keys or logs from any game, and no decryption or DRM workarounds. Bring your own legally obtained, unpacked game files. -XCL runs Xbox Series X|S (GDK) game files on a Windows PC **without CPU emulation**: the game's -x64 code runs natively and XCL stands in for the console libraries the PC does not have +Bathyal runs Xbox Series X|S (GDK) game files on a Windows PC **without CPU emulation**: the game's +x64 code runs natively and Bathyal stands in for the console libraries the PC does not have (`kernelx.dll`, XGameRuntime, `d3d12_xs.dll`, …) – in the spirit of Wine/Proton. The console's GPU code (RDNA2 machine code) is recompiled into PC shaders (HLSL → DXIL). @@ -70,8 +71,8 @@ next steps: |---|---|---|---| | **Shader recompiler** | ✅ | RDNA2 → HLSL → DXIL: VS, PS, CS, mesh (NGG), GS; atomics, LDS, scratch, images, samplers incl. static ones, wave ops, ray-tracing instructions; structured control flow; parallel DXC, disk cache | 26 698 / 26 698 programs of the retail pack; 0 DXC errors on random samples; per-instruction GPU tests | | **Pipelines** | ✅ | PSOs from console shaders: VS+PS, CS, MS+PS, VS+GS+PS; root signature with the shaders' static samplers; non-blocking creation – a pipeline whose shaders are not compiled yet gets a stand-in at once and is built in the background | GPU tests drawing the game's own VS / PS pairs, also built in the background | -| **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers, clears, copies) | the game's BVH builder and FSR 4 record and run through XCL | -| **D3D12.X graphics** | ✅ | device, resources and heaps (also placed in title memory), pipelines; the title's graphics command lists – draws, indirect draws, graphics root arguments, barriers, copies, clears – and command lists recorded by console code, replayed; `PresentX` and frame pacing into an XCL window | Minecraft Preview plays its worlds (millions of draws, none skipped); Fortnite and XDefiant draw their screens | +| **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers, clears, copies) | the game's BVH builder and FSR 4 record and run through Bathyal | +| **D3D12.X graphics** | ✅ | device, resources and heaps (also placed in title memory), pipelines; the title's graphics command lists – draws, indirect draws, graphics root arguments, barriers, copies, clears – and command lists recorded by console code, replayed; `PresentX` and frame pacing into an Bathyal window | Minecraft Preview plays its worlds (millions of draws, none skipped); Fortnite and XDefiant draw their screens | | **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes, the 6 3D thick modes, linear), mip chains with mip tail, arrays, cubes and 3D textures → PC textures | 909 / 912 retail textures exact (the 3 volume LUTs decode smooth); GPU upload bit exact | | **Ray tracing** | ✅ | BLAS / TLAS built on the GPU by the game's own XboxBvhBuilder; RDNA2 BVH node format; BVH intersection instructions emulated in shaders | GPU traversal = brute force reference; the game's builder output checked on the GPU | | **Upscaling** | ✅ | the game's AMD FSR 4 console DLL (`amd_fidelityfx_upscaler_xbox.dll`): context, the 29 pipelines in the console driver's own container (FSPX) translated, a frame's 20 passes recorded and run on the GPU | end-to-end with the real DLL: a 1280×720 → 1920×1080 frame on an RX 9070, the input's gradient in the output | @@ -81,7 +82,7 @@ next steps: | Feature | State | What it does | Verified by | |---|---|---|---| | **Video** | ✅ | the game's Bink 2 console DLL decodes its movies (720p / 1080p) on the CPU; the game's own YUV → RGB display shaders (`PS_Bink…` in its pack) translate like any other. Bink's GPU-assisted mode needs no Bink-specific support: its compute shaders ship with the game and go through the recompiler too (no game seen using it yet) | a game movie decodes frame by frame, picture checked | -| **Tools** | ✅ | `xcl inspect`, `xcl run`, `xcl disasm` (RDNA2, console shader containers), `xcl shaders` (pack statistics, recompile / compile runs), `xcl rpf` | – | +| **Tools** | ✅ | `bathyal inspect`, `bathyal run`, `bathyal disasm` (RDNA2, console shader containers), `bathyal shaders` (pack statistics, recompile / compile runs), `bathyal rpf` | – | ## Controls @@ -98,12 +99,12 @@ A **gamepad is recommended**: console games are made for one, and their menus an ## Building and usage Windows 10/11 x64, Rust (`stable-x86_64-pc-windows-msvc`), the Windows SDK (DXC: `dxcompiler.dll` -+ `dxil.dll`, looked up in `Windows Kits\10\bin\<version>\x64`, next to `xcl.exe` or in ++ `dxil.dll`, looked up in `Windows Kits\10\bin\<version>\x64`, next to `bathyal.exe` or in `%XCL_DXC_DIR%`), a D3D12 GPU with Shader Model 6.6 and mesh shaders, and the system XGameRuntime (`System32\xgameruntime.dll`, part of Windows / Gaming Services). On **Windows 10** (22H2 KB5029331+), inbox `D3D12Core.dll` stops at SM 6.5; place the Microsoft D3D12 Agility SDK (`D3D12Core.dll`, plus `d3d12SDKLayers.dll` if using `XCL_D3D12_DEBUG=1`) in a `D3D12\` folder -next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, or point `%XCL_D3D12_DIR%` at it +next to `bathyal.exe`, directly next to `bathyal.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, or point `%XCL_D3D12_DIR%` at it (for `cargo test`, use `%LOCALAPPDATA%\XCL\D3D12\` or `%XCL_D3D12_DIR%`). - **DXC:** 1.8 or newer is recommended, from the @@ -111,7 +112,7 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o and point `XCL_DXC_DIR` at its `bin\x64`. A Windows SDK may hold an older one (the same `10.0.26100.0` folder has DXC 1.7.2308 or 1.8.2502, depending on the SDK's revision). DXC 1.7's DXIL was 2–2.7 times the size of 1.9's for translated compute programs and took an NVIDIA driver 1.4–2.2 times as long to build - pipelines from ([#156](https://github.com/ivall/xcl/issues/156)). `xcl run` prints the DXC it loaded, and + pipelines from ([#156](https://github.com/ivall/xcl/issues/156)). `bathyal run` prints the DXC it loaded, and `report.json` has it under `dxc`. - **GPU:** developed on AMD RDNA4. The console's geometry and NGG programs run as a compute pass plus a mesh pass, so a GPU without mesh shaders draws none of them. On GPUs with 32-lane waves only @@ -121,19 +122,19 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o can still differ there. Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42). ```powershell -cargo build --release --workspace # target\release\xcl.exe +cargo build --release --workspace # target\release\bathyal.exe -xcl inspect D:\Game\game.exe # the game's imports and what XCL has for them -xcl run D:\Game [-- game arguments] # run -xcl disasm <shader.bin> [--hex] # RDNA2 disassembler (console containers too) -xcl shaders D:\data\shaders.rpf --top 50 # pack statistics; --recomp / --compile N -xcl rpf D:\data\shaders.rpf --extract NAME --out folder +bathyal inspect D:\Game\game.exe # the game's imports and what Bathyal has for them +bathyal run D:\Game [-- game arguments] # run +bathyal disasm <shader.bin> [--hex] # RDNA2 disassembler (console containers too) +bathyal shaders D:\data\shaders.rpf --top 50 # pack statistics; --recomp / --compile N +bathyal rpf D:\data\shaders.rpf --extract NAME --out folder ``` -- **Without a command line** (xcl.exe opened from Explorer) XCL shows a small menu: *Choose a +- **Without a command line** (bathyal.exe opened from Explorer) Bathyal shows a small menu: *Choose a game…* (pick its exe or `MicrosoftGame.config`) or *Run again* (the last one). On an error the window stays open until Enter. -- XCL works on **unpacked** game files you own; it contains nothing for decrypting or +- Bathyal works on **unpacked** game files you own; it contains nothing for decrypting or circumventing DRM. - **The game folder is never modified** – writes go to the overlay. - Every run writes `report.json` (called stubs, unknown D3D12.X slots and interfaces, XGameRuntime diff --git a/crates/xcl/Cargo.toml b/crates/xcl/Cargo.toml index f3f6d60..0ecf786 100644 --- a/crates/xcl/Cargo.toml +++ b/crates/xcl/Cargo.toml @@ -10,7 +10,7 @@ name = "xcl" path = "src/lib.rs" [[bin]] -name = "xcl" +name = "bathyal" path = "src/main.rs" [dependencies] diff --git a/crates/xcl/src/launcher.rs b/crates/xcl/src/launcher.rs index d88a177..af591db 100644 --- a/crates/xcl/src/launcher.rs +++ b/crates/xcl/src/launcher.rs @@ -140,7 +140,7 @@ pub fn read_game_config(root: &Path) -> (Vec<String>, Option<String>) { /// `xcl.exe` itself (by name, path or identical bytes) must never be picked as the game. fn is_xcl_copy(p: &Path) -> bool { - if p.file_name().map(|n| n.to_string_lossy().eq_ignore_ascii_case("xcl.exe")).unwrap_or(false) { + if p.file_name().map(|n| { let n = n.to_string_lossy(); n.eq_ignore_ascii_case("bathyal.exe") || n.eq_ignore_ascii_case("xcl.exe") }).unwrap_or(false) { return true; } let Ok(me) = std::env::current_exe() else { return false }; @@ -201,7 +201,7 @@ fn pick_exe(root: &Path) -> Result<PathBuf, String> { 0 => Err(format!( "no game .exe file in {}{}", root.display(), - if skipped_self { " (only xcl.exe – that is XCL itself; do not copy it into the game folder)" } else { "" } + if skipped_self { " (only bathyal.exe – that is Bathyal itself; do not copy it into the game folder)" } else { "" } )), _ => Err(format!( "several .exe files ({}) – point to the game exe directly or set 'exe' in xcl.toml", @@ -241,7 +241,7 @@ fn resolve_location(target: &Path) -> Result<(PathBuf, Option<PathBuf>, String), (target, None) } else { if is_xcl_copy(&target) { - return Err(format!("{} is XCL itself, not a game – give the game exe or folder", target.display())); + return Err(format!("{} is Bathyal itself, not a game – give the game exe or folder", target.display())); } (config_root(&target).unwrap_or(target.parent().ok_or("no parent folder")?.to_path_buf()), Some(target)) }; @@ -337,7 +337,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 { let _ = std::fs::rename(boot.report_path(), logs.join("report.prev.json")); let _ = std::fs::remove_file(boot.report_path()); - println!("XCL {} – starting '{title}'", env!("CARGO_PKG_VERSION")); + println!("Bathyal {} – starting '{title}'", env!("CARGO_PKG_VERSION")); println!(" exe: {}", exe.display()); println!(" data: {}", data_dir.display()); if !from_manifest.is_empty() { @@ -606,8 +606,8 @@ mod tests { std::fs::copy(&me, d.0.join("xcl.exe")).unwrap(); std::fs::copy(&me, d.0.join("renamed_copy.exe")).unwrap(); // byte-identical copy of XCL let e = resolve_target(&d.0).unwrap_err(); - assert!(e.contains("xcl.exe") && e.contains("XCL itself"), "{e}"); - assert!(resolve_target(&d.0.join("xcl.exe")).unwrap_err().contains("XCL itself")); + assert!(e.contains("bathyal.exe") && e.contains("Bathyal itself"), "{e}"); + assert!(resolve_target(&d.0.join("xcl.exe")).unwrap_err().contains("Bathyal itself")); // a real game exe next to it wins std::fs::write(d.0.join("game.exe"), b"MZ not really a game").unwrap(); let (_, exe, _) = resolve_target(&d.0).unwrap(); diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 83ed102..d043544 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -18,27 +18,27 @@ unsafe extern "system" fn xcl_tls_callback(_h: *mut c_void, reason: u32, _r: *mu static XCL_TLS_CALLBACK: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = xcl_tls_callback; const HELP: &str = "\ -XCL – Xbox Series X|S → Windows compatibility layer +Bathyal – Xbox Series X|S → Windows compatibility layer (a fork of XCL) Usage: - xcl run <game folder | file.exe> [-- game arguments] + bathyal run <game folder | file.exe> [-- game arguments] Runs the game. The game folder is only read; writes, game saves and logs go to %LOCALAPPDATA%\\XCL\\<title>\\ (or %XCL_DATA_ROOT%\\<title>\\). - xcl inspect <file.exe|file.dll> [--json] - Analysis without running: imports and what XCL has for them (HLE / Windows / stub). - xcl disasm <file> [--offset N] [--length N] [--all] [--hex] [--fssm FILE] + bathyal inspect <file.exe|file.dll> [--json] + Analysis without running: imports and what Bathyal has for them (HLE / Windows / stub). + bathyal disasm <file> [--offset N] [--length N] [--all] [--hex] [--fssm FILE] Disassembler for console GPU code (RDNA2) – e.g. for shaders saved in <data>\\shaders\\. Console containers (XDAT/XBCH/FSSM) are unpacked; --fssm saves the unpacked FSSM. - xcl shaders <file | folder | package.rpf> [--top N] [--json] [--recomp] [--compile N] + bathyal shaders <file | folder | package.rpf> [--top N] [--json] [--recomp] [--compile N] Shader corpus statistics: formats, stages, RDNA2 instruction histogram (priorities for the recompiler). RPF9 packages are scanned for shader records. --recomp: translates every RDNA2 program → HLSL and shows what is missing; --compile N: additionally compiles N complete translations with DXC. - xcl rpf <package.rpf> [--top N] [--find NAME] [--extract NAME --out DIR] + bathyal rpf <package.rpf> [--top N] [--find NAME] [--extract NAME --out DIR] Lists or extracts readable inline records. Archives larger than 1 GB use a bounded-memory header probe; --probe requests it explicitly and --full overrides it. Use --probe only for header summaries, without --find, --extract, --out or --full. - xcl --version + bathyal --version "; fn main() { @@ -67,7 +67,7 @@ fn main() { Some("shaders") if args.len() >= 2 => xcl::shaders::run(&PathBuf::from(&args[1]), &args[2..]), Some("rpf") if args.len() >= 2 => xcl::rpf::run(&PathBuf::from(&args[1]), &args[2..]), Some("--version") | Some("-V") => { - println!("xcl {}", env!("CARGO_PKG_VERSION")); + println!("bathyal {} (XCL fork)", env!("CARGO_PKG_VERSION")); 0 } None if started_by_double_click() => run_picked_game(), @@ -110,7 +110,7 @@ fn run_picked_game() -> i32 { let Some(target) = target else { return 0 }; let _ = std::fs::create_dir_all(xcl::launcher::data_root()); let _ = std::fs::write(&last_file, target.to_string_lossy().as_bytes()); - println!("xcl run \"{}\"", target.display()); + println!("bathyal run \"{}\"", target.display()); let code = xcl::launcher::run(&target, &[]); if code != 0 { println!("\nXCL ended with code {code}. Press Enter to close."); @@ -199,9 +199,9 @@ fn menu(last: Option<&std::path::Path>) -> Choice { const AGAIN: i32 = 101; type TaskDialogIndirect = unsafe extern "system" fn(*const TASKDIALOGCONFIG, *mut i32, *mut i32, *mut i32) -> i32; let Some(f) = (unsafe { system_proc("comctl32.dll", "TaskDialogIndirect") }) else { return Choice::NoMenu }; - let title = wide("XCL"); + let title = wide("Bathyal"); let heading = wide("Run an Xbox Series game"); - let content = wide("XCL runs the game from its unpacked files. Choose the game's exe or its MicrosoftGame.config."); + let content = wide("Bathyal runs the game from its unpacked files. Choose the game's exe or its MicrosoftGame.config."); let again = last.map(|p| wide(&format!("Run again\n{}", p.display()))); let choose = wide("Choose a game…\nThe game's exe or MicrosoftGame.config"); let mut buttons = Vec::new(); @@ -237,7 +237,7 @@ fn pick_game_file() -> Option<PathBuf> { let f = unsafe { system_proc("comdlg32.dll", "GetOpenFileNameW") }?; // pairs of (description, pattern), each ending in NUL, the list in one more let filter: Vec<u16> = "Xbox game (*.exe, MicrosoftGame.config)\0*.exe;MicrosoftGame.config\0All files\0*.*\0\0".encode_utf16().collect(); - let title = wide("XCL – choose a game"); + let title = wide("Bathyal – choose a game"); let mut file = vec![0u16; 32768]; let mut ofn: OPENFILENAMEW = unsafe { std::mem::zeroed() }; ofn.lStructSize = std::mem::size_of::<OPENFILENAMEW>() as u32; diff --git a/crates/xcl/tests/disasm_e2e.rs b/crates/xcl/tests/disasm_e2e.rs index 675862a..25159cb 100644 --- a/crates/xcl/tests/disasm_e2e.rs +++ b/crates/xcl/tests/disasm_e2e.rs @@ -11,7 +11,7 @@ fn disasm_honors_byte_range_options() { std::env::temp_dir().join(format!("xcl-disasm-{}-{nonce}.bin", std::process::id())); std::fs::write(&shader, [0, 0, 0x80, 0xbf, 0, 0, 0x81, 0xbf]).unwrap(); let run = |args: &[&str]| { - Command::new(env!("CARGO_BIN_EXE_xcl")) + Command::new(env!("CARGO_BIN_EXE_bathyal")) .arg("disasm") .arg(&shader) .args(args) diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index f3082d2..aa73c18 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -69,7 +69,7 @@ fn launcher_uses_configured_exe_in_an_ambiguous_folder() { .unwrap(); std::fs::write(title.join("xcl.toml"), "exe = 'game.exe'\n").unwrap(); - let output = Command::new(env!("CARGO_BIN_EXE_xcl")) + let output = Command::new(env!("CARGO_BIN_EXE_bathyal")) .arg("run") .arg(&game) .env("XCL_DATA_ROOT", &data) @@ -86,7 +86,7 @@ fn launcher_uses_configured_exe_in_an_ambiguous_folder() { #[test] fn test_title_runs_and_game_folder_is_untouched() { - let xcl = PathBuf::from(env!("CARGO_BIN_EXE_xcl")); + let xcl = PathBuf::from(env!("CARGO_BIN_EXE_bathyal")); let bin_dir = xcl.parent().unwrap(); let title = bin_dir.join("xcl_testtitle.exe"); let dll = bin_dir.join("testgame_mw.dll"); @@ -252,7 +252,7 @@ fn test_title_draws_with_a_root_signature_under_the_debug_layer() { return; } } - let xcl = PathBuf::from(env!("CARGO_BIN_EXE_xcl")); + let xcl = PathBuf::from(env!("CARGO_BIN_EXE_bathyal")); let bin_dir = xcl.parent().unwrap(); let manifest = Path::new(env!("CARGO_MANIFEST_DIR")); let root = manifest.join("..").join("..").join("target").join("e2e-debug-layer"); diff --git a/scripts/block-egress.ps1 b/scripts/block-egress.ps1 index 1854f3e..5b3ea37 100644 --- a/scripts/block-egress.ps1 +++ b/scripts/block-egress.ps1 @@ -3,9 +3,9 @@ # should have no egress. Needs an elevated shell. Running it again keeps the existing rule. # # powershell -ExecutionPolicy Bypass -File scripts\block-egress.ps1 -# powershell -ExecutionPolicy Bypass -File scripts\block-egress.ps1 -Program D:\other\xcl.exe +# powershell -ExecutionPolicy Bypass -File scripts\block-egress.ps1 -Program D:\other\bathyal.exe param( - [string]$Program = (Join-Path (Split-Path -Parent $PSScriptRoot) 'target\release\xcl.exe'), + [string]$Program = (Join-Path (Split-Path -Parent $PSScriptRoot) 'target\release\bathyal.exe'), [string]$Name = '' ) $ErrorActionPreference = 'Stop' diff --git a/scripts/run-title.ps1 b/scripts/run-title.ps1 index 7c16b5e..7098bce 100644 --- a/scripts/run-title.ps1 +++ b/scripts/run-title.ps1 @@ -1,19 +1,19 @@ # Runs a title with the release build in a visible window and keeps a log of each run. # Before the first run it fills XCL's shader caches, as HANDOFF.md advises for large titles: compute programs # first (`--precompile --only cs`), then the compute pipelines (`--precompile --pipelines`). A marker file in the -# log folder records that this was done for this xcl.exe; -Precompile forces it again. +# log folder records that this was done for this bathyal.exe; -Precompile forces it again. # # powershell -ExecutionPolicy Bypass -File scripts\run-title.ps1 -Game D:\games\title # powershell -ExecutionPolicy Bypass -File scripts\run-title.ps1 -Game D:\games\title -Seconds 120 param( [Parameter(Mandatory = $true)][string]$Game, - [string]$Xcl = (Join-Path (Split-Path -Parent $PSScriptRoot) 'target\release\xcl.exe'), + [string]$Xcl = (Join-Path (Split-Path -Parent $PSScriptRoot) 'target\release\bathyal.exe'), [string]$Logs = (Join-Path $env:LOCALAPPDATA 'bathyal\runs'), [int]$Seconds = 0, [switch]$Precompile ) $ErrorActionPreference = 'Stop' -if (-not (Test-Path -LiteralPath $Xcl)) { throw "xcl.exe not found: $Xcl (cargo build --release --workspace)" } +if (-not (Test-Path -LiteralPath $Xcl)) { throw "bathyal.exe not found: $Xcl (cargo build --release --workspace)" } $shaders = Get-ChildItem -LiteralPath $Game -Filter 'shaders.rpf' -Recurse -Depth 2 -ErrorAction SilentlyContinue | Select-Object -First 1 New-Item -ItemType Directory -Force -Path $Logs | Out-Null @@ -34,5 +34,5 @@ if ($Seconds -gt 0) { $env:XCL_RUN_SECONDS = "$Seconds" } "running $Game; log $log" & $Xcl run $Game 2>&1 | Tee-Object -FilePath $log $code = $LASTEXITCODE -"xcl exited with code $code; the run's report.json is written as XCL describes in README.md" +"bathyal exited with code $code; the run's report.json is written as XCL describes in README.md" exit $code From 79a59ac487f0c054f81a018013ed375dc2807fa0 Mon Sep 17 00:00:00 2001 From: T-Crypt <T-Crypt@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:16:35 -0700 Subject: [PATCH 31/37] tests: CARGO_BIN_EXE_bathyal in every e2e test --- crates/xcl/tests/rpf_e2e.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/xcl/tests/rpf_e2e.rs b/crates/xcl/tests/rpf_e2e.rs index ed7a4c0..b6d4b12 100644 --- a/crates/xcl/tests/rpf_e2e.rs +++ b/crates/xcl/tests/rpf_e2e.rs @@ -14,7 +14,7 @@ fn full_scan_and_streaming_probe_agree_on_header_evidence() { std::fs::write(&archive, data).unwrap(); let run = |mode| { - Command::new(env!("CARGO_BIN_EXE_xcl")) + Command::new(env!("CARGO_BIN_EXE_bathyal")) .arg("rpf") .arg(&archive) .arg(mode) @@ -59,7 +59,7 @@ fn explicit_probe_rejects_conflicting_options() { &["--out", "unused"], ]; let outputs = options.map(|args| { - Command::new(env!("CARGO_BIN_EXE_xcl")) + Command::new(env!("CARGO_BIN_EXE_bathyal")) .arg("rpf") .arg(&archive) .arg("--probe") From 349c8481c2aa0baa3a716ee53f2e1cd65a57ef83 Mon Sep 17 00:00:00 2001 From: T-Crypt <T-Crypt@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:22:45 -0700 Subject: [PATCH 32/37] D3D12.X: title textures on shared 64 KiB pages of video memory - video memory stays at what the title covers (#248) From ivall/xcl#269 by @TG0000, squashed. --- .github/pull_request_template.md | 23 ++ .github/workflows/pr-check.yml | 59 +++ CLAUDE.md | 16 + CONTRIBUTING.md | 199 +++++++++ crates/xcl/src/hle/d3d12x/device_x.rs | 23 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 45 +- crates/xcl/src/hle/d3d12x/vram.rs | 429 +++++++++++++++----- scripts/smoke.ps1 | 64 +++ 8 files changed, 756 insertions(+), 102 deletions(-) create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/pr-check.yml create mode 100644 CLAUDE.md create mode 100644 CONTRIBUTING.md create mode 100644 scripts/smoke.ps1 diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..fe52870 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,23 @@ +<!-- What changes and why, in a few sentences. "Fixes #N" / "Part of #N". Stacked: "Stacked on #N". --> + +**What is in it** +- + +**Tested** +- hardware (GPU + driver, CPU), Rust version, debug / release: +- `cargo test --workspace -- --test-threads=4`: N passed, N failed, N ignored (SKIPPED GPU tests: …) + +**Regression run** +<!-- Required when the PR changes crates/xcl/src outside tests: `scripts/smoke.ps1` on a real title, + built from main and from this PR's head commit (no uncommitted changes); paste both blocks. + Rerun the PR's after every push. Not needed for docs / tests / scripts only. --> + +main: + +PR: + +**Not tested** +- + +**AI use** +- none / tool and model, and what it did diff --git a/.github/workflows/pr-check.yml b/.github/workflows/pr-check.yml new file mode 100644 index 0000000..c46c223 --- /dev/null +++ b/.github/workflows/pr-check.yml @@ -0,0 +1,59 @@ +# The description a pull request needs before it can be merged (CONTRIBUTING.md, "What a PR +# needs to be merged"): the Tested / Not tested / AI use sections, and – when it changes the +# runtime (crates/xcl/src outside tests) – two `xcl-smoke` blocks from scripts/smoke.ps1, one of +# them made on the PR's head commit with no uncommitted changes. Runs again when the description +# is edited or a commit is pushed. +name: PR checks + +on: + pull_request: + types: [opened, edited, synchronize, reopened, ready_for_review] + +permissions: + contents: read + pull-requests: read + +jobs: + description: + name: PR description + runs-on: ubuntu-latest + steps: + - name: Check the description + env: + GH_TOKEN: ${{ github.token }} + BODY: ${{ github.event.pull_request.body }} + HEAD: ${{ github.event.pull_request.head.sha }} + NUMBER: ${{ github.event.pull_request.number }} + REPO: ${{ github.repository }} + run: | + gh api "repos/$REPO/pulls/$NUMBER/files" --paginate --jq '.[].filename' > files.txt + python3 - <<'EOF' + import os, re, sys + body = os.environ.get("BODY") or "" + head = os.environ["HEAD"] + files = open("files.txt").read().split() + problems = [] + for section in ("Tested", "Not tested", "AI use"): + if not re.search(r"\*\*" + section + r"\*\*\s*\n\s*\S", body): + problems.append(f"the **{section}** section is missing or empty") + def runtime(f): + return f.startswith("crates/xcl/src/") and "/tests" not in f and not f.endswith("tests.rs") + if any(runtime(f) for f in files): + blocks = re.findall(r"xcl-smoke v1\s*\ncommit: (\S+)(.*)", body) + if len(blocks) < 2: + problems.append("the PR changes the runtime: **Regression run** needs two `xcl-smoke` blocks " + "(scripts/smoke.ps1 built from main and from this PR's head commit)") + elif not any(head.startswith(c) and "uncommitted" not in rest for c, rest in blocks): + problems.append(f"no `xcl-smoke` block was made on this PR's head commit {head[:12]} without " + "uncommitted changes - rerun scripts/smoke.ps1 after the last push") + for key in ("device removals", "crashes"): + for n in re.findall(key + r": (\d+)", body): + if int(n) > 0: + problems.append(f"a regression run shows {key}: {n}") + if problems: + print("This PR cannot be merged yet (see CONTRIBUTING.md, 'What a PR needs to be merged'):") + for p in problems: + print(" -", p) + sys.exit(1) + print("description ok") + EOF diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..e30885a --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,16 @@ +# Claude Code + +The instructions for agents in this repository are in `AGENTS.md`, and the rules for every +contributor are in `CONTRIBUTING.md`. Both apply to you: + +@AGENTS.md +@CONTRIBUTING.md + +Specific to Claude Code: + +- Plan a task that spans more than one subsystem or more than ~400 lines (plan mode), and propose + how to split it into PRs before you write code. +- Run the tests and report the real output; do not stop at "the tests should pass". +- Fill in the **AI use** section of the PR description with Claude Code and your exact model name. +- For a runtime change, run `scripts/smoke.ps1` on main and on the PR's head commit and paste both + `xcl-smoke` blocks; do not write or edit them by hand. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..75e48de --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,199 @@ +# Contributing to XCL + +Thanks for helping. XCL gets far more pull requests than one maintainer can read carefully, so +these rules exist to make every PR **cheap to review and safe to merge**. A PR that ignores them +may be closed without a review, however good the code is. + +AI tools are welcome (see [AI-assisted contributions](#ai-assisted-contributions)). The rules are +the same for code written by hand and by an agent. + +## What a PR needs to be merged + +XCL gets more pull requests in an hour than anyone can test by hand, most of them written with AI +tools. So a PR is merged only when it shows that it was tested and that it breaks nothing. These are +checked before anything else; a PR that does not meet them waits (or is closed after a week). + +1. **Both required checks are green:** `CI` (build and tests on Windows, no GPU) and `PR checks` + (the description: the sections below, and the regression runs when they are needed). +2. **The whole suite ran on a GPU**, with the counts in **Tested** + (`cargo test --workspace -- --test-threads=4`: N passed, N failed, N ignored, and the SKIPPED tests). +3. **A PR that changes the runtime** (`crates/xcl/src` outside tests) **has a regression run on a real + title**: `scripts/smoke.ps1 -Game <your game folder>` built from `main` and built from the PR's head + commit, both `xcl-smoke` blocks pasted under **Regression run**. The PR's block must name its head + commit with no uncommitted changes: rerun it after every push. It must show no device removal and + no crash, at least as many frames as `main` and no much higher peak commit. A run on a title that + does not reach the code the PR changes still counts as a regression check; say what it does not + cover under **Not tested**. +4. **No regression on the maintainer's run.** The maintainer merges in batches: the whole suite and a + retail title run again on the merged tree, on an AMD RDNA4 GPU. A PR that breaks either is taken + out of the batch and gets a comment with what failed. +5. **Up to date and reviewable:** it merges into `main` without conflicts, and keeps to the size and + scope rules below. A PR that duplicates one already merged is closed. + +A test result that was not produced by a real run on the hardware named gets the PR closed. + +## Before you start + +1. **Search open PRs and issues first.** Several PRs have solved the same problem at once and all + but one were closed. If someone is already on it, review or test their PR instead. +2. **Say what you are doing.** For anything bigger than a small fix, comment on the issue (or open + one) with the plan in two or three lines before writing it. That avoids duplicate work and wasted + effort on a direction the maintainer would not take. +3. **One problem per PR.** If you find a second bug while working, it gets its own PR. + +## Pull requests: small and single-purpose + +The smaller the PR, the faster it gets reviewed and merged. + +- **One logical change per PR.** A fix, a feature, a refactor and a test-only change are four PRs, + not one. "While I was here" changes go into a separate PR. +- **Size target: under ~400 changed lines**, not counting generated files and test data. Over ~800 + lines, the description must say why it cannot be split. Most large PRs can be split. +- **How to split** a large piece of work, in roughly this order: + 1. preparation that changes no behaviour (moving code, a new helper, a renamed type), + 2. new code behind a check or not yet called, with its tests, + 3. turning it on, + 4. diagnostics, logging and env-var switches, each on its own. +- **Stacked PRs** are fine when one change depends on another. Open each PR against `main`, say + `Stacked on #N` at the top of the description, and make it clear which commits belong to this PR. + Each PR in the stack must make sense when reviewed on its own. +- **No drive-by reformatting.** The tree is not `rustfmt`-clean. Do not run `cargo fmt` on whole + files or the whole crate: format only the lines you change. Reformatting buries the real diff. +- **No unrelated churn:** no renames, reordering, comment rewrites or dependency bumps the change + does not need. +- Keep the PR up to date by rebasing onto `main`, not by merging `main` into it. +- Open the PR as a **draft** until it builds, its tests pass and you have checked it yourself. + +### PR description + +Use this outline: + +```markdown +<What changes and why, in a few sentences. Link the issue: "Fixes #N" / "Part of #N".> +<If it is stacked: "Stacked on #N; only the top commit belongs here."> + +**What is in it** +- one bullet per commit or part, with the file it lives in + +**Tested** +- hardware (GPU + driver, CPU), Windows build, Rust version, debug/release +- commands run and their results, e.g. `cargo test --workspace -- --test-threads=4`: 541 passed, 0 failed, 21 ignored +- `SKIPPED` GPU tests on your adapter, if any +- game checked (if any), and what got better, with numbers if you have them + +**Regression run** +- for a runtime change: the two `xcl-smoke` blocks (main, this PR's head) – see above + +**Not tested** +- what you could not check, e.g. AMD / NVIDIA, the retail title, wave32-only GPUs + +**AI use** +- none / which tool and model (e.g. Claude Code with Claude Opus 5.5), and for what (see below) +``` + +"Not tested" is required. An honest "not tested on AMD" is fine. A test you did not run listed as +passing is not, and gets the PR closed. + +## Commits + +History is merged with merge commits, so every commit on a PR ends up in `main`. + +- **Scope prefix + outcome**, as in the existing history: + ``` + Recompiler: round f16 conversions and products to nearest-even by default + VFS: preserve the destination when an overlay rename fails + D3D12.X: draws with untranslated pipelines get the title's root signature + ``` + The prefix is the subsystem: `Recompiler`, `D3D12.X`, `DirectStorage`, `XGameRuntime`, + `kernelx`, `XAudio2`, `VFS`, `Memory`, `TLS`, `PE loader`, `Shaders`, `Frame clock`, `xcl run`, + `Tests`, `e2e`, `Scripts`, `README`, `Docs`, `Issue templates`. Use one that exists already when it fits. + No `fix:` / `feat(...)` style prefixes; this repo does not use Conventional Commits. +- Subject line of about 72 characters or less, saying what the change does, not "update file.rs" or + "fix bug". +- The body (optional for small changes) says **why**, and anything a reviewer could not see from the + diff: the root cause, what was measured, what was ruled out. +- **One logical change per commit.** Each commit builds and passes the tests on its own, so `git bisect` + works. +- **No fixup commits in the final PR**: squash "fix review", "wip", "fmt", "oops" commits into the + commit they fix before asking for review (`git rebase -i`, then force-push). +- Reference issues as `(#123)` in the subject or `Fixes #123` in the body. + +## Tests + +Add or change a test when the change touches logic: a bug fix gets a test that fails before the fix +and passes after it, and new behaviour gets a test that shows it working. Docs, comments, logging +and pure renames need no test. + +- **Unit tests** go in a `#[cfg(test)] mod tests` in the same file, the way the rest of the crate does it. +- **Integration / end-to-end tests** go in `crates/xcl/tests/`. The e2e test drives our own console + title in `tests/testtitle` / `tests/testgamedll`: extend it when a change concerns the path a title + takes. +- **GPU tests** must run without a GPU too: when the adapter cannot run them, call + `gpu::recomp::runner::skip_test("no GPU" | "no DXC" | "no wave64" | "no mesh shaders")` and return. + Never mark a test `#[ignore]` only so that it passes. +- **Tests on game data** read files the contributor owns through the `XCL_SAMPLE_*` variables + (see README / `scripts/test.ps1`), and pass without doing anything when the variable is not set. + **Never commit game data**, console SDK headers or binaries, or output dumped from a game. +- **Recompiler instructions** get a per-instruction GPU test compared against an expected result, + like the existing ones. +- Run the whole suite before opening the PR: + ```powershell + .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace + ``` + XCL builds and runs on Windows only. If you could not run the tests (e.g. you work on macOS or + Linux), say so in **Not tested**; a PR with no Windows test run waits until someone runs one. + +## Licence and provenance + +XCL is **GPL-2.0-only**. + +- Dependencies must be GPL-2.0-compatible (no Apache-2.0-only, no GPL-3.0). New dependencies need a + reason in the PR description; avoid them for a few lines of code. +- Code ported or adapted from another project needs a provenance note in the file (project, URL, + licence) and an entry in `THIRD_PARTY.md` when it is new. +- WinDurango (LGPL-3.0) is a reference only: no code is ported from it. +- Nothing from the console SDK: no headers, no binaries, no copied documentation. +- Generated files (`*_spec.rs`, tables) come with the script in `scripts/` that generates them, and + the PR says how they were generated. Do not edit them by hand. +- Nothing for decrypting or getting around DRM. + +## Docs + +- `README.md` tells users what works. Update it when your change makes something work (or stop + working) for them. +- `HANDOFF.md` and `docs/specs/` are the maintainer's design and status notes. Do not rewrite them in + a feature PR; if your change makes a statement in them wrong, point that out in the PR description. +- Everything in the repository (code, comments, commit messages, docs) is in English. + +## Reviews and test reports + +- **Test results on your GPU** go to [#42](https://github.com/ivall/xcl/issues/42), not a new issue. +- Testing someone else's PR helps the most when it follows the **Tested / Not tested** outline above + and names the exact commit tested. Post one comment and edit it when you rerun the tests; do not + post a new comment for every run. +- **AI-written test reports are welcome** when they come from a real run: the exact commit, the + hardware, the commands and their results. Say which tool and model wrote the report. +- **AI reviews:** check each point yourself, post only what you confirmed, and say that a tool helped. +- Reply to review comments in the thread, push the fix (squashed into the right commit), and mark the + thread resolved only once it is addressed. + +## AI-assisted contributions + +You can use any AI tool. In return: + +- **You are the author and you are responsible.** You have read every line of the diff, you + understand it, and you can answer questions about it without asking the tool again. "The AI wrote it" + is not an answer in a review. +- **Disclose it** in the PR's **AI use** section: the tool, the model, and what it did (wrote the + code, wrote the tests, wrote the description, only reviewed). A trailer in the commit naming the + model, such as `Co-Authored-By: <model>` or `Assisted-by: <tool> (<model>)`, is welcome too. +- **The tests were run, not just written.** Results in the PR come from a run you did, on hardware + you name. +- **A person opens the PR.** No PRs or issues opened by an unattended agent. +- **Keep the description short and true.** Leave out generated filler, marketing tone and claims + nobody measured. A reviewer should be able to read the description in one minute. +- The same size and scope rules apply. An agent can write 2000 lines in an hour, and nobody can + review that in an hour. Split it. + +Agents working in this repository read [`AGENTS.md`](AGENTS.md) (and Claude Code also reads +[`CLAUDE.md`](CLAUDE.md)), which put these rules into instructions for them. diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index aee3d02..e8dbfb0 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -899,11 +899,32 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, return hr; } } + // a texture the CPU fills: on the title's pages of such textures (`vram`), shared with the + // ones placed there before as on the console, else a committed texture of its own + let mut kept = if buffer { Err(String::new()) } else { super::title_textures::layout(&x) }; + let on_pages = kept.as_ref().ok().map(|t| t.size()).filter(|_| !super::vram::gpu_owned(flags)); + if let Some(console_bytes) = on_pages { + let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); + if let Some(hr) = super::vram::place_title_texture(this, va as usize, &pc, state, console_bytes, riid, ppv) { + let res = *ppv; + let tex = std::mem::replace(&mut kept, Err(String::new())); + if tex.and_then(|t| super::title_textures::register(this, res, va as usize, t, D3D12_RESOURCE_STATES(state as i32))).is_ok() { + real::note_title_address(res as usize, va as usize); + return hr; + } + // (not kept in step: the pages are not its own – a resource of its own instead) + if !res.is_null() { + drop(windows::core::IUnknown::from_raw(res)); + } + *ppv = std::ptr::null_mut(); + kept = super::title_textures::layout(&x); + } + } let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; let hr = real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, d.as_ptr() as usize, state as usize, clear as usize, riid, ppv); if hr >= 0 && !buffer && !(*ppv).is_null() { static M: AtomicU64 = AtomicU64::new(0); - match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { + match kept.and_then(|tex| super::title_textures::register(this, *ppv, va as usize, tex, D3D12_RESOURCE_STATES(state as i32))) { Ok(()) => { real::note_title_address(*ppv as usize, va as usize); return hr; diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 2d8194e..1e170a5 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -19,6 +19,11 @@ //! transitions of these textures are noted per PC command list as they are recorded //! (`note_transitions`) and applied, in submission order, when the list is submitted //! (`submitted`) – per subresource once a transition names one. +//! +//! The PC texture is a reserved resource on 64 KiB pages of video memory, one per page of the +//! title's address, shared by every such texture placed there (`vram::place_title_texture`) – +//! a title streaming its world places new textures over the old ones' memory; where it cannot +//! be (an address not 64 KiB aligned, a texture the driver does not reserve) it is committed. use std::collections::BTreeMap; use std::ffi::c_void; @@ -54,8 +59,15 @@ struct Entry { /// the title's GPU work wrote it (CopyTextureRegion into it): its CPU view is stale from /// then on and no longer uploaded gpu_written: bool, + /// the order it was placed in: textures placed over the same memory share its video memory + /// (`vram::place_title_texture`), and as on the console the newest one's texels are what it + /// holds – uploads go oldest first + seq: u64, } +/// the next texture's `Entry::seq` +static SEQ: AtomicU64 = AtomicU64::new(0); + /// textures waiting for their first upload static PENDING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); @@ -80,8 +92,9 @@ pub fn counts() -> (usize, u64) { (TEXTURES.lock().unwrap().len(), UPLOADS.load(Ordering::Relaxed)) } -/// A texture the title placed at `va` (its console desc `desc`): kept in step with the memory. -pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, desc: &[u8; 0x38], state: D3D12_RESOURCE_STATES) -> Result<(), String> { +/// The console layout of a texture the title places (its console desc `desc`) when it can be +/// kept in step with the memory (`register`); Err: why not. +pub(super) fn layout(desc: &[u8; 0x38]) -> Result<xg::Texture, String> { let tex = xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?; // the console's 32-bit 116 / 117 floats are half floats on the PC (`pc_resource_desc`): the // title's bytes are not the resource's texels @@ -110,13 +123,20 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, static N: AtomicU64 = AtomicU64::new(0); let n = N.fetch_add(1, Ordering::Relaxed) + 1; if n <= 2 || n.is_power_of_two() { - crate::xlog_info!("D3D12.X: a small render target at {va:#x} ({} planes) is kept in step with the title's memory – a glyph cache the CPU fills ({n} so far)", tex.planes.len()); + crate::xlog_info!("D3D12.X: a small render target ({} planes) is kept in step with the title's memory – a glyph cache the CPU fills ({n} so far)", tex.planes.len()); } } + Ok(tex) +} + +/// A texture the title placed at `va` (its console layout `tex`, from `layout`): kept in step +/// with the memory. +pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, tex: xg::Texture, state: D3D12_RESOURCE_STATES) -> Result<(), String> { if ID3D12Resource::from_raw_borrowed(&res).is_none() { return Err("no resource".into()); } - let e = Entry { device: device as usize, va, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false }; + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let e = Entry { device: device as usize, va, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false, seq }; { let mut t = TEXTURES.lock().unwrap(); if let Some(old) = t.insert(res as usize, e) { @@ -392,7 +412,7 @@ unsafe fn refresh_once(queue: *mut c_void) { } // textures made since the last submit and those with a written page; a reference each // while they are uploaded - let todo: Vec<(ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| { + let mut todo: Vec<(u64, ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); let mut t = TEXTURES.lock().unwrap(); t.iter_mut() @@ -412,11 +432,18 @@ unsafe fn refresh_once(queue: *mut c_void) { PENDING.fetch_sub(1, Ordering::Relaxed); } let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) + ID3D12Resource::from_raw_borrowed(&p).map(|r| (e.seq, r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) }) .collect() }); - upload_all(todo); + upload_all(in_placement_order(&mut todo)); +} + +/// The uploads `todo` (placement order, PC texture, upload) oldest placement first: where +/// textures share video memory the newest one's upload is the last word. +fn in_placement_order<R, U>(todo: &mut Vec<(u64, R, U)>) -> Vec<(R, U)> { + todo.sort_unstable_by_key(|t| t.0); + todo.drain(..).map(|(_, r, u)| (r, u)).collect() } /// staging bytes of one batch at most @@ -457,6 +484,8 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { continue; } }; + // textures on pages: their tiles' mappings come first + super::vram::before_execute(&queue); match own_work(|| texture::upload_batch(dev, &queue, &batch)) { Ok(failed) => { for (_, e) in failed { @@ -710,7 +739,7 @@ mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, seq: 0 }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().get(&res).unwrap().states.clone(); let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index dcca9ec..9b6c058 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -22,6 +22,11 @@ //! Arenas remain for what cannot be tiled (an address not 64 KiB aligned, a resource the //! driver does not make reserved: D32S8, MSAA): heaps of the placement's size, shared by //! placements inside them, let go 2 s after their last resource (256 MiB ones: 2.8 GB of D32S8). +//! +//! Textures the CPU fills (kept in step with the title's memory, `title_textures`) go on pages +//! the same way, in a space of their own (`Space`): a title streaming its world places new +//! textures over memory it used before and lets few of the old ones go, and a committed texture +//! per placement held the sum of every texture ever placed (#248). use std::collections::HashSet; use std::ffi::c_void; @@ -170,28 +175,133 @@ const COOL: std::time::Duration = std::time::Duration::from_secs(2); /// A pool tile: (pool heap, tile in it). type Tile = (u32, u32); +/// Which resources share a title page's video memory. GPU-owned targets share with targets, +/// textures kept in step with the title's memory (`title_textures`) with such textures: their +/// uploads are the CPU's view of the memory, which over a target's page would overwrite what +/// the GPU rendered there (on the console the memory holds it; here the CPU's view does not). +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub(super) enum Space { + Targets, + Textures, +} + struct Page { tile: Tile, - /// targets using the page + /// resources using the page users: u32, /// when the last of them went idle_since: Option<std::time::Instant>, } -/// The title's pages of video memory for GPU-owned textures (see the module's comment). +/// Which pool tile backs which title page, and which resource uses which pages – apart from +/// D3D12 (a new pool heap is the `grow` callback's). +struct Book { + free: Vec<Tile>, + /// tiles given back, reusable after `COOL` + cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, + /// (space, title page address) → its video memory + pages: std::collections::HashMap<(Space, usize), Page>, + /// resource → (its space, the title pages it uses, tiles of its own past the title's memory) + users: std::collections::HashMap<usize, (Space, Vec<usize>, Vec<Tile>)>, +} + +impl Book { + fn new() -> Book { + Book { free: Vec::new(), cooling: std::collections::VecDeque::new(), pages: std::collections::HashMap::new(), users: std::collections::HashMap::new() } + } + + /// Pages no resource used for `IDLE` go back to the pools. + fn sweep(&mut self, now: std::time::Instant) { + let old: Vec<(Space, usize)> = self.pages.iter().filter(|(_, p)| p.idle_since.is_some_and(|t| now.duration_since(t) >= IDLE)).map(|(&a, _)| a).collect(); + for a in old { + if let Some(p) = self.pages.remove(&a) { + self.cooling.push_back((p.tile, now)); + } + } + } + + /// A tile: a free one, one cooled down, else the first of a new pool heap (`grow`: its + /// index; None: no video memory). + fn take_tile(&mut self, now: std::time::Instant, grow: &mut impl FnMut() -> Option<u32>) -> Option<Tile> { + if let Some(t) = self.free.pop() { + return Some(t); + } + if self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + return self.cooling.pop_front().map(|(t, _)| t); + } + let h = grow()?; + self.free.extend((1..POOL_PAGES).rev().map(|t| (h, t))); + Some((h, 0)) + } + + /// The tiles of resource `res` at title address `va` in `space`: `total` tiles, the first + /// `own` on the title's pages there (shared with every resource of the space on them), the + /// rest its own. None: no video memory for all of them (nothing is kept). + #[allow(clippy::too_many_arguments)] + fn claim(&mut self, space: Space, res: usize, va: usize, own: usize, total: usize, now: std::time::Instant, grow: &mut impl FnMut() -> Option<u32>) -> Option<Vec<Tile>> { + self.sweep(now); + let mut tiles = Vec::with_capacity(total); + let mut used = Vec::with_capacity(own.min(total)); + let mut extra = Vec::new(); + for i in 0..total { + let tile = if i < own { + let a = va + i * PAGE; + let tile = match self.pages.get_mut(&(space, a)) { + Some(p) => { + p.users += 1; + p.idle_since = None; + Some(p.tile) + } + None => self.take_tile(now, grow).inspect(|&t| { + self.pages.insert((space, a), Page { tile: t, users: 1, idle_since: None }); + }), + }; + if tile.is_some() { + used.push(a); + } + tile + } else { + self.take_tile(now, grow).inspect(|&t| extra.push(t)) + }; + let Some(t) = tile else { break }; + tiles.push(t); + } + self.users.insert(res, (space, used, extra)); + if tiles.len() < total { + self.release(res, now); + return None; + } + Some(tiles) + } + + /// Resource `res` released: its pages are no longer its. + fn release(&mut self, res: usize, now: std::time::Instant) { + let Some((space, used, extra)) = self.users.remove(&res) else { return }; + for a in used { + if let Some(p) = self.pages.get_mut(&(space, a)) { + p.users = p.users.saturating_sub(1); + if p.users == 0 { + p.idle_since = Some(now); + } + } + } + self.cooling.extend(extra.into_iter().map(|t| (t, now))); + } + + /// bytes of the pages (idle ones included) and own tiles in use + fn bytes(&self) -> usize { + (self.pages.len() + self.users.values().map(|u| u.2.len()).sum::<usize>()) * PAGE + } +} + +/// The title's pages of video memory for textures in its memory (see the module's comment). struct Pages { queue: ID3D12CommandQueue, /// signalled after each mapping; title queues wait for it before their next work fence: ID3D12Fence, value: u64, pools: Vec<ID3D12Heap>, - free: Vec<Tile>, - /// tiles given back, reusable after `COOL` - cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, - /// title page address → its video memory - pages: std::collections::HashMap<usize, Page>, - /// target → (the title pages it uses, tiles of its own past the title's memory) - targets: std::collections::HashMap<usize, (Vec<usize>, Vec<Tile>)>, + book: Book, /// queue → the fence value it last waited for waited: std::collections::HashMap<usize, u64>, } @@ -213,37 +323,12 @@ impl Pages { } let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; - crate::xlog_info!("D3D12.X: GPU-owned textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); - Some(Pages { - queue, - fence, - value: 0, - pools: Vec::new(), - free: Vec::new(), - cooling: std::collections::VecDeque::new(), - pages: std::collections::HashMap::new(), - targets: std::collections::HashMap::new(), - waited: std::collections::HashMap::new(), - }) - } - - /// Pages no target used for `IDLE` go back to the pools. - fn sweep(&mut self, now: std::time::Instant) { - let old: Vec<usize> = self.pages.iter().filter(|(_, p)| p.idle_since.is_some_and(|t| now.duration_since(t) >= IDLE)).map(|(&a, _)| a).collect(); - for a in old { - if let Some(p) = self.pages.remove(&a) { - self.cooling.push_back((p.tile, now)); - } - } + crate::xlog_info!("D3D12.X: textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); + Some(Pages { queue, fence, value: 0, pools: Vec::new(), book: Book::new(), waited: std::collections::HashMap::new() }) } - unsafe fn take_tile(&mut self, dev: &ID3D12Device) -> Option<Tile> { - if let Some(t) = self.free.pop() { - return Some(t); - } - if self.cooling.front().is_some_and(|(_, at)| at.elapsed() >= COOL) { - return self.cooling.pop_front().map(|(t, _)| t); - } + /// A new pool heap (its index); None: no video memory. + unsafe fn grow(dev: &ID3D12Device, pools: &mut Vec<ID3D12Heap>) -> Option<u32> { let desc = D3D12_HEAP_DESC { SizeInBytes: POOL_PAGES as u64 * PAGE as u64, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, @@ -253,13 +338,11 @@ impl Pages { }; let mut heap: Option<ID3D12Heap> = None; if let Err(e) = dev.CreateHeap(&desc, &mut heap) { - crate::xlog_warn!("D3D12.X: no video memory for more pages of GPU-owned textures ({e})"); + crate::xlog_warn!("D3D12.X: no video memory for more pages of textures in title memory ({e})"); return None; } - self.pools.push(heap?); - let h = self.pools.len() as u32 - 1; - self.free.extend((1..POOL_PAGES).rev().map(|t| (h, t))); - Some((h, 0)) + pools.push(heap?); + Some(pools.len() as u32 - 1) } /// Map every tile of `res` (`tiles[i]`: overall tile i) – one call per pool heap. @@ -308,10 +391,11 @@ fn heap_ranges(heap: u32, tiles: &[Tile]) -> Vec<(bool, u32, u32)> { out } -/// A GPU-owned texture at `va` as a reserved resource on the title's pages there +/// A texture at `va` as a reserved resource on the title's pages there in `space` /// (`console_bytes`: its size on the console – the pages it covers; tiles past them are its -/// own). None: it cannot be (the caller tries an arena). -unsafe fn place_on_pages(dev: &ID3D12Device, this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void, console_bytes: Option<u64>, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<HRESULT> { +/// own). None: it cannot be (the caller tries an arena or a resource of its own). +#[allow(clippy::too_many_arguments)] +unsafe fn place_on_pages(dev: &ID3D12Device, this: *mut c_void, space: Space, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void, console_bytes: Option<u64>, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<HRESULT> { if va % PAGE != 0 || desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN { return None; } @@ -323,7 +407,7 @@ unsafe fn place_on_pages(dev: &ID3D12Device, this: *mut c_void, va: usize, desc: if hr < 0 || (*ppv).is_null() { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - crate::xlog_info!("D3D12.X: GPU-owned texture at {va:#x} ({}x{}, format {}, {} samples) not reserved ({hr:#x}): in an arena", desc.Width, desc.Height, desc.Format.0, desc.SampleDesc.Count); + crate::xlog_info!("D3D12.X: texture at {va:#x} ({space:?}: {}x{}, format {}, {} samples) not reserved ({hr:#x}): not on pages", desc.Width, desc.Height, desc.Format.0, desc.SampleDesc.Count); } return None; } @@ -332,63 +416,45 @@ unsafe fn place_on_pages(dev: &ID3D12Device, this: *mut c_void, va: usize, desc: let mut total = 0u32; dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); let own = console_bytes.map_or(total as usize, |b| (b as usize).div_ceil(PAGE)).min(total as usize); - let now = std::time::Instant::now(); - pages.sweep(now); - let mut tiles = Vec::with_capacity(total as usize); - let mut used = Vec::with_capacity(own); - let mut extra = Vec::new(); - for i in 0..total as usize { - let tile = if i < own { - let a = va + i * PAGE; - let tile = match pages.pages.get_mut(&a) { - Some(p) => { - p.users += 1; - p.idle_since = None; - Some(p.tile) - } - None => pages.take_tile(dev).inspect(|&t| { - pages.pages.insert(a, Page { tile: t, users: 1, idle_since: None }); - }), - }; - if tile.is_some() { - used.push(a); - } - tile - } else { - pages.take_tile(dev).inspect(|&t| extra.push(t)) - }; - let Some(t) = tile else { break }; - tiles.push(t); - } - pages.targets.insert(raw as usize, (used, extra)); - if tiles.len() < total as usize { - // no video memory for all of it: the target goes (its pages with it) + let Pages { book, pools, .. } = pages; + let Some(tiles) = book.claim(space, raw as usize, va, own, total as usize, std::time::Instant::now(), &mut || Pages::grow(dev, pools)) else { + // no video memory for all of it: the texture goes drop(g); - forget_pages(raw as usize); drop(windows::core::IUnknown::from_raw(raw)); *ppv = std::ptr::null_mut(); return None; - } + }; pages.map(res, &tiles); PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); Some(hr) } -/// A target released: its pages are no longer its. +/// A resource released: its pages are no longer its. fn forget_pages(resource: usize) { let mut g = PAGES.lock().unwrap(); let Some(Some(pages)) = g.as_mut() else { return }; - let Some((used, extra)) = pages.targets.remove(&resource) else { return }; - let now = std::time::Instant::now(); - for a in used { - if let Some(p) = pages.pages.get_mut(&a) { - p.users = p.users.saturating_sub(1); - if p.users == 0 { - p.idle_since = Some(now); - } - } + pages.book.release(resource, std::time::Instant::now()); +} + +/// A texture the title placed at `va` whose texels the CPU writes (kept in step with the memory, +/// `title_textures`) as a reserved resource on the title's pages of such textures (`desc`: the PC +/// description, `console_bytes` its size on the console). A title streams its world by placing +/// new textures over memory it used before – as the console allows: the new texture overwrites +/// the old one's memory – and lets few of the old ones go; a committed texture per placement +/// held the sum of every texture ever placed (a retail game: 12.7 GB of them over 4.0 GB of its +/// memory after 90 s, then the device was removed). On pages they cost the memory they cover. +/// None: not on pages (the caller makes a resource of its own). `XCL_TITLE_TEXTURE_PAGES=0` +/// turns this off. +pub unsafe fn place_title_texture(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, console_bytes: u64, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<HRESULT> { + static OFF: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if *OFF.get_or_init(|| std::env::var("XCL_TITLE_TEXTURE_PAGES").is_ok_and(|v| v.trim() == "0")) { + return None; } - pages.cooling.extend(extra.into_iter().map(|t| (t, now))); + let dev = ID3D12Device::from_raw_borrowed(&this)?; + if !tier2(dev) { + return None; + } + place_on_pages(dev, this, Space::Textures, va, desc, state, std::ptr::null(), Some(console_bytes), riid, ppv) } /// Before a title queue's work: it waits for the pages mapped since its last work. @@ -406,7 +472,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { pub fn page_bytes() -> (usize, usize) { let g = PAGES.lock().unwrap(); let Some(Some(p)) = g.as_ref() else { return (0, 0) }; - (p.pages.len() * PAGE + p.targets.values().map(|t| t.1.len()).sum::<usize>() * PAGE, p.pools.len() * POOL_PAGES as usize * PAGE) + (p.book.bytes(), p.pools.len() * POOL_PAGES as usize * PAGE) } /// Heaps of every kind of resource in one (resource heap tier 2) – else no arenas. @@ -425,7 +491,7 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st return None; } if std::env::var_os("XCL_VRAM_ARENAS").is_none() { - if let Some(hr) = place_on_pages(dev, this, va, desc, state, clear, console_bytes, riid, ppv) { + if let Some(hr) = place_on_pages(dev, this, Space::Targets, va, desc, state, clear, console_bytes, riid, ppv) { return Some(hr); } } @@ -463,6 +529,183 @@ mod tests { assert_eq!(heap_ranges(0, &[(0, 3), (0, 1), (0, 2)]), [(true, 3, 1), (true, 1, 2)]); } + /// A pool-heap maker for `Book` that numbers heaps as they are made. + fn heaps() -> impl FnMut() -> Option<u32> { + let mut n = 0; + move || { + n += 1; + Some(n - 1) + } + } + + /// Textures at one address share its pages, an overlapping one the pages they both cover; + /// targets there have pages of their own; tiles past the title's memory are each one's own. + #[test] + fn textures_share_pages_with_textures_not_with_targets() { + let (t, va) = (Instant::now(), 0x2_0000_0000usize); + let mut b = Book::new(); + let mut grow = heaps(); + let a = b.claim(Space::Textures, 1, va, 4, 4, t, &mut grow).unwrap(); + let same = b.claim(Space::Textures, 2, va, 4, 5, t, &mut grow).unwrap(); + assert_eq!(same[..4], a[..], "a texture placed over another one: the same memory"); + assert!(!a.contains(&same[4]), "a tile past the title's memory is its own"); + let over = b.claim(Space::Textures, 3, va + 2 * PAGE, 4, 4, t, &mut grow).unwrap(); + assert_eq!(over[..2], a[2..], "the pages both cover"); + assert!(!a.contains(&over[2]) && !a.contains(&over[3])); + let target = b.claim(Space::Targets, 4, va, 4, 4, t, &mut grow).unwrap(); + assert!(target.iter().all(|x| !a.contains(x) && !over.contains(x)), "a target's pages are not a texture's"); + // 6 texture pages, 4 target pages, 1 own tile + assert_eq!(b.bytes(), 11 * PAGE); + } + + /// The retail game's pattern (#248): textures streamed in over memory used before, nearly + /// none released. Committed, they held the sum of every texture placed; on pages, the memory + /// they cover. + #[test] + fn streamed_textures_cost_the_memory_they_cover() { + const SPAN: usize = 256 * MIB; + let (t, va) = (Instant::now(), 0x3_0000_0000usize); + let mut b = Book::new(); + let mut grow = heaps(); + let mut placed = 0usize; + // 8000 textures of 64 KiB to 4 MiB at page addresses all over the span + let mut x = 0x2545_F491u32; + for res in 0..8000usize { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + let pages = 1usize << (x % 7); + let at = (x as usize >> 3) % (SPAN / PAGE - pages) * PAGE; + b.claim(Space::Textures, res, va + at, pages, pages, t, &mut grow).unwrap(); + placed += pages * PAGE; + } + assert!(placed > 30 * SPAN, "the test places {placed} bytes"); + assert!(b.bytes() <= SPAN, "{} bytes of pages for a span of {SPAN}", b.bytes()); + } + + /// A page no resource uses keeps its tile (and what it holds) for 2 s, then the tile cools + /// another 2 s before it is reused; a claim without video memory for all of it keeps nothing. + #[test] + fn released_pages_are_kept_then_cooled_before_reuse() { + let (t, va) = (Instant::now(), 0x4_0000_0000usize); + let s = Duration::from_secs; + let mut b = Book::new(); + let mut grow = heaps(); + let first = b.claim(Space::Textures, 1, va, 1, 1, t, &mut grow).unwrap(); + b.release(1, t); + assert_eq!(b.claim(Space::Textures, 2, va, 1, 1, t + s(1), &mut grow).unwrap(), first, "placed again within 2 s: the same memory"); + b.release(2, t + s(1)); + // the page is let go at 3 s (2 s idle) and its tile cools until 5 s + b.sweep(t + s(3)); + assert!(b.pages.is_empty()); + b.free.clear(); + assert!(b.claim(Space::Textures, 3, va, 1, 1, t + s(4), &mut || None).is_none(), "the tile is still cooling, no new heap"); + assert_eq!(b.claim(Space::Textures, 4, va + PAGE, 1, 1, t + s(5), &mut || None).unwrap(), first, "cooled down: reused"); + // 3 pages wanted, one tile to be had: nothing kept, the tile reusable + b.free.push((7, 7)); + assert!(b.claim(Space::Textures, 5, va + 8 * PAGE, 3, 3, t + s(5), &mut || None).is_none()); + assert!(!b.users.contains_key(&5)); + assert!(b.pages.get(&(Space::Textures, va + 8 * PAGE)).is_some_and(|p| p.users == 0), "its page is idle, not in use"); + } + + /// On the GPU: kept-in-step textures placed at one title address are one memory (an upload + /// through one is what the other reads), and many placements there take one texture's video + /// memory. Needs a hardware adapter with tiled resources tier 2 (skips otherwise). + #[test] + fn title_textures_at_one_address_share_video_memory() { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let Ok(adapter) = factory.EnumAdapters1(0) else { return }; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { + eprintln!("SKIPPED title_textures_at_one_address_share_video_memory: software adapter"); + return; + } + let mut dev: Option<ID3D12Device> = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev.filter(|d| tier2(d)) else { return }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let memory: IDXGIAdapter3 = adapter.cast().unwrap(); + let local = || { + let mut i = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let _ = memory.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut i); + i.CurrentUsage as usize + }; + // RGBA8 512x512, one mip: 1 MiB (16 pages) on the console + let (w, h) = (512u32, 512u32); + let console_bytes = (w * h * 4) as u64; + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: w as u64, Height: h, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8G8B8A8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }; + let srv = D3D12_RESOURCE_STATES(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let place_at = |va: usize| { + let mut p = std::ptr::null_mut(); + let hr = place_title_texture(dev.as_raw(), va, &desc, srv.0 as u32, console_bytes, riid, &mut p); + if hr.is_none() { + return None; + } + assert!(hr.is_some_and(|hr| hr >= 0) && !p.is_null(), "texture at {va:#x}"); + Some(ID3D12Resource::from_raw(p)) + }; + let va = 0x60_0000_0000usize; + let Some(a) = place_at(va) else { + eprintln!("SKIPPED title_textures_at_one_address_share_video_memory: no reserved RGBA8 textures"); + return; + }; + let b = place_at(va).unwrap(); + + // texels uploaded through b are what a holds + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + before_execute(&queue); + let texels: Vec<u8> = (0..w * h * 4).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); + let sub = crate::gpu::texture::Subresource { rows: h as usize, row_bytes: w as usize * 4, depth: 1, data: texels.clone() }; + let failed = crate::gpu::texture::upload_batch(&dev, &queue, &[(b.clone(), vec![sub], vec![srv])]).unwrap(); + assert!(failed.is_empty(), "{failed:?}"); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + dev.GetCopyableFootprints(&desc, 0, 1, 0, Some(&mut fp), None, None, Some(&mut total)); + let buffer = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; + let mut readback: Option<ID3D12Resource> = None; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback).unwrap(); + let readback = readback.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let barrier = |from: D3D12_RESOURCE_STATES, to: D3D12_RESOURCE_STATES| { + let t = D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(&a), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: from, StateAfter: to }; + D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(t) }, ..Default::default() } + }; + // (tiles shared between two reserved resources: an aliasing barrier between them) + let alias = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, Anonymous: D3D12_RESOURCE_BARRIER_0 { Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { pResourceBefore: std::mem::transmute_copy(&b), pResourceAfter: std::mem::transmute_copy(&a) }) }, ..Default::default() }; + list.ResourceBarrier(&[alias, barrier(srv, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::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: std::mem::transmute_copy(&a), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, srv)]); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + crate::gpu::texture::wait(&dev, &queue).unwrap(); + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).unwrap(); + let pitch = fp.Footprint.RowPitch as usize; + let bad = (0..h as usize).filter(|&y| std::slice::from_raw_parts((p as *const u8).add(y * pitch), w as usize * 4) != &texels[y * w as usize * 4..(y + 1) * w as usize * 4]).count(); + readback.Unmap(0, None); + assert_eq!(bad, 0, "rows of the texture placed first that differ from what was uploaded through the second"); + + // 256 more placements at 8 addresses: video memory for 8 textures, not 256 + let used0 = local(); + let pages0 = page_bytes().0; + let more: Vec<ID3D12Resource> = (0..256).map(|k| place_at(va + 0x100_0000 + (k % 8) * 0x10_0000).unwrap()).collect(); + let (used, pages) = (local().saturating_sub(used0), page_bytes().0 - pages0); + println!("256 RGBA8 512x512 textures at 8 addresses: {pages} bytes of pages, {used} bytes more local video memory"); + assert!(pages <= 8 * console_bytes as usize + 256 * PAGE, "{pages} bytes of pages"); + assert!(used < 64 * console_bytes as usize, "{used} bytes of video memory"); + drop((more, a, b)); + } + } + /// A placement's arena id, with heaps numbered as they are made. fn take(a: &mut Arenas<u32>, va: usize, bytes: usize, align: usize, now: Instant) -> u64 { let n = a.list.len() as u32; diff --git a/scripts/smoke.ps1 b/scripts/smoke.ps1 new file mode 100644 index 0000000..a4f668a --- /dev/null +++ b/scripts/smoke.ps1 @@ -0,0 +1,64 @@ +# Regression run of a title for a pull request: runs it for a fixed time, reads XCL's log and +# prints an `xcl-smoke` block to paste into the PR's "Regression run" section – once built +# from main, once from the PR's head commit (CONTRIBUTING.md, "What a PR needs to be merged"). +# +# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] +# +# Networking is off (XCL_NETWORK=0). Build first: cargo build --release -p xcl +param( + [Parameter(Mandatory = $true)][string]$Game, + [int]$Seconds = 60, + [string]$Xcl = (Join-Path $PSScriptRoot '..\target\release\xcl.exe') +) +$ErrorActionPreference = 'Stop' + +if (-not (Test-Path $Xcl)) { throw "no $Xcl - build it first (cargo build --release -p xcl)" } +$root = Split-Path $PSScriptRoot -Parent +$commit = (git -C $root rev-parse HEAD).Trim() +$dirty = [bool](git -C $root status --porcelain --untracked-files=no -- crates Cargo.toml Cargo.lock) + +$out = New-TemporaryFile +$err = New-TemporaryFile +$env:XCL_NETWORK = '0' +$env:XCL_RUN_SECONDS = "$Seconds" +$env:XCL_ACTIVITY = '1' +$p = Start-Process -FilePath $Xcl -ArgumentList @('run', "`"$Game`"") -NoNewWindow -PassThru -RedirectStandardOutput $out -RedirectStandardError $err +$null = $p.Handle # (without it ExitCode stays empty) +if (-not $p.WaitForExit(($Seconds + 120) * 1000)) { + Stop-Process -Id $p.Id -Force + $timedOut = $true +} +Remove-Item Env:XCL_RUN_SECONDS, Env:XCL_ACTIVITY + +$stdout = Get-Content $out -Raw -Encoding utf8 +Remove-Item $out, $err +$logLine = ($stdout -split "`n" | Where-Object { $_ -match '^Log:\s+(.+)$' } | Select-Object -Last 1) +if (-not $logLine) { throw "XCL printed no log path; its output:`n$stdout" } +$log = ($logLine -replace '^Log:\s+', '').Trim() +$text = Get-Content $log -Raw -Encoding utf8 + +$frames = if ($text -match '\((\d+) frames shown, (\d+) PresentX calls\)') { "$($Matches[1]) (PresentX $($Matches[2]))" } else { 'none logged (the run did not reach its end)' } +$presents = [regex]::Matches($text, 'activity \(2 s\): (\d+) presents') | ForEach-Object { [int]$_.Groups[1].Value } +$lastPresents = ($presents | Select-Object -Last 3) -join ' ' +$commits = [regex]::Matches($text, 'memory: (\d+) MB committed') | ForEach-Object { [int]$_.Groups[1].Value } +$peak = if ($commits) { ($commits | Measure-Object -Maximum).Maximum } else { 'n/a' } +$removals = ([regex]::Matches($text, 'device removed')).Count +$crashes = ([regex]::Matches($text, 'unhandled exception|process ends with status')).Count +$gpu = (Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Basic' } | Select-Object -First 1).Name +$code = if ($timedOut) { 'killed (no exit)' } else { '0x{0:x}' -f $p.ExitCode } + +@" +`````` +xcl-smoke v1 +commit: $commit$(if ($dirty) { ' (uncommitted changes)' }) +gpu: $gpu +title: $(Split-Path $Game -Leaf) +seconds: $Seconds +exit: $code +frames shown: $frames +presents per 2 s (last 3): $lastPresents +device removals: $removals +crashes: $crashes +peak commit: $peak MB +`````` +"@ From db5c0b294a8771a1ea16581311a0136001b2278d Mon Sep 17 00:00:00 2001 From: T-Crypt <T-Crypt@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:22:51 -0700 Subject: [PATCH 33/37] VS / PS whole-wave reductions as wave operations (partial waves, every GPU) From ivall/xcl#152 by @Foniass, squashed; conflict resolved by hand. --- HANDOFF.md | 35 +- crates/xcl/src/gpu/recomp/emit.rs | 95 ++++ crates/xcl/src/gpu/recomp/mod.rs | 47 +- crates/xcl/src/gpu/recomp/reductions.rs | 544 +++++++++++++++++++ crates/xcl/src/gpu/recomp/runner.rs | 32 +- crates/xcl/src/gpu/recomp/tests.rs | 693 ++++++++++++++++++++++-- docs/wave64-on-wave32.md | 105 +++- 7 files changed, 1480 insertions(+), 71 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/reductions.rs diff --git a/HANDOFF.md b/HANDOFF.md index d68bf3e..e6c6913 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1725,7 +1725,7 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76 - Not exact yet, on every GPU: whole-wave code in a partial wave reads lanes the PC never launched (the console's inactive lanes run it). Measured on the 5070 Ti: such lanes read 0 – a min reduction (identity -1) gives 0 in a 3-quad wave, max / or / sum are right. 325 of the 436 reduction programs have a min reduction. Needs the reduction - recognised as a whole (`docs/wave64-on-wave32.md`, "Vertex and pixel shaders"). + recognised as a whole (`docs/wave64-on-wave32.md`, "Vertex and pixel shaders"). Done next (below). - Merged as PR #133. On the RX 9070 (64-lane waves) the native-form digest of the 26 698 programs equals `main`'s (the forms test run on both); the three GPU tests pass, also with `XCL_SPLIT_WAVE64=1`; XDefiant and Minecraft run with and without `XCL_SPLIT_WAVE64=1` (the forced split form starts with a cold shader cache: XDefiant black while compiling). @@ -1893,6 +1893,37 @@ three `graphics PSO rejected (0x8007000e)` just before are the driver's E_OUTOFM - Scripts for the DLL (in the session's scratch, not the repo): a PE reader (`fo(va)`, `q(va)`), a scan of `.rdata` for runs of code pointers (vtables), `x86_64-w64-mingw32-objdump -d -M intel --start-address … --stop-address …`. +## Whole-wave reductions as wave operations, 2026-11-23 +- The reduction of the pack's PS (and one VS) is now recognised as a whole (`recomp/reductions.rs`) and replaced + with wave operations, on every GPU and at both wave sizes (`docs/wave64-on-wave32.md`, "Whole-wave reductions"): + `s_or_saveexec -1`, `v_cndmask` of x / the op's identity by a mask within the saved EXEC, three DPP8 steps, + row_mirror, `v_permlanex16`, `v_readlane` 32 / 0 (wave64) or 0 (wave32), EXEC restored; min_u32 / max_u32 / or_b32. + The pack's DPP8 selects are not lane-xor permutations (`[2,2,0,0,6,6,4,4]`, `[4,4,4,4,0,0,0,0]` after the pair + step): the matcher follows the set of lanes each lane has read and asks for the whole row after the mirror. +- Emitted: `xcl_wave_<op>(x, mask)` = the op over the mask's lanes per 16-lane row of the hardware wave + (`WaveActiveMin(row == k ? q : identity)`; in a PS q is first the op over the quad through quad reads – helper + lanes, which wave operations leave out, are in a mask taken from EXEC after `s_wqm`); from the rows sH, sT and what + vA / vB hold in every lane afterwards. A 64-lane wave of a wave32 program: rows 0–1 / 2–3 by `xcl_half`. +- Census (`retail_wave_reductions_census`, ignored): wave64 VS / PS all 1 082 sites in 436 programs (min 325, max + 322, or 435 sites); wave32 PS all 2 106 sites in 926 programs (min 588, max 588, or 930). The lane-32 constants of + #133 are all inside them; 110 of those programs still get the 32-lane form for spill slots. Compute / mesh keep the + steps (same form at 4 371 of 4 607 wave32 CS sites, 94 of 1 148 wave64 CS, 17 of 17 wave64 MS; the rest sums, + prefix sums, a float min / max, `v_and`). +- `retail_wave64_graphics_lane_forms`: the native HLSL changes for exactly the 1 362 VS / PS with a reduction (the 25 336 others byte-identical – per-program digests, `XCL_FORMS_LIST`, against + `XCL_NO_WAVE_REDUCTIONS=1`); the other modes' 32-lane digest stays `09d45ad13eddc30d`; the 32-lane form differs + for 287 programs (spill slots; 613 before). DXC compiles all of them. +- Tests on the RTX 5070 Ti: `gpu_ps_partial_wave_reductions` (wave64 and wave32; min / max / or over the odd pixels + and over the quads' lanes; whole target, 3 quads, 55 pixels; sT, sH, vA, vB of every pixel against a console + wave of the same lanes), `gpu_vs_partial_wave_reductions` (3 vertices), `reductions::tests`. Before + (`XCL_NO_WAVE_REDUCTIONS=1`, which gives `main`'s HLSL: digests `ac67db269b7452be` / `09d45ad13eddc30d`): every + partial-wave min is 0, the or over the quads' lanes of 3 quads misses two helper pixels, the VS min is 0. +- Helper lanes (found in review): wave operations leave them out (on the RTX 5070 Ti they return 0 there), the + console leaves the result in every lane: in a PS each lane takes its quad's result (a helper gives the identity), + `gpu_ps_reduction_result_in_helper_lanes` (46 of 54 cases differed), `gpu_ps_reductions_in_branches_and_loops`. +- Test runner: draws share one queue per device. After a test brings up the D3D12.X backend (`real::init`) its hooks + are on the adapter's device and the per-draw queues were not given back – the draw-heavy tests ended in + E_OUTOFMEMORY at CreateCommandQueue with several test threads. + ## Next steps (priority) Little is left to do without the exe – the rest needs an actual run of the game. 1. Once the user has a legal game exe: `xcl inspect`, `xcl run`, analysis of `report.json` @@ -1906,6 +1937,6 @@ Little is left to do without the exe – the rest needs an actual run of the gam pipe/packer configuration for the _X modes (`texture::CONSOLE_PIPES`), MSAA. 4. Audio: Opus is decoded (0x704F voices); with the exe check how the title feeds it (voice format, buffer framing, or a console API); XMA2 low priority (the game has none). -5. Smaller: whole-wave reductions in partial waves (325 PS with a min reduction, every GPU), `image_sample_o` with an offset from a VGPR, +5. Smaller: whole-wave reductions of compute / mesh programs in partial waves (VS / PS done), `image_sample_o` with an offset from a VGPR, smaller HLSL, further XGameRuntime APIs (XGameUI, XNetworking…), GameInput → system GameInput.dll, mapping physical pages at the game's address. diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 3b95148..e353c1f 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4,6 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write as _; use super::{elements_at, param_registers, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; +use super::reductions::{Op as WaveOp, Reduction}; use super::upper_lanes::Read; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; @@ -53,6 +54,11 @@ pub(super) struct Em { /// 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<super::upper_lanes::UpperLanes>, + /// whole-wave reductions of a VS / PS recognised as a whole (`reductions`), by the pc of + /// their `v_cndmask`; the pcs of their other steps, emitted as nothing; the ops used + reductions: BTreeMap<u64, Reduction>, + reduced: BTreeSet<u64>, + wave_ops: BTreeSet<WaveOp>, /// pc of the instruction being emitted cur_pc: u64, /// MIMG instruction address → its sampler's S# when the code builds it from constants @@ -560,6 +566,9 @@ impl Em { loops: Vec::new(), cs_pad: false, upper: None, + reductions: BTreeMap::new(), + reduced: BTreeSet::new(), + wave_ops: BTreeSet::new(), cur_pc: 0, static_ss: BTreeMap::new(), static_used: Vec::new(), @@ -617,6 +626,12 @@ impl Em { std::mem::take(&mut self.out) } + /// Whole-wave reductions to emit as a whole (`reductions::find`). + pub fn set_reductions(&mut self, rs: Vec<Reduction>) { + self.reduced = rs.iter().flat_map(|r| r.rest.iter().copied()).collect(); + self.reductions = rs.into_iter().map(|r| (r.at, r)).collect(); + } + fn line(&mut self, s: &str) { for _ in 0..self.indent { self.out.push_str(" "); @@ -926,6 +941,42 @@ impl Em { } } + /// A whole-wave reduction recognised as a whole (`reductions`), from its `v_cndmask` to + /// its `v_readlane` of lane 0: the op over the mask's lanes of each 16-lane row of the + /// hardware wave (`xcl_wave_<op>`), and from those what the steps leave – vB the other + /// row's of its half (`v_permlanex16`), vA the wave's (wave64: in lanes 0..31, the upper + /// half's in 32..63), sH the upper half's, sT the wave's. A wave64 program's hardware wave + /// is (the lower part of) its console wave; a wave32 program's 64-lane wave holds two + /// console waves, one per half (`xcl_half`). Every lane writes vA and vB, as under the + /// console's whole-wave EXEC. + fn reduction(&mut self, r: &Reduction) { + let x = self.code32(r.x, r.literal, false).unwrap_or_else(|| "0u".into()); + let m0 = self.sreg(r.mask); + let m1 = if r.wave64 { self.sreg(r.mask + 1) } else { "0u".into() }; + let t = self.t(); + self.line(&format!("uint4 {t} = xcl_wave_{}({x}, {m0}, {m1});", r.op.name())); + let row = |k: &str| format!("{t}.{k}"); + let (lower, upper) = (r.op.hlsl(&row("x"), &row("y")), r.op.hlsl(&row("z"), &row("w"))); + let (a, b) = (self.vreg(r.acc), self.vreg(r.other)); + let st = self.sreg(r.total); + self.line(&format!("{b} = {t}[(WaveGetLaneIndex() >> 4) ^ 1u];")); + match r.half { + Some(sh) => { + let sh = self.sreg(sh); + self.line(&format!("uint {t}_h = {upper};")); + self.line(&format!("uint {t}_w = {};", r.op.hlsl(&lower, &format!("{t}_h")))); + self.line(&format!("{a} = select(lane_id < 32u, {t}_w, {t}_h);")); + self.line(&format!("{sh} = {t}_h;")); + } + None => { + self.line(&format!("uint {t}_w = select(xcl_half != 0u, {upper}, {lower});")); + self.line(&format!("{a} = {t}_w;")); + } + } + self.line(&format!("{st} = {t}_w;")); + self.wave_ops.insert(r.op); + } + // ---------------------------------------------------------------- one instruction pub fn inst(&mut self, d: &Decoded, next: u64) -> Flow { @@ -933,6 +984,15 @@ impl Em { let text = rdna2::format(d); self.line(&format!("// {:04x}: {text}", d.pc)); self.cur_pc = d.pc; + // a whole-wave reduction recognised as a whole: emitted at its v_cndmask, its other + // steps as nothing + if let Some(r) = self.reductions.get(&d.pc).cloned() { + self.reduction(&r); + return Flow::Next; + } + if self.reduced.contains(&d.pc) { + return Flow::Next; + } // a far jump (`rdna2::resolve_far_jumps`) is an unconditional branch if let Some(t) = d.far_target { return Flow::Jump(t); @@ -4352,6 +4412,9 @@ impl Em { let _ = writeln!(h, "static uint xcl_sh{v}_{l} = 0u; // v_writelane slot: v{v} lane {l}"); } } + for op in &self.wave_ops { + h.push_str(&wave_reduction_fn(*op, matches!(self.opt.mode, Mode::Pixel(_)))); + } let infos: Vec<String> = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect(); let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", ")); h.push_str(PRELUDE_MEM); @@ -5434,6 +5497,38 @@ void st_bytes(uint a, uint4 r, uint n) { uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, select(sel == 1u, select(isint, 1u, 0x3F800000u), c[(sel - 4u) & 3u])); } "#; +/// `xcl_wave_<op>(x, m0, m1)` of a whole-wave reduction (`Em::reduction`): the op over the +/// lanes of the console wave's mask m0 / m1 – x there, the identity elsewhere – per 16-lane +/// row of the hardware wave (x: lanes 0..15 … w: 48..63). Wave operations leave out the lanes +/// the PC did not launch (never in the mask) and helper lanes: in a pixel shader each lane +/// first takes the op over its quad, through quad reads, which see helper lanes. +fn wave_reduction_fn(op: WaveOp, pixel: bool) -> String { + let (name, id) = (op.name(), hex(op.identity())); + let mut s = format!("// whole-wave v_{name} of the console (`reductions`): over the lanes of mask m0 / m1, per 16-lane row of the wave\nuint4 xcl_wave_{name}(uint x, uint m0, uint m1) {{\n"); + if pixel { + s.push_str(" // the quad first: quad reads see its helper lanes, wave operations do not\n uint b = lane_id & ~3u;\n"); + let _ = writeln!(s, " uint q = select(lanebit_at(m0, m1, b), QuadReadLaneAt(x, 0u), {id});"); + for k in 1..4 { + let _ = writeln!(s, " q = {};", op.hlsl("q", &format!("select(lanebit_at(m0, m1, b + {k}u), QuadReadLaneAt(x, {k}u), {id})"))); + } + } else { + let _ = writeln!(s, " uint q = select(lanebit_at(m0, m1, lane_id), x, {id});"); + } + let rows: Vec<String> = (0..4).map(|k| format!("{}(select(r == {k}u, q, {id}))", op.wave())).collect(); + if pixel { + // wave operations leave helper lanes out (on the RTX 5070 Ti they return 0 there), but + // the console leaves the result in every lane, helpers included – and helpers feed the + // derivatives of what is computed from it: each lane takes its quad's live result + let _ = writeln!(s, " uint r = WaveGetLaneIndex() >> 4;\n uint4 t = uint4({});", rows.join(", ")); + let _ = writeln!(s, " uint4 h = IsHelperLane() ? (uint4){id} : t;"); + let c = op.hlsl(&op.hlsl("QuadReadLaneAt(h, 0u)", "QuadReadLaneAt(h, 1u)"), &op.hlsl("QuadReadLaneAt(h, 2u)", "QuadReadLaneAt(h, 3u)")); + let _ = writeln!(s, " return {c};\n}}"); + return s; + } + let _ = writeln!(s, " uint r = WaveGetLaneIndex() >> 4;\n return uint4({});\n}}", rows.join(", ")); + s +} + /// A console wave64 as two hardware wave32 halves of one thread group (docs/wave64-on-wave32.md): /// per-lane code is unchanged, and the halves meet ("exchange") wherever a value has to be /// the whole wave's – masks, lane reads, coherent scalar loads – so both hold the same SGPRs diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 6a864b8..c887ab9 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -59,6 +59,7 @@ pub mod mesh_wave; pub mod partial_waves; pub mod x64_masks; pub mod pso; +pub mod reductions; pub use emit::mesh_passthrough; pub mod runner; #[cfg(test)] @@ -1133,7 +1134,8 @@ pub fn wave_hazards(code: &[u8]) -> BTreeSet<&'static str> { wave_lane_reads(code).0 } -/// `wave_hazards` and the kinds of reads `upper_lanes` resolves. +/// `wave_hazards` and the kinds of reads `upper_lanes` resolves – reads inside a whole-wave +/// reduction recognised as a whole (`reductions`) count as that. pub fn wave_lane_reads(code: &[u8]) -> (BTreeSet<&'static str>, BTreeSet<&'static str>) { let mut insts = Vec::new(); let mut off = 0; @@ -1143,8 +1145,37 @@ pub fn wave_lane_reads(code: &[u8]) -> (BTreeSet<&'static str>, BTreeSet<&'stati insts.push(d); } rdna2::resolve_far_jumps(&mut insts); - let a = upper_lanes::analyze(&insts); - (a.hazards(&insts), a.resolved()) + let mut a = upper_lanes::analyze(&insts); + let rs = wave_reductions(&insts, true); + let reduced: BTreeSet<u64> = rs.iter().flat_map(|r| r.rest.iter().copied()).collect(); + a.reads.retain(|pc, _| !reduced.contains(pc)); + let mut resolved = a.resolved(); + if !rs.is_empty() { + resolved.insert("whole-wave min / max / or reduction (WaveActive*)"); + } + (a.hazards(&insts), resolved) +} + +/// The whole-wave reductions of a program of that wave size (`reductions`); +/// `XCL_NO_WAVE_REDUCTIONS=1`: none – each step translated on its own, as before (for +/// comparison). +fn wave_reductions(insts: &[Decoded], wave64: bool) -> Vec<reductions::Reduction> { + if std::env::var_os("XCL_NO_WAVE_REDUCTIONS").is_some() { + return Vec::new(); + } + reductions::find(insts, wave64) +} + +/// The reductions a translation emits as wave operations: those of VS / PS, whose hardware +/// wave holds (the lower part of) one wave64 console wave, or one or two wave32 console +/// waves (`xcl_half`). Compute-like modes keep the steps: there a wave64 console wave is two +/// hardware waves on GPUs with 32-lane waves (`x64`). +fn graphics_reductions(insts: &[Decoded], opt: &Options) -> Vec<reductions::Reduction> { + if matches!(opt.mode, Mode::Vertex(_) | Mode::Pixel(_)) { + wave_reductions(insts, opt.wave64) + } else { + Vec::new() + } } /// Operations that cannot be split into two independent native wave32 halves while @@ -1407,15 +1438,19 @@ pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> { 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 + // a VS / PS: its whole-wave reductions as wave operations, at any wave size (`reductions`) + let reductions = graphics_reductions(&insts, opt); + let reduced: BTreeSet<u64> = reductions.iter().flat_map(|r| r.rest.iter().copied()).collect(); + // a wave64 VS / PS on a GPU with 32-lane waves only: 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 + // program with a read to change – outside the reductions – gets the form if opt.wave64 && opt.split_wave64 && matches!(opt.mode, Mode::Vertex(_) | Mode::Pixel(_)) { let a = upper_lanes::analyze(&insts); - if a.reads.values().any(|r| matches!(r, upper_lanes::Read::Const(_) | upper_lanes::Read::Shadow)) { + if a.reads.iter().any(|(pc, r)| !reduced.contains(pc) && matches!(r, upper_lanes::Read::Const(_) | upper_lanes::Read::Shadow)) { em.upper = Some(a); } } + em.set_reductions(reductions); em.max_vgpr = insts .iter() .flat_map(|d| { diff --git a/crates/xcl/src/gpu/recomp/reductions.rs b/crates/xcl/src/gpu/recomp/reductions.rs new file mode 100644 index 0000000..bd37bce --- /dev/null +++ b/crates/xcl/src/gpu/recomp/reductions.rs @@ -0,0 +1,544 @@ +//! Whole-wave reductions of vertex / pixel shaders, recognised as a whole +//! (docs/wave64-on-wave32.md, "Whole-wave reductions"). +//! +//! The console's compiler makes a wave reduction – `WaveActiveMin` / `Max` / `BitOr` of a +//! uint, as far as the retail pack shows – into whole-wave code. In a wave64 program: +//! +//! ```text +//! s_or_saveexec_b64 s[S:S+1], -1 EXEC saved, every lane on +//! s_and_b64 s[M:M+1], s[L:L+1], s[S:S+1] the lanes that take part (L: the live pixels); +//! without it the mask is the saved EXEC (M = S) +//! v_cndmask_b32 vA, id, x, s[M:M+1] x in those lanes, the op's identity elsewhere +//! op_dpp8 vA, vA, vA three times, over 8 lanes: the other lane of the +//! pair, a lane of the other pair, of the other quad +//! op_dpp vA, vA, vA row_mirror over the row (16 lanes) +//! v_permlanex16_b32 vB, vA, 0, 0 the other row of the 32-lane half +//! op vA, vB, vA over the half +//! v_readlane_b32 sH, vA, 32 the upper half's +//! op vA, sH, vA lanes 0..31: over the wave +//! v_readlane_b32 sT, vA, 0 the wave's +//! s_mov_b64 exec, s[S:S+1] +//! ``` +//! +//! A wave32 program has the same up to `op vA, vB, vA` (the wave, then), with the 32-bit +//! forms (`s_or_saveexec_b32`, `s_and_b32`, a mask in one SGPR), then `v_readlane_b32 sT, vA, +//! 0` and `s_mov_b32 exec_lo, sS`. The op is min_u32 (identity -1), max_u32 (0) or or_b32 (0); +//! `s_waitcnt` / `s_nop` / `v_nop` may stand anywhere between. +//! +//! On the console all lanes of the wave run it, inactive ones included. The PC runs only the +//! lanes it launched, and in a partial wave – a primitive's edge, the last vertices of a draw +//! – the DPP / `v_permlanex16` / `v_readlane` steps read lanes that do not exist: 0 on NVIDIA, +//! so a min gave 0 there. A wave64 program in 32-lane waves never has lanes 32..63. +//! +//! Lanes the PC did not launch hold the identity on the console: the mask is within the saved +//! EXEC, and EXEC outside whole-wave code holds only lanes the program was started with (as the +//! program uses it). So each value the sequence leaves is the op over the mask's lanes of a +//! part of the wave, which wave operations give at any wave size: per 16-lane row k, +//! `WaveActiveMin(row == k ? q : id)` with q the lane's x if it is in the mask, the identity +//! if not; the halves and the wave from the rows. Every register the steps write gets what the +//! console leaves there: vA the wave's result (wave64: in lanes 0..31, the upper half's in +//! 32..63), vB the other row's of its half, sH and sT. A wave operation leaves out helper +//! lanes, which a mask taken from EXEC after `s_wqm` holds: in a pixel shader q is first the op +//! over the lane's quad (quad reads see helper lanes), as in the console's 2 × 2 steps. +//! +//! Only an exactly matched sequence is replaced; the SALU instructions around it stay as they +//! are. The emitter (`Em::reduction`) uses this for VS / PS at any wave size, so it also +//! changes the HLSL GPUs with 64-lane waves get for those programs. + +use std::collections::BTreeSet; + +use super::emit::ext_encoding; +use crate::gpu::rdna2::{self, Decoded, Variant}; + +/// The reduction's operation. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub enum Op { + MinU32, + MaxU32, + OrB32, +} + +impl Op { + fn of(name: &str) -> Option<Op> { + Some(match name { + "V_MIN_U32" => Op::MinU32, + "V_MAX_U32" => Op::MaxU32, + "V_OR_B32" => Op::OrB32, + _ => return None, + }) + } + + /// The value that leaves the other operand unchanged. + pub fn identity(self) -> u32 { + match self { + Op::MinU32 => u32::MAX, + Op::MaxU32 | Op::OrB32 => 0, + } + } + + pub fn name(self) -> &'static str { + match self { + Op::MinU32 => "min_u32", + Op::MaxU32 => "max_u32", + Op::OrB32 => "or_b32", + } + } + + /// The HLSL wave operation. + pub fn wave(self) -> &'static str { + match self { + Op::MinU32 => "WaveActiveMin", + Op::MaxU32 => "WaveActiveMax", + Op::OrB32 => "WaveActiveBitOr", + } + } + + /// `a op b` in HLSL. + pub fn hlsl(self, a: &str, b: &str) -> String { + match self { + Op::MinU32 => format!("min({a}, {b})"), + Op::MaxU32 => format!("max({a}, {b})"), + Op::OrB32 => format!("({a} | {b})"), + } + } + + /// The op on two values (tests, census). + pub fn apply(self, a: u32, b: u32) -> u32 { + match self { + Op::MinU32 => a.min(b), + Op::MaxU32 => a.max(b), + Op::OrB32 => a | b, + } + } +} + +/// A recognised reduction: what the emitter needs to replace it. +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct Reduction { + pub op: Op, + /// the 64-bit forms (a wave64 program) + pub wave64: bool, + /// the `v_cndmask_b32`: the reduction is emitted there + pub at: u64, + /// the instructions after it, up to the last `v_readlane_b32`: emitted as nothing + pub rest: Vec<u64>, + /// x, the `v_cndmask`'s SRC1 (operand code: 256 + n for vN), and the instruction's literal + pub x: u64, + pub literal: Option<u32>, + /// the mask: its (first) SGPR + pub mask: u64, + /// vA (the steps' register), vB (`v_permlanex16`'s) + pub acc: u64, + pub other: u64, + /// sH (`v_readlane` 32, wave64 only), sT (`v_readlane` 0) + pub half: Option<u64>, + pub total: u64, +} + +/// No effect in the translation (`emit::NOOPS`): may stand anywhere in the sequence. +fn skipped(d: &Decoded) -> bool { + matches!(d.inst.name, "S_NOP" | "V_NOP") || d.inst.name.starts_with("S_WAITCNT") +} + +/// An integer constant source (inline or literal). +fn constant(code: u64, literal: Option<u32>) -> Option<u32> { + Some(match code { + 128..=192 => (code - 128) as u32, + 193..=208 => (-((code - 192) as i32)) as u32, + 255 => literal?, + _ => return None, + }) +} + +/// A mask register the translation names: an SGPR pair (s0..s105, VCC) for a wave64 +/// program, an SGPR (s0..s105, VCC's words) for a wave32 one. +fn mask_register(r: u64, wave64: bool) -> bool { + if wave64 { + r <= 104 || r == 106 + } else { + r <= 107 + } +} + +/// A single SGPR the translation names (s0..s105, VCC's words). +fn sgpr(r: u64) -> bool { + r <= 107 +} + +/// The next instruction from `insts[*j]` on that does something; `*j` past it. +fn next<'a>(insts: &'a [Decoded], j: &mut usize) -> Result<&'a Decoded, &'static str> { + while let Some(d) = insts.get(*j) { + *j += 1; + if !skipped(d) { + return Ok(d); + } + } + Err("the program ends") +} + +/// The whole-wave section that starts at `insts[i]` as a reduction, or why it is not one +/// this recognises. `targets`: every branch target of the program. +pub fn at(insts: &[Decoded], i: usize, targets: &BTreeSet<u64>) -> Result<Reduction, &'static str> { + let fv = |d: &Decoded, f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let ext = |d: &Decoded, f: &str| ext_encoding(d).and_then(|e| rdna2::field_value(e, &d.words, f)).unwrap_or(0); + // a VOP3 instruction without source / output modifiers + let plain3 = |d: &Decoded| d.enc.name == "ENC_VOP3" && d.variant == Variant::Plain && ["ABS", "NEG", "CLAMP", "OMOD"].iter().all(|f| fv(d, f) == 0); + let d0 = insts.get(i).ok_or("no instruction")?; + let wave64 = match d0.inst.name { + "S_OR_SAVEEXEC_B64" if fv(d0, "SSRC0") == 193 => true, + "S_OR_SAVEEXEC_B32" if fv(d0, "SSRC0") == 193 => false, + _ => return Err("not s_or_saveexec s, -1"), + }; + let saved = fv(d0, "SDST"); + if !mask_register(saved, wave64) { + return Err("EXEC saved to an unusual register"); + } + let mut j = i + 1; + let mut step = || next(insts, &mut j); + let mut d = step()?; + let and = if wave64 { "S_AND_B64" } else { "S_AND_B32" }; + let mask = if d.inst.name == and { + if fv(d, "SSRC0") != saved && fv(d, "SSRC1") != saved { + return Err("s_and without the saved EXEC"); + } + let m = fv(d, "SDST"); + if !mask_register(m, wave64) { + return Err("the mask in an unusual register"); + } + d = step()?; + m + } else { + saved + }; + // x in the mask's lanes, a constant elsewhere + if d.inst.name != "V_CNDMASK_B32" || !plain3(d) || fv(d, "SRC2") != mask { + return Err("no v_cndmask_b32 of the mask"); + } + let id = constant(fv(d, "SRC0"), d.literal).ok_or("v_cndmask_b32: no constant outside the mask")?; + let x = fv(d, "SRC1"); + if !matches!(x, 0..=107 | 128..=208 | 240..=248 | 255 | 256..=511) { + return Err("v_cndmask_b32: an unusual source"); + } + let (acc, at, literal) = (fv(d, "VDST"), d.pc, d.literal); + // the row: DPP8 steps, then row_mirror. The op is idempotent, so each lane holds the op + // over the lanes it has read so far (bit l of `read[lane]`); every lane must end with its + // whole row – whichever DPP8 selects do it (the pack's read one lane of the other pair, + // then of the other quad, of lanes that hold the same by then). + let mut read: [u16; 16] = std::array::from_fn(|l| 1 << l); + let mut op = None; + let mut d = step()?; + while d.variant == Variant::Dpp8 { + let o = Op::of(d.inst.name).ok_or("the steps are not v_min_u32 / v_max_u32 / v_or_b32")?; + if *op.get_or_insert(o) != o { + return Err("steps of different ops"); + } + if d.enc.name != "ENC_VOP2" || fv(d, "VDST") != acc || ext(d, "VSRC0") != acc || fv(d, "VSRC1") != acc { + return Err("a DPP8 step of another register"); + } + // every lane is active: FI does not matter + let sel: [usize; 8] = std::array::from_fn(|k| ext(d, &format!("LANE_SEL_{k}")) as usize); + read = std::array::from_fn(|l| read[l] | read[(l & 8) | sel[l & 7]]); + d = step()?; + } + let op = op.ok_or("no DPP8 step after the v_cndmask_b32")?; + if id != op.identity() { + return Err("the constant outside the mask is not the op's identity"); + } + if Op::of(d.inst.name) != Some(op) || d.variant != Variant::Dpp16 || d.enc.name != "ENC_VOP2" { + return Err("no row_mirror step"); + } + let mods = ["SRC0_ABS", "SRC0_NEG", "SRC1_ABS", "SRC1_NEG"].iter().any(|f| ext(d, f) != 0); + if ext(d, "DPP_CTRL") != 0x140 || ext(d, "ROW_MASK") != 0xF || ext(d, "BANK_MASK") != 0xF || mods { + return Err("a DPP16 step other than row_mirror of all lanes"); + } + if fv(d, "VDST") != acc || ext(d, "VSRC0") != acc || fv(d, "VSRC1") != acc { + return Err("the row_mirror step of another register"); + } + read = std::array::from_fn(|l| read[l] | read[15 - l]); + if read.iter().any(|&r| r != 0xFFFF) { + return Err("the DPP8 steps and row_mirror leave out lanes of the row"); + } + // the other row of the half: every lane of it holds the row's value, so whichever lane + // the selects pick (and FI / bound_ctrl only matter for inactive lanes: none here) + let d = step()?; + if d.inst.name != "V_PERMLANEX16_B32" || !plain3(d) || fv(d, "SRC0") != 256 + acc || fv(d, "SRC1") >= 256 || fv(d, "SRC2") >= 256 { + return Err("no v_permlanex16_b32 of the row's value"); + } + let other = fv(d, "VDST"); + if other == acc { + return Err("v_permlanex16_b32 into the steps' register"); + } + // the half + let d = step()?; + let (s0, s1) = (fv(d, "SRC0"), fv(d, "VSRC1")); + if Op::of(d.inst.name) != Some(op) || d.enc.name != "ENC_VOP2" || d.variant != Variant::Plain || fv(d, "VDST") != acc || !((s0 == 256 + other && s1 == acc) || (s0 == 256 + acc && s1 == other)) { + return Err("no op of the two rows"); + } + // wave64: the upper half's, then the wave's in lanes 0..31 + let mut d = step()?; + let half = if wave64 { + if d.inst.name != "V_READLANE_B32" || !plain3(d) || fv(d, "SRC0") != 256 + acc || fv(d, "SRC1") != 128 + 32 || !sgpr(fv(d, "VDST")) { + return Err("no v_readlane_b32 of lane 32"); + } + let half = fv(d, "VDST"); + let d = step()?; + if Op::of(d.inst.name) != Some(op) || d.enc.name != "ENC_VOP2" || d.variant != Variant::Plain || fv(d, "VDST") != acc || fv(d, "SRC0") != half || fv(d, "VSRC1") != acc { + return Err("no op of the upper half's value"); + } + Some(half) + } else { + None + }; + if wave64 { + d = step()?; + } + if d.inst.name != "V_READLANE_B32" || !plain3(d) || fv(d, "SRC0") != 256 + acc || fv(d, "SRC1") != 128 || !sgpr(fv(d, "VDST")) { + return Err("no v_readlane_b32 of lane 0"); + } + let total = fv(d, "VDST"); + let last = d.pc; + let d = step()?; + let restore = if wave64 { "S_MOV_B64" } else { "S_MOV_B32" }; + if d.inst.name != restore || fv(d, "SDST") != 126 || fv(d, "SSRC0") != saved { + return Err("EXEC not restored after the v_readlane_b32 of lane 0"); + } + // entered only at the top: no branch lands after the s_or_saveexec + if targets.range(d0.pc + 1..=d.pc).next().is_some() { + return Err("a branch into the sequence"); + } + let rest = insts.iter().map(|d| d.pc).filter(|&pc| pc > at && pc <= last).collect(); + Ok(Reduction { op, wave64, at, rest, x, literal, mask, acc, other, half, total }) +} + +/// Every branch target of a program. +fn targets(insts: &[Decoded]) -> BTreeSet<u64> { + insts.iter().filter_map(rdna2::branch_target).collect() +} + +/// Every whole-wave section (`s_or_saveexec_b64` / `_b32` with -1) of a program: its pc, and +/// the reduction or why it is not one this recognises (the census). +pub fn survey(insts: &[Decoded]) -> Vec<(u64, Result<Reduction, &'static str>)> { + let t = targets(insts); + insts + .iter() + .enumerate() + .filter(|(_, d)| matches!(d.inst.name, "S_OR_SAVEEXEC_B64" | "S_OR_SAVEEXEC_B32") && rdna2::field_value(d.enc, &d.words, "SSRC0") == Some(193)) + .map(|(i, d)| (d.pc, at(insts, i, &t))) + .collect() +} + +/// The reductions of a program (instructions in address order, far jumps resolved) in the +/// forms of its wave size. +pub fn find(insts: &[Decoded], wave64: bool) -> Vec<Reduction> { + survey(insts).into_iter().filter_map(|(_, r)| r.ok()).filter(|r| r.wave64 == wave64).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::rdna2::encode; + + const V: u64 = 256; + type F = Vec<(&'static str, u64)>; + type I = (&'static str, &'static str, F, Option<u32>); + + fn program(lines: &[I]) -> Vec<Decoded> { + let mut bytes: Vec<u8> = lines.iter().flat_map(|(n, e, f, l)| encode(n, e, f, *l).unwrap_or_else(|x| panic!("{n}: {x}"))).collect(); + bytes.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + 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 i(n: &'static str, e: &'static str, f: &[(&'static str, u64)]) -> I { + (n, e, f.to_vec(), None) + } + + /// A DPP8 step of op on v6: lane l reads lane `sel[l]` of its 8. + fn dpp8(op: &'static str, sel: [u64; 8]) -> I { + let mut f = vec![("VDST", 6), ("SRC0", 0xE9), ("VSRC0", 6), ("VSRC1", 6)]; + let names = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"]; + f.extend(names.iter().copied().zip(sel)); + (op, "VOP2_VOP_DPP8", f, None) + } + + /// lane ^ k + fn xor(k: u64) -> [u64; 8] { + std::array::from_fn(|l| l as u64 ^ k) + } + + /// The pack's DPP8 steps: the other lane of the pair, a lane of the other pair, of the + /// other quad + const PACK: [[u64; 8]; 3] = [[1, 0, 3, 2, 5, 4, 7, 6], [2, 2, 0, 0, 6, 6, 4, 4], [4, 4, 4, 4, 0, 0, 0, 0]]; + + /// The pack's sequence: op (by name) over v55 in the lanes of s[18:19] & EXEC, identity + /// operand code `id`, the upper half's into s10 and the wave's into s61. + fn retail(op: &'static str, id: u64) -> Vec<I> { + vec![ + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)]), + i("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 18), ("SSRC1", 30)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", id), ("SRC1", V + 55), ("SRC2", 10)]), + dpp8(op, PACK[0]), + dpp8(op, PACK[1]), + dpp8(op, PACK[2]), + i(op, "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x140), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)]), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 128), ("SRC2", 128)]), + i(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 7), ("VSRC1", 6)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 32)]), + i(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", 10), ("VSRC1", 6)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 61), ("SRC0", V + 6), ("SRC1", 128)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)]), + ] + } + + fn survey_of(lines: &[I]) -> Vec<Result<Reduction, &'static str>> { + survey(&program(lines)).into_iter().map(|(_, r)| r).collect() + } + + fn reason(lines: &[I]) -> &'static str { + let s = survey_of(lines); + assert_eq!(s.len(), 1); + s[0].clone().expect_err("recognised") + } + + #[test] + fn the_retail_sequences_are_recognised() { + for (op, id, want) in [("V_MIN_U32", 193, Op::MinU32), ("V_MAX_U32", 128, Op::MaxU32), ("V_OR_B32", 128, Op::OrB32)] { + let p = program(&retail(op, id)); + let r = find(&p, true); + assert_eq!(r.len(), 1, "{op}"); + let r = &r[0]; + assert_eq!((r.op, r.x, r.mask, r.acc, r.other, r.half, r.total), (want, V + 55, 10, 6, 7, Some(10), 61)); + // emitted at the v_cndmask, nothing for the steps up to the last v_readlane + assert_eq!(r.at, p[2].pc); + assert_eq!(r.rest, p[3..12].iter().map(|d| d.pc).collect::<Vec<_>>()); + } + } + + #[test] + fn variants_of_the_pack() { + // the mask is the saved EXEC itself (16 sites in the pack) + let mut l = retail("V_OR_B32", 128); + l.remove(1); + l[1].2[3] = ("SRC2", 30); + let r = find(&program(&l), true); + assert_eq!(r.iter().map(|r| r.mask).collect::<Vec<_>>(), [30]); + // s_waitcnt / v_nop between the steps; the saved EXEC as s_and_b64's first operand; + // the halves' op with its operands swapped; both v_readlane into one register + let mut l = retail("V_MAX_U32", 128); + l.insert(1, i("V_NOP", "ENC_VOP1", &[])); + l.insert(3, i("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0x3F70)])); + l[2] = i("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 30), ("SSRC1", 18)]); + l[10] = i("V_MAX_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 6), ("VSRC1", 7)]); + l[13].2[0] = ("VDST", 10); + let r = find(&program(&l), true); + assert_eq!(r.iter().map(|r| (r.op, r.half, r.total)).collect::<Vec<_>>(), [(Op::MaxU32, Some(10), 10)]); + // other DPP8 steps that take in the 8 lanes: lane ^ 4, ^ 1, ^ 2; ^ 1, ^ 3, ^ 7; four + // steps, one of them reading the lane itself + for steps in [vec![xor(4), xor(1), xor(2)], vec![xor(1), xor(3), xor(7)], vec![xor(1), xor(0), xor(2), xor(4)]] { + let mut l = retail("V_MIN_U32", 193); + l.splice(3..6, steps.iter().map(|&sel| dpp8("V_MIN_U32", sel))); + assert_eq!(find(&program(&l), true).len(), 1, "{steps:?}"); + } + } + + #[test] + fn anything_else_is_left_alone() { + let base = retail("V_MIN_U32", 193); + let with = |k: usize, d: I| { + let mut l = base.clone(); + l[k] = d; + l + }; + let short = "the DPP8 steps and row_mirror leave out lanes of the row"; + // not the identity outside the mask: max's 0 for a min + assert_eq!(reason(&with(2, i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 128), ("SRC1", V + 55), ("SRC2", 10)]))), "the constant outside the mask is not the op's identity"); + // a mask not within the saved EXEC: lanes the PC did not launch could be in it + assert_eq!(reason(&with(1, i("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 18), ("SSRC1", 20)]))), "s_and without the saved EXEC"); + // the v_cndmask selects by another register than the mask + assert_eq!(reason(&with(2, i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 193), ("SRC1", V + 55), ("SRC2", 18)]))), "no v_cndmask_b32 of the mask"); + // a step of another op + assert_eq!(reason(&with(4, dpp8("V_MAX_U32", PACK[1]))), "steps of different ops"); + // steps that leave lanes out: the pack's in another order (they read one lane of a + // pair or quad, which holds the same as the other only after the steps before), the + // other lane of the pair twice, a rotation, two steps + let mut l = base.clone(); + l.swap(3, 5); + assert_eq!(reason(&l), short); + assert_eq!(reason(&with(4, dpp8("V_MIN_U32", PACK[0]))), short); + assert_eq!(reason(&with(4, dpp8("V_MIN_U32", [1, 2, 3, 4, 5, 6, 7, 0]))), short); + let mut l = base.clone(); + l.remove(5); + assert_eq!(reason(&l), short); + // no DPP8 step at all; a shift or a row mask instead of the whole mirror + let mut l = base.clone(); + l.drain(3..6); + assert_eq!(reason(&l), "no DPP8 step after the v_cndmask_b32"); + let shr = with(6, i("V_MIN_U32", "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x111), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)])); + assert_eq!(reason(&shr), "a DPP16 step other than row_mirror of all lanes"); + let rows = with(6, i("V_MIN_U32", "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x140), ("ROW_MASK", 0x5), ("BANK_MASK", 0xF)])); + assert_eq!(reason(&rows), "a DPP16 step other than row_mirror of all lanes"); + // v_permlane16 (same row) instead of v_permlanex16 + assert_eq!(reason(&with(7, i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 128), ("SRC2", 128)]))), "no v_permlanex16_b32 of the row's value"); + // another lane than 32, then than 0 + assert_eq!(reason(&with(9, i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 16)]))), "no v_readlane_b32 of lane 32"); + assert_eq!(reason(&with(11, i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 61), ("SRC0", V + 6), ("SRC1", 128 + 1)]))), "no v_readlane_b32 of lane 0"); + // the halves' op reads another register than the readlane's + assert_eq!(reason(&with(10, i("V_MIN_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 11), ("VSRC1", 6)]))), "no op of the upper half's value"); + // something else under the whole wave before the restore + let mut l = base.clone(); + l.insert(12, i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)])); + assert_eq!(reason(&l), "EXEC not restored after the v_readlane_b32 of lane 0"); + // a branch into the middle (to the third DPP8 step) + let mut l = vec![i("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 8)])]; + l.extend(base.iter().cloned()); + assert_eq!(reason(&l), "a branch into the sequence"); + // the branch to the s_or_saveexec itself is fine + let mut l = vec![i("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 0)])]; + l.extend(base.iter().cloned()); + assert_eq!(find(&program(&l), true).len(), 1); + // the 64-bit forms in a wave32 program (`find` by the program's wave size) + assert!(find(&program(&base), false).is_empty()); + } + + /// The pack's wave32 sequence: the 32-bit forms, no v_readlane of lane 32. + fn retail32(op: &'static str, id: u64) -> Vec<I> { + let mut l = retail(op, id); + l[0] = i("S_OR_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)]); + l[1] = i("S_AND_B32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 18), ("SSRC1", 30)]); + l.drain(9..11); + l[10] = i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)]); + l + } + + #[test] + fn the_wave32_sequences_are_recognised() { + for (op, id, want) in [("V_MIN_U32", 193, Op::MinU32), ("V_MAX_U32", 128, Op::MaxU32), ("V_OR_B32", 128, Op::OrB32)] { + let p = program(&retail32(op, id)); + assert!(find(&p, true).is_empty(), "{op}: wave32 forms in a wave64 program"); + let r = find(&p, false); + assert_eq!(r.len(), 1, "{op}"); + let r = &r[0]; + assert_eq!((r.op, r.wave64, r.x, r.mask, r.acc, r.other, r.half, r.total), (want, false, V + 55, 10, 6, 7, None, 61)); + assert_eq!(r.rest, p[3..10].iter().map(|d| d.pc).collect::<Vec<_>>()); + } + // the mask is the saved EXEC itself + let mut l = retail32("V_MIN_U32", 193); + l.remove(1); + l[1].2[3] = ("SRC2", 30); + assert_eq!(find(&program(&l), false).iter().map(|r| r.mask).collect::<Vec<_>>(), [30]); + // a wave64 restore, a v_readlane of lane 32 (the upper half's: no such lane) + let mut l = retail32("V_MIN_U32", 193); + l[10] = i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)]); + assert_eq!(reason(&l), "EXEC not restored after the v_readlane_b32 of lane 0"); + let mut l = retail32("V_MIN_U32", 193); + l[9].2[2] = ("SRC1", 128 + 32); + assert_eq!(reason(&l), "no v_readlane_b32 of lane 0"); + } +} diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 7ebe475..4f39826 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -859,6 +859,19 @@ unsafe fn bind_views(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, textu Ok(keep) } +/// The command queue and fence `draw_on_multi` submits with, for one device at a time. +struct DrawQueue { + dev: usize, + queue: ID3D12CommandQueue, + fence: ID3D12Fence, + value: u64, +} + +// D3D12 objects are free-threaded; access is serialised by the mutex. +unsafe impl Send for DrawQueue {} + +static DRAW_QUEUE: Mutex<Option<DrawQueue>> = Mutex::new(None); + /// Several draws with one pipeline in one command list: each draw gets its own user data /// (u0 – e.g. a different descriptor table pointer) and scissor; textures and samplers in /// the directly indexed heaps (see `ViewTexture`). Otherwise as `draw_on`. @@ -877,9 +890,20 @@ pub fn draw_on_multi( clear: [f32; 4], ) -> Result<Vec<[f32; 4]>, String> { unsafe { - 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)?; + // one queue and fence per device for all draws, not one per draw: once a test has + // brought up the D3D12.X backend (`hle::d3d12x::real::init`) its hooks are on the + // device this process gets for the adapter, and the queues made through them were + // not given back – a run with many draws ended in E_OUTOFMEMORY at CreateCommandQueue + let mut cached = DRAW_QUEUE.lock().unwrap(); + if cached.as_ref().is_none_or(|c| c.dev != dev.as_raw() as usize) { + 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)?; + *cached = Some(DrawQueue { dev: dev.as_raw() as usize, queue, fence, value: 0 }); + } + let dq = cached.as_mut().unwrap(); + dq.value += 1; + let (queue, fence, value) = (dq.queue.clone(), dq.fence.clone(), dq.value); let tex = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, @@ -982,7 +1006,7 @@ pub fn draw_on_multi( list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); list.Close().map_err(werr)?; queue.ExecuteCommandLists(&[Some(list.cast().map_err(werr)?)]); - wait_for_submission(dev, &queue, &fence, 1, "draw")?; + wait_for_submission(dev, &queue, &fence, value, "draw")?; let mut p = std::ptr::null_mut(); readback.Map(0, None, Some(&mut p)).map_err(werr)?; let pitch = layout_fp.Footprint.RowPitch as usize; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 7307c7d..e7c39d8 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2368,6 +2368,11 @@ fn draw_console(vs: Option<&[u8]>, ps: Option<&[u8]>, tris_px: &[[f32; 2]]) -> V draw_console_views(vs, ps, tris_px, &[], &[], &[]) } +/// `draw_console` with the programs translated as wave64 or wave32 programs. +fn draw_console_as(vs: Option<&[u8]>, ps: Option<&[u8]>, tris_px: &[[f32; 2]], wave64: bool) -> Vec<[f32; 4]> { + draw_console_views_as(vs, ps, tris_px, &[], &[], &[], wave64) +} + /// `draw_console` with initial SGPRs and textures / samplers (see `runner::ViewTexture`). fn draw_console_views( vs: Option<&[u8]>, @@ -2376,6 +2381,20 @@ fn draw_console_views( sgprs: &[u32], textures: &[runner::ViewTexture], samplers: &[windows::Win32::Graphics::Direct3D12::D3D12_SAMPLER_DESC], +) -> Vec<[f32; 4]> { + draw_console_views_as(vs, ps, tris_px, sgprs, textures, samplers, true) +} + +/// `draw_console_views` with the programs translated for a stated wave size. +#[allow(clippy::too_many_arguments)] +fn draw_console_views_as( + vs: Option<&[u8]>, + ps: Option<&[u8]>, + tris_px: &[[f32; 2]], + sgprs: &[u32], + textures: &[runner::ViewTexture], + samplers: &[windows::Win32::Graphics::Direct3D12::D3D12_SAMPLER_DESC], + wave64: bool, ) -> Vec<[f32; 4]> { use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32_FLOAT}; let pass_vs = prog(&[ @@ -2398,7 +2417,7 @@ fn draw_console_views( ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None), ]); let compile = |code: &[u8], mode: Mode, profile: &str| { - let t = translate(code, &runner::options(mode)).unwrap(); + let t = translate(code, &Options { wave64, ..runner::options(mode) }).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); super::dxc::compile(&t.hlsl, "main", profile, &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)) }; @@ -2645,44 +2664,62 @@ fn spill_slots(slot: fn(u32) -> u32) -> Vec<u8> { code } -/// The whole-wave reduction of the retail pixel shaders (`upper_lanes`), run as a wave64 PS: -/// identity into the lanes outside the mask, DPP8 xor 1 / 2 / 4, row_mirror, the other row -/// through `v_permlanex16`, `v_readlane` 32 for the upper half's result, `v_readlane` 0 for -/// the total – as min (identity -1, as in the pack) and as a sum (identity 0: wrong if lane -/// 32 is read as anything but the identity, e.g. as lane 0, where a 32-lane GPU's wave read -/// wraps). Over the odd pixels of each wave; also the waterfall read of the pack -/// (`v_readlane` of the lane `s_ff1` picks from mask & EXEC). The waves are found from the -/// pixels: each exports its wave's `v_readfirstlane` of the pixel number and its lane -/// (`v_mbcnt`), and the CPU computes what a console wave of those lanes gives. +/// The whole-wave reduction of the retail pixel shaders as the console's compiler emits it +/// (`reductions`): EXEC saved in s[30:31]; `op` over vX in the lanes of the saved EXEC – and of +/// s[and_with:+1], given – with `identity` elsewhere (v_cndmask), three DPP8 steps (the other +/// lane of the pair, a lane of the other pair, of the other quad: the pack's selects), +/// row_mirror, the other row through `v_permlanex16` (v7), `v_readlane` 32 for the upper +/// half's (s[half]), `v_readlane` 0 for the wave's (s[total]); v6 the steps' register. +fn whole_wave_reduction(op: &str, identity: u64, x: u64, and_with: Option<u64>, half: u64, total: u64) -> Vec<u8> { + whole_wave_reduction_as(true, op, identity, x, and_with, half, total) +} + +/// `whole_wave_reduction` in a wave64 program, or in a wave32 one: the 32-bit forms, no +/// upper half (s30 the saved EXEC, s[and_with] the mask, `half` unused). +fn whole_wave_reduction_as(wave64: bool, op: &str, identity: u64, x: u64, and_with: Option<u64>, half: u64, total: u64) -> Vec<u8> { + let w = |b64: &'static str, b32: &'static str| if wave64 { b64 } else { b32 }; + let mut c = vec![ins(w("S_OR_SAVEEXEC_B64", "S_OR_SAVEEXEC_B32"), "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)], None)]; + if let Some(s) = and_with { + c.push(ins(w("S_AND_B64", "S_AND_B32"), "ENC_SOP2", &[("SDST", 10), ("SSRC0", s), ("SSRC1", 30)], None)); + } + let mask = if and_with.is_some() { 10 } else { 30 }; + c.push(ins("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", identity), ("SRC1", V + x), ("SRC2", mask)], None)); + let names = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"]; + for sel in [[1u64, 0, 3, 2, 5, 4, 7, 6], [2, 2, 0, 0, 6, 6, 4, 4], [4, 4, 4, 4, 0, 0, 0, 0]] { + let mut f = vec![("VDST", 6u64), ("SRC0", 0xE9), ("VSRC0", 6), ("VSRC1", 6)]; + f.extend(names.iter().copied().zip(sel)); + c.push(ins(op, "VOP2_VOP_DPP8", &f, None)); + } + c.extend([ + ins(op, "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x140), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None), + ins("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 128), ("SRC2", 128)], None), + ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 7), ("VSRC1", 6)], None), + ]); + if wave64 { + c.push(ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", half), ("SRC0", V + 6), ("SRC1", 128 + 32)], None)); + c.push(ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", half), ("VSRC1", 6)], None)); + } + c.push(ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", total), ("SRC0", V + 6), ("SRC1", 128)], None)); + c.push(ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)], None)); + c.concat() +} + +/// The whole-wave reduction of the retail pixel shaders (`whole_wave_reduction`), run as a +/// wave64 PS in full waves – as min (identity -1, as in the pack: replaced with wave +/// operations, `reductions`) and as a sum (identity 0: its steps stay, and lane 32 is read as +/// the identity in a 32-lane wave, `upper_lanes`; wrong if it were read as anything else, e.g. +/// as lane 0, where a 32-lane GPU's wave read wraps). Over the odd pixels of each wave; also +/// the waterfall read of the pack (`v_readlane` of the lane `s_ff1` picks from mask & EXEC). +/// The waves are found from the pixels: each exports its wave's `v_readfirstlane` of the pixel +/// number and its lane (`v_mbcnt`), and the CPU computes what a console wave of those lanes +/// gives. #[test] fn gpu_wave64_ps_whole_wave_reductions() { use std::collections::{BTreeMap, BTreeSet}; if !gpu_ready() { return; } - let reduce = |op: &str, identity: u64, out: u64| -> Vec<u8> { - let mut c = vec![ - ins("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)], None), - ins("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 18), ("SSRC1", 30)], None), - ins("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", identity), ("SRC1", V + 13), ("SRC2", 10)], None), - ]; - let names = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"]; - for sel in [[1u64, 0, 3, 2, 5, 4, 7, 6], [2, 3, 0, 1, 6, 7, 4, 5], [4, 5, 6, 7, 0, 1, 2, 3]] { - let mut f = vec![("VDST", 6u64), ("SRC0", 0xE9), ("VSRC0", 6), ("VSRC1", 6)]; - f.extend(names.iter().copied().zip(sel)); - c.push(ins(op, "VOP2_VOP_DPP8", &f, None)); - } - c.extend([ - ins(op, "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x140), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None), - ins("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 128), ("SRC2", 128)], None), - ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 7), ("VSRC1", 6)], None), - ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 32)], None), - ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", 10), ("VSRC1", 6)], None), - ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", out), ("SRC0", V + 6), ("SRC1", 128)], None), - ins("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)], None), - ]); - c.concat() - }; + let reduce = |op: &str, identity: u64, out: u64| whole_wave_reduction(op, identity, 13, Some(18), 10, out); let code = program_of(&[ // v12 = pixel number y·16 + x, v13 = v12 + 1, s[18:19] = the odd pixels ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)], None), @@ -2975,6 +3012,227 @@ fn gpu_ps_helper_lanes_see_ballots_and_quads_are_lanes_4k() { assert_eq!(quads, px.len(), "quads not at hardware lanes 4k..4k+3"); } +/// The three reductions of the pack (`reductions`): instruction, identity operand code, op. +const WAVE_REDUCTIONS: [(&str, u64, super::reductions::Op); 3] = [ + ("V_MIN_U32", 193, super::reductions::Op::MinU32), + ("V_MAX_U32", 128, super::reductions::Op::MaxU32), + ("V_OR_B32", 128, super::reductions::Op::OrB32), +]; + +/// The translation of recognised reductions (`reductions`, `Em::reduction`) in every VS / PS +/// form: wave operations instead of the steps (no lane read left), quad reads in a pixel +/// shader only, the halves of a 64-lane wave for wave32 programs, the same HLSL whether or not +/// the GPU has 64-lane waves (`split_wave64`); it compiles (DXC, where there is one). +#[test] +fn whole_wave_reductions_translate_to_wave_operations() { + for wave64 in [true, false] { + for pixel in [true, false] { + let mut parts: Vec<Vec<u8>> = WAVE_REDUCTIONS.iter().map(|(op, id, _)| whole_wave_reduction_as(wave64, op, *id, 13, Some(18), 40, 41)).collect(); + let (mode, profile) = if pixel { + parts.push(ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 6), ("VSRC1", 7), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); + (Mode::Pixel(draw_psi()), "ps_6_6") + } else { + parts.push(ins("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 6), ("VSRC1", 7), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1)], None)); + parts.push(ins("EXP", "ENC_EXP", &[("TGT", 32), ("EN", 0xF), ("VSRC0", 6), ("VSRC1", 7), ("VSRC2", 6), ("VSRC3", 7)], None)); + (Mode::Vertex(draw_vsi()), "vs_6_6") + }; + let code = program_of(&parts); + let what = format!("wave64 {wave64}, {profile}"); + let native = translate(&code, &Options { mode: mode.clone(), wave64, ..Default::default() }).unwrap(); + let split = translate(&code, &Options { mode, wave64, split_wave64: true, ..Default::default() }).unwrap(); + assert!(native.complete(), "{what}: {:?}", native.unsupported_why); + let h = &native.hlsl; + assert_eq!(h, &split.hlsl, "{what}: one form at every wave size"); + for op in ["min_u32", "max_u32", "or_b32"] { + assert_eq!(h.matches(&format!("xcl_wave_{op}(")).count(), 2, "{what}: the function and its call\n{h}"); + } + assert!(!h.contains(" = rla("), "{what}: a lane read left\n{h}"); + assert_eq!(h.contains("QuadReadLaneAt(x, 3u)"), pixel, "{what}: quad reads\n{h}"); + assert_eq!(h.contains("select(xcl_half != 0u, "), !wave64, "{what}: the halves\n{h}"); + if super::dxc::location().is_ok() { + super::dxc::compile(h, "main", profile, &[]).unwrap_or_else(|e| panic!("{what}: {e}\n{h}")); + } + } + } +} + +/// Whole-wave reductions (`reductions`) in full and partial pixel waves, of wave64 and of wave32 +/// programs: the pack's min, max and or of pixel number + 1, over the odd pixels (`s_and` of +/// the saved EXEC with the live pixels' mask, as in the pack) and over every lane of the wave's +/// quads (the saved EXEC after `s_wqm`, helper lanes included), drawn as the whole target, a +/// 3-quad triangle and a 55-pixel one. A pixel exports its console wave and lane and one of the +/// results for each op – the wave's (sT), the upper half's (sH, wave64), what the steps leave in +/// its lane (vA, vB) – which the CPU computes from the console wave's lanes, as on a console +/// wave whose other lanes are not populated. Each step translated on its own (before, +/// `XCL_NO_WAVE_REDUCTIONS=1`) reads the lanes the PC did not launch: 0 on NVIDIA, so the min +/// of a partial wave was 0 – and the or over the quads' lanes of 3 quads missed helper pixels. +#[test] +fn gpu_ps_partial_wave_reductions() { + use std::collections::BTreeMap; + if !gpu_ready() { + return; + } + const RESULTS: [&str; 4] = ["sT", "sH", "vA", "vB"]; + // `view`: which result a pixel exports (RESULTS) + let program = |wave64: bool, wqm: bool, view: usize| -> Vec<u8> { + let w = |b64: &'static str, b32: &'static str| if wave64 { b64 } else { b32 }; + let pixel = [ + ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)], None), + ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None), + ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 128 + 4), ("SRC2", V + 10)], None), + ]; + // v12 = pixel number y·16 + x; the console wave: its first lane's pixel number (s62), + // the lane (v15) + let mut c = pixel.to_vec(); + c.extend([ + ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 62), ("SRC0", V + 12)], None), + ins("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", 193), ("SRC1", 128)], None), + ins("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", 193), ("SRC1", V + 15)], None), + ]); + if wqm { + // live pixels in s[16:17], then the whole quads: the helper lanes' pixel numbers too + c.push(ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 16), ("SSRC0", 126)], None)); + c.push(ins(w("S_WQM_B64", "S_WQM_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None)); + c.extend(pixel.iter().cloned()); + } + // v13 = pixel number + 1, s[18:19] = the odd pixels + c.extend([ + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 129), ("VSRC1", 12)], None), + ins("V_AND_B32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 129), ("VSRC1", 12)], None), + ins("V_CMP_NE_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 14)], None), + ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 18), ("SSRC0", 106)], None), + ]); + // op k: sH in s[40 + 2k], sT in s[41 + 2k], vA / vB copied to v[20 + 2k] / v[21 + 2k] + for (k, (op, id, _)) in WAVE_REDUCTIONS.iter().enumerate() { + let k = k as u64; + c.push(whole_wave_reduction_as(wave64, op, *id, 13, (!wqm).then_some(18), 40 + 2 * k, 41 + 2 * k)); + c.push(ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 20 + 2 * k), ("SRC0", V + 6)], None)); + c.push(ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 21 + 2 * k), ("SRC0", V + 7)], None)); + } + if wqm { + c.push(ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 16)], None)); + } + for k in 0..3u64 { + let src = [41 + 2 * k, 40 + 2 * k, V + 20 + 2 * k, V + 21 + 2 * k][view]; + c.push(ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 30 + k), ("SRC0", src)], None)); + } + c.extend([ + ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 33), ("SRC0", 62), ("SRC1", 128 + 6), ("SRC2", V + 15)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 33), ("SRC0", V + 33)], None), + ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 30), ("VSRC1", 31), ("VSRC2", 32), ("VSRC3", 33), ("DONE", 1), ("VM", 1)], None), + ]); + program_of(&c) + }; + let shapes: [(&str, [[f32; 2]; 3]); 3] = [ + ("whole target", [[0.0, 0.0], [0.0, 32.0], [32.0, 0.0]]), + ("3 quads", [[0.0, 0.0], [3.2, 0.0], [0.0, 3.2]]), + ("55 pixels", [[0.0, 0.0], [11.0, 0.0], [0.0, 11.0]]), + ]; + let mut wave_sizes = BTreeMap::new(); + // wave size, shape, mask, op, result → (pixels wrong, the first: pixel, lane, got, want) + let mut wrong: BTreeMap<String, (usize, (u32, u32, u32, u32))> = BTreeMap::new(); + for wave64 in [true, false] { + let size = if wave64 { "wave64" } else { "wave32" }; + for (shape, tri) in &shapes { + for wqm in [false, true] { + let mask = if wqm { "the quads' lanes" } else { "the odd pixels" }; + for (view, what) in RESULTS.iter().enumerate() { + if view == 1 && !wave64 { + continue; + } + let px = draw_console_as(None, Some(&program(wave64, wqm, view)), tri, wave64); + // by console wave (its first lane's pixel number): (pixel number, lane, results) + let mut waves: BTreeMap<u32, Vec<(u32, u32, [f32; 4])>> = BTreeMap::new(); + for (id, p) in px.iter().enumerate().filter(|(_, p)| p[3] >= 0.0) { + let kl = p[3] as u32; + waves.entry(kl >> 6).or_default().push((id as u32, kl & 63, *p)); + } + assert!(!waves.is_empty(), "{size}, {shape}: nothing drawn"); + if view == 0 { + wave_sizes.insert((size, *shape, wqm), waves.values().map(|w| w.len()).collect::<Vec<_>>()); + } + for (first, w) in &waves { + // the lanes in the mask: (row = lane / 16, value) + let lanes: Vec<(u32, u32)> = if wqm { + // every lane of a quad with a live pixel; a quad keeps to one row + let quads: BTreeMap<(u32, u32), u32> = w.iter().map(|(id, lane, _)| ((id % 16 / 2, id / 16 / 2), lane >> 4)).collect(); + quads.iter().flat_map(|(&(qx, qy), &row)| [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(dx, dy)| (row, (2 * qy + dy) * 16 + 2 * qx + dx + 1))).collect() + } else { + w.iter().filter(|x| x.0 % 2 == 1).map(|(id, lane, _)| (lane >> 4, id + 1)).collect() + }; + for (o, (_, _, op)) in WAVE_REDUCTIONS.iter().enumerate() { + let rows: [u32; 4] = std::array::from_fn(|k| lanes.iter().filter(|l| l.0 == k as u32).fold(op.identity(), |a, l| op.apply(a, l.1))); + let half = op.apply(rows[2], rows[3]); + let wave = op.apply(op.apply(rows[0], rows[1]), half); + for (id, lane, p) in w { + let want = match view { + 0 => wave, + 1 => half, + 2 if *lane < 32 => wave, + 2 => half, + _ => rows[((lane >> 4) ^ 1) as usize], + }; + // u32 → f32 → u32: exact below 2^24; the identity -1 saturates back + let got = p[o] as u32; + if got != want { + let k = format!("{size}, {shape}, over {mask}: {} {what} (wave of pixel {first})", op.name()); + wrong.entry(k).or_insert((0, (*id, *lane, got, want))).0 += 1; + } + } + } + } + } + } + } + } + println!("pixels per console wave: {wave_sizes:?}"); + for (k, (n, (id, lane, got, want))) in &wrong { + println!("{k}: {n} pixels wrong, e.g. pixel {id} (lane {lane}): {got:#x}, want {want:#x}"); + } + assert!(wrong.is_empty(), "{} results wrong", wrong.len()); +} + +/// Whole-wave reductions (`reductions`) in a vertex wave of three lanes, of a wave64 and of a +/// wave32 program: min, max and or of vertex id + 1 over the saved EXEC, exported as param0 with +/// what v_permlanex16 leaves for the min (vB: the other row's – no lane there, so the +/// identity). The same at every vertex, so the interpolated value is exact. Before +/// (`XCL_NO_WAVE_REDUCTIONS=1`) the min and vB read lanes the PC did not launch: 0 on NVIDIA. +#[test] +fn gpu_vs_partial_wave_reductions() { + if !gpu_ready() { + return; + } + for wave64 in [true, false] { + // v13 = vertex id + 1 (the id is in v0), then the position and the reductions + let mut c = vec![ + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 129), ("VSRC1", 0)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V + 4)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V + 5)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 128)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 242)], None), + ]; + for (k, (op, id, _)) in WAVE_REDUCTIONS.iter().enumerate() { + c.push(whole_wave_reduction_as(wave64, op, *id, 13, None, 40 + 2 * k as u64, 41 + 2 * k as u64)); + if k == 0 { + c.push(ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 21), ("SRC0", V + 7)], None)); + } + } + c.extend([ + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 41)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 43)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 45)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 21)], None), + ins("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None), + ins("EXP", "ENC_EXP", &[("TGT", 32), ("EN", 0xF), ("VSRC0", 8), ("VSRC1", 9), ("VSRC2", 10), ("VSRC3", 11)], None), + ]); + let px = draw_console_as(Some(&program_of(&c)), None, &[[0.0, 0.0], [0.0, 32.0], [32.0, 0.0]], wave64); + println!("wave64 {wave64}: {:?}", px[0]); + for (i, p) in px.iter().enumerate() { + assert_eq!(p.map(|x| x as u32), [1, 3, 3, u32::MAX], "wave64 {wave64}, pixel {i}: min, max, or of vertex id + 1, vB of the min"); + } + } +} + /// XCL image descriptor (T#, GFX10 layout): BASE_ADDRESS = SRV heap index, FORMAT, TYPE. fn tsharp(index: u32, format: u32, ty: u32) -> [u32; 8] { [index, format << 20, 0, ty << 28, 0, 0, 0, 0] @@ -6143,10 +6401,12 @@ fn retail_wave64_graphics_lane_census() { } /// The 32-lane form of the pack's wave64 VS / PS (`upper_lanes`): every program whose -/// translation it changes is compiled with DXC. Digests of every program's translation in the -/// native form (`split_wave64` off – the form a GPU with 64-lane waves gets) and of the other -/// modes' 32-lane form are printed, to compare with another build: `XCL_SAMPLE_RPF`; -/// `XCL_FORMS_NO_DXC=1` skips the compiles. +/// translation it changes is compiled with DXC, and so is the native form of every VS / PS +/// with a whole-wave reduction recognised as a whole (`reductions`: it changes the form of +/// every GPU). Digests of every program's translation in the native form (`split_wave64` off +/// – the form a GPU with 64-lane waves gets) and of the other modes' 32-lane form are printed, +/// to compare with another build: `XCL_SAMPLE_RPF`; `XCL_FORMS_NO_DXC=1` skips the compiles; +/// `XCL_FORMS_LIST=<file>`: each program's digests, one line each (to diff two builds). #[test] #[ignore] fn retail_wave64_graphics_lane_forms() { @@ -6154,10 +6414,14 @@ fn retail_wave64_graphics_lane_forms() { use std::sync::Mutex; let Ok(path) = std::env::var("XCL_SAMPLE_RPF") else { return }; let dxc = std::env::var_os("XCL_FORMS_NO_DXC").is_none(); + let list_out = std::env::var("XCL_FORMS_LIST").ok(); let data = std::fs::read(path).unwrap(); let records = crate::gpu::pack::scan(&data, 0x40); let (digest, programs, changed, compiled) = (AtomicU64::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); let split_digest = AtomicU64::new(0); + // VS / PS with a recognised reduction, wave64 / wave32; their native forms compiled + let (reduced64, reduced32, reduced_compiled) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + let list: Mutex<Vec<String>> = Mutex::new(Vec::new()); let errors: Mutex<Vec<String>> = Mutex::new(Vec::new()); let next = AtomicUsize::new(0); std::thread::scope(|s| { @@ -6184,16 +6448,41 @@ fn retail_wave64_graphics_lane_forms() { Mode::Pixel(_) => "ps_6_6", _ => { // the other modes' 32-lane form: unchanged by `upper_lanes` + let mut sh = 0; if let Ok(t) = translate(code, &Options { split_wave64: true, ..opt }) { - split_digest.fetch_add(crate::gpu::shader::fnv64(format!("{key}\\n{}", t.hlsl).as_bytes()), Ordering::Relaxed); + sh = crate::gpu::shader::fnv64(format!("{key}\\n{}", t.hlsl).as_bytes()); + split_digest.fetch_add(sh, Ordering::Relaxed); + } + if list_out.is_some() { + list.lock().unwrap().push(format!("{key}\t{h:016x}\t{sh:016x}\t-")); } continue; } }; + // (the list's last column: whether the program has one) + let reduced = native.hlsl.contains("uint4 xcl_wave_"); + if reduced { + if wave64 { &reduced64 } else { &reduced32 }.fetch_add(1, Ordering::Relaxed); + if dxc { + match super::dxc::compile(&native.hlsl, "main", profile, &[]) { + Ok(_) => { + reduced_compiled.fetch_add(1, Ordering::Relaxed); + } + Err(e) => errors.lock().unwrap().push(format!("{key} (native): {}", e.lines().take(4).collect::<Vec<_>>().join(" | "))), + } + } + } if !wave64 { + if list_out.is_some() { + list.lock().unwrap().push(format!("{key}\t{h:016x}\t-\t{reduced}")); + } continue; } let t = translate(code, &Options { split_wave64: true, ..opt }).unwrap(); + if list_out.is_some() { + let sh = crate::gpu::shader::fnv64(format!("{key}\n{}", t.hlsl).as_bytes()); + list.lock().unwrap().push(format!("{key}\t{h:016x}\t{sh:016x}\t{reduced}")); + } if t.hlsl == native.hlsl { continue; } @@ -6213,20 +6502,134 @@ fn retail_wave64_graphics_lane_forms() { }); let errors = errors.into_inner().unwrap(); println!( - "{} programs, native-form digest {:016x}, 32-lane-form digest of the other modes {:016x}; 32-lane form differs for {} wave64 VS / PS, {} compiled, {} DXC errors", + "{} programs, native-form digest {:016x}, 32-lane-form digest of the other modes {:016x}; 32-lane form differs for {} wave64 VS / PS, {} compiled; whole-wave reductions as wave operations in {} wave64 and {} wave32 VS / PS, native form {} compiled; {} DXC errors", programs.into_inner(), digest.into_inner(), split_digest.into_inner(), changed.into_inner(), compiled.into_inner(), + reduced64.into_inner(), + reduced32.into_inner(), + reduced_compiled.into_inner(), errors.len() ); + if let Some(out) = list_out { + let mut v = list.into_inner().unwrap(); + v.sort(); + std::fs::write(out, v.join("\n") + "\n").unwrap(); + } for e in errors.iter().take(10) { println!(" {e}"); } assert!(errors.is_empty()); } +/// The pack's whole-wave sections (`s_or_saveexec_b64` / `_b32` with -1) and the reductions +/// `reductions` recognises in them: sites, programs and distinct programs (by code) per op, +/// and per reason for the sections it leaves – for wave64 VS / PS, where the translation uses +/// them, and for the other modes and wave sizes, where it does not. For wave64 VS / PS also the +/// programs with a lane ≥ 32 read as a constant (`upper_lanes`, #133), those whose such reads +/// are all inside recognised reductions, and those that still get the 32-lane form. +/// `XCL_SAMPLE_RPF`; `XCL_CENSUS_OUT=<file>`: the sections left, with their instructions. +#[test] +#[ignore] +fn retail_wave_reductions_census() { + use super::upper_lanes::Read; + use std::collections::{BTreeMap, BTreeSet}; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Mutex; + let Ok(path) = std::env::var("XCL_SAMPLE_RPF") else { return }; + let out = std::env::var("XCL_CENSUS_OUT").ok(); + let data = std::fs::read(path).unwrap(); + let records = crate::gpu::pack::scan(&data, 0x40); + // (programs, kind) → (sites, programs, distinct programs by code hash) + type Stats = BTreeMap<(String, String), (usize, usize, BTreeSet<u64>)>; + let stats: Mutex<Stats> = Mutex::new(BTreeMap::new()); + let left: Mutex<Vec<String>> = Mutex::new(Vec::new()); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..std::thread::available_parallelism().map_or(4, |n| n.get()) { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(r) = records.get(i) else { break }; + let Some(blob) = crate::gpu::pack::inflate(&data, r) else { continue }; + let Some(sh) = crate::gpu::xbox::parse(&blob) else { continue }; + for (fi, f) in sh.fssm.iter().enumerate() { + let label = match super::interface(&blob, &sh, f) { + Some(Mode::Vertex(_)) => "VS", + Some(Mode::Pixel(_)) => "PS", + Some(Mode::Compute(_)) => "CS", + Some(Mode::Mesh(_)) => "MS", + Some(Mode::Geometry(_)) => "GS", + _ => "other", + }; + for p in &f.programs { + let code = &f.data[p.offset..p.offset + p.len]; + let mut insts = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + let Ok(d) = crate::gpu::rdna2::decode(&code[off..], off as u64) else { break }; + off += d.len; + insts.push(d); + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + let sections = super::reductions::survey(&insts); + if sections.is_empty() { + continue; + } + let wave64 = super::detect_wave64(code); + let group = format!("{label} {}", if wave64 { "wave64" } else { "wave32" }); + let hash = crate::gpu::shader::fnv64(code); + let mut kinds = BTreeSet::from(["(programs with a whole-wave section)".to_string()]); + let mut st = stats.lock().unwrap(); + for (pc, res) in §ions { + let kind = match res { + Ok(r) => format!("recognised: {}", r.op.name()), + Err(e) => format!("left: {e}"), + }; + st.entry((group.clone(), kind.clone())).or_default().0 += 1; + if let (Err(e), Some(_)) = (res, &out) { + let lines = crate::gpu::rdna2::disassemble(code, 0, false); + let k = lines.iter().position(|l| l.pc == *pc).unwrap_or(0); + let text: Vec<String> = lines[k..(k + 16).min(lines.len())].iter().map(|l| format!(" {:05x}: {}", l.pc, l.text)).collect(); + left.lock().unwrap().push(format!("=== {group} {} FSSM#{fi} {hash:016x}: {e}\n{}\n", r.name, text.join("\n"))); + } + kinds.insert(kind); + } + if wave64 && matches!(label, "VS" | "PS") { + let a = super::upper_lanes::analyze(&insts); + let reduced: BTreeSet<u64> = sections.iter().filter_map(|(_, r)| r.as_ref().ok()).flat_map(|r| r.rest.iter().copied()).collect(); + let consts: Vec<u64> = a.reads.iter().filter(|(_, r)| matches!(r, Read::Const(_))).map(|(pc, _)| *pc).collect(); + if !consts.is_empty() { + kinds.insert("(programs with a lane >= 32 read as a constant, #133)".into()); + if consts.iter().all(|pc| reduced.contains(pc)) { + kinds.insert("(... all inside recognised reductions)".into()); + } + } + if a.reads.iter().any(|(pc, r)| !reduced.contains(pc) && matches!(r, Read::Const(_) | Read::Shadow)) { + kinds.insert("(programs that still get the 32-lane form)".into()); + } + } + for k in kinds { + let e = st.entry((group.clone(), k)).or_default(); + e.1 += 1; + e.2.insert(hash); + } + } + } + }); + } + }); + for ((group, kind), (sites, programs, distinct)) in stats.into_inner().unwrap() { + println!(" {group:<11} {kind:<62} {sites:>6} sites {programs:>6} programs {:>6} distinct", distinct.len()); + } + if let Some(out) = out { + let mut v = left.into_inner().unwrap(); + v.sort(); + std::fs::write(out, v.concat()).unwrap(); + } +} + /// `ds_swizzle_b32`'s four modes against the RDNA ISA (its FFT examples, rotate, quad /// permute, and the bit mode with xor ≥ 16, which retail compute shaders use to swap the /// 16-lane halves: 0x401F). @@ -8466,3 +8869,215 @@ fn dxc_bench_folder() { println!(" peak commit {} MB", c.PeakPagefileUsage >> 20); } } + +/// After a pixel shader's reduction, what the helper lanes of a quad hold (sT copied to a +/// VGPR, vA, vB), read by the live pixels through DPP quad_perm (the console: every lane holds +/// the result). +#[test] +fn gpu_ps_reduction_result_in_helper_lanes() { + if !gpu_ready() { + return; + } + let mut bad = 0; + for wave64 in [true, false] { + let w = |b64: &'static str, b32: &'static str| if wave64 { b64 } else { b32 }; + for (op, id, rop) in WAVE_REDUCTIONS.iter() { + for view in 0..3u64 { + // view 0: sT (as a VGPR), 1: vA, 2: vB + let mut c = vec![ + ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 16), ("SSRC0", 126)], None), + ins(w("S_WQM_B64", "S_WQM_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None), + ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)], None), + ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None), + ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 128 + 4), ("SRC2", V + 10)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 129), ("VSRC1", 12)], None), + ]; + c.push(whole_wave_reduction_as(wave64, op, *id, 13, Some(16), 40, 41)); + let src = [41, V + 6, V + 7][view as usize]; + c.extend([ + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 20), ("SRC0", src)], None), + ins("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 21), ("SRC0", 0xFA), ("VSRC0", 20), ("DPP_CTRL", 0xB1), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None), + ins("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 22), ("SRC0", 0xFA), ("VSRC0", 20), ("DPP_CTRL", 0x4E), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None), + ins("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 23), ("SRC0", 0xFA), ("VSRC0", 20), ("DPP_CTRL", 0x1B), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None), + ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 16)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 30), ("SRC0", V + 20)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 31), ("SRC0", V + 21)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 32), ("SRC0", V + 22)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 33), ("SRC0", V + 23)], None), + ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 30), ("VSRC1", 31), ("VSRC2", 32), ("VSRC3", 33), ("DONE", 1), ("VM", 1)], None), + ]); + let code = program_of(&c); + for (shape, tri) in [("3 quads", [[0.0f32, 0.0], [3.2, 0.0], [0.0, 3.2]]), ("55 pixels", [[0.0, 0.0], [11.0, 0.0], [0.0, 11.0]]), ("sliver", [[1.0, 1.0], [15.0, 2.2], [1.0, 2.2]])] { + let px = draw_console_as(None, Some(&code), &tri, wave64); + let live: Vec<(usize, [u32; 4])> = px.iter().enumerate().filter(|(_, p)| p[0] >= 0.0).map(|(i, p)| (i, p.map(|x| x as u32))).collect(); + let wrong: Vec<&(usize, [u32; 4])> = live.iter().filter(|(_, p)| p[1] != p[0] || p[2] != p[0] || p[3] != p[0]).collect(); + if !wrong.is_empty() { + bad += 1; + println!( + "wave64 {wave64} {} view {} {shape}: {} of {} live pixels see another value in their quad, e.g. pixel {} own {:#x} h {:#x} v {:#x} d {:#x}", + rop.name(), + ["sT", "vA", "vB"][view as usize], + wrong.len(), + live.len(), + wrong[0].0, + wrong[0].1[0], + wrong[0].1[1], + wrong[0].1[2], + wrong[0].1[3] + ); + } + } + } + } + } + println!("gpu_ps_reduction_result_in_helper_lanes: {bad} cases differ"); + assert_eq!(bad, 0); +} + +enum RvIt { + L(&'static str), + I(Vec<u8>), + B(&'static str, &'static str), +} + +/// Assemble items with labels and branches; ends in s_endpgm. +fn rv_assemble(items: &[RvIt]) -> Vec<u8> { + let mut at = std::collections::BTreeMap::new(); + let mut pc = 0usize; + for it in items { + match it { + RvIt::L(l) => { + at.insert(*l, pc); + } + RvIt::I(b) => pc += b.len(), + RvIt::B(..) => pc += 4, + } + } + let mut code = Vec::new(); + for it in items { + match it { + RvIt::L(_) => {} + RvIt::I(b) => code.extend(b.iter().copied()), + RvIt::B(n, l) => { + let rel = (at[l] as i64 - (code.len() as i64 + 4)) / 4; + code.extend(ins(n, "ENC_SOPP", &[("SIMM16", (rel as i16 as u16) as u64)], None)); + } + } + } + code.extend(ins("S_ENDPGM", "ENC_SOPP", &[], None)); + code +} + +/// Reductions as the retail pixel shaders place them - live pixels saved, s_wqm, a kill (cmpx, live &= ~exec), +/// a region under s_and_saveexec / s_cbranch_execz with a min reduction and a loop of two or +/// reductions (mask = live & saved EXEC). +#[test] +fn gpu_ps_reductions_in_branches_and_loops() { + use std::collections::BTreeMap; + use RvIt::*; + if !gpu_ready() { + return; + } + let mut bad = 0; + for wave64 in [true, false] { + let w = |b64: &'static str, b32: &'static str| if wave64 { b64 } else { b32 }; + let items = vec![ + I(ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)], None)), + I(ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None)), + I(ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 128 + 4), ("SRC2", V + 10)], None)), + I(ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 62), ("SRC0", V + 12)], None)), + I(ins("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", 193), ("SRC1", 128)], None)), + I(ins("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", 193), ("SRC1", V + 15)], None)), + I(ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 43), ("SSRC0", 128)], None)), + I(ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 50), ("SSRC0", 128)], None)), + I(ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 51), ("SSRC0", 128)], None)), + I(ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 16), ("SSRC0", 126)], None)), + I(ins(w("S_WQM_B64", "S_WQM_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None)), + // the helper lanes' pixel numbers too + I(ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)], None)), + I(ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None)), + I(ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 128 + 4), ("SRC2", V + 10)], None)), + I(ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 129), ("VSRC1", 12)], None)), + // kill the pixels with (number & 3) == 3 + I(ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)], None)), + I(ins("V_AND_B32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 131), ("VSRC1", 12)], None)), + I(ins("V_CMPX_EQ_U32", "ENC_VOPC", &[("SRC0", 131), ("VSRC1", 14)], None)), + I(ins(w("S_ANDN2_B64", "S_ANDN2_B32"), "ENC_SOP2", &[("SDST", 16), ("SSRC0", 16), ("SSRC1", 126)], None)), + B("S_CBRANCH_SCC0", "end"), + I(ins(w("S_WQM_B64", "S_WQM_B32"), "ENC_SOP1", &[("SDST", 2), ("SSRC0", 16)], None)), + I(ins(w("S_AND_B64", "S_AND_B32"), "ENC_SOP2", &[("SDST", 126), ("SSRC0", 0), ("SSRC1", 2)], None)), + // the region: pixels with (number & 4) == 0 + I(ins("V_AND_B32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 132), ("VSRC1", 12)], None)), + I(ins("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 14)], None)), + I(ins(w("S_AND_SAVEEXEC_B64", "S_AND_SAVEEXEC_B32"), "ENC_SOP1", &[("SDST", 60), ("SSRC0", 106)], None)), + B("S_CBRANCH_EXECZ", "skip"), + I(whole_wave_reduction_as(wave64, "V_MIN_U32", 193, 13, Some(16), 40, 43)), + L("loop"), + I(ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 51), ("VSRC1", 13)], None)), + I(whole_wave_reduction_as(wave64, "V_OR_B32", 128, 19, Some(16), 40, 41)), + I(ins("S_ADD_U32", "ENC_SOP2", &[("SDST", 50), ("SSRC0", 50), ("SSRC1", 41)], None)), + I(ins("S_ADD_U32", "ENC_SOP2", &[("SDST", 51), ("SSRC0", 51), ("SSRC1", 129)], None)), + I(ins("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 51), ("SSRC1", 130)], None)), + B("S_CBRANCH_SCC1", "loop"), + L("skip"), + I(ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 16)], None)), + I(ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 30), ("SRC0", 43)], None)), + I(ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 31), ("SRC0", 50)], None)), + I(ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 32), ("SRC0", 51)], None)), + I(ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 33), ("SRC0", 62), ("SRC1", 128 + 6), ("SRC2", V + 15)], None)), + I(ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 33), ("SRC0", V + 33)], None)), + I(ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 30), ("VSRC1", 31), ("VSRC2", 32), ("VSRC3", 33), ("DONE", 1), ("VM", 1)], None)), + L("end"), + ]; + let code = rv_assemble(&items); + { + let mut insts = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + let d = crate::gpu::rdna2::decode(&code[off..], off as u64).unwrap(); + off += d.len; + insts.push(d); + } + assert_eq!(super::reductions::find(&insts, wave64).len(), 2, "both recognised"); + } + let shapes: [(&str, [[f32; 2]; 3]); 5] = [ + ("whole target", [[0.0, 0.0], [0.0, 32.0], [32.0, 0.0]]), + ("3 quads", [[0.0, 0.0], [3.2, 0.0], [0.0, 3.2]]), + ("55 pixels", [[0.0, 0.0], [11.0, 0.0], [0.0, 11.0]]), + ("sliver", [[1.0, 1.0], [15.0, 2.2], [1.0, 2.2]]), + ("right", [[9.0, 9.0], [16.0, 9.0], [16.0, 16.0]]), + ]; + for (shape, tri) in shapes { + let px = draw_console_as(None, Some(&code), &tri, wave64); + let mut waves: BTreeMap<u32, Vec<(u32, u32, [f32; 4])>> = BTreeMap::new(); + for (id, p) in px.iter().enumerate().filter(|(_, p)| p[3] >= 0.0) { + let kl = p[3] as u32; + waves.entry(kl >> 6).or_default().push((id as u32, kl & 63, *p)); + } + let mut wrong = 0; + let mut eg = String::new(); + for (first, wv) in &waves { + assert!(wv.iter().all(|x| x.0 & 3 != 3), "a killed pixel was drawn"); + let m: Vec<u32> = wv.iter().filter(|x| x.0 & 4 == 0).map(|x| x.0 + 1).collect(); + let want = if m.is_empty() { + [0, 0, 0] + } else { + let or = m.iter().fold(0, |a, b| a | b); + [*m.iter().min().unwrap(), or + (or << 1), 2] + }; + for (id, lane, p) in wv { + let got = [p[0] as u32, p[1] as u32, p[2] as u32]; + if got != want { + wrong += 1; + if eg.is_empty() { + eg = format!("pixel {id} lane {lane} wave of {first} ({} pixels): got {got:x?} want {want:x?}", wv.len()); + } + } + } + } + println!("wave64 {wave64} {shape}: waves {:?}, {wrong} wrong {eg}", waves.values().map(|w| w.len()).collect::<Vec<_>>()); + bad += (wrong != 0) as usize; + } + } + assert_eq!(bad, 0); +} diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index c11d203..5983db3 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -2,8 +2,10 @@ Status: implemented for compute / kernel mode, the mesh (NGG) first pass and ES+GS (`gpu/recomp/emit.rs`, `PRELUDE_X64`); wave64 VS / PS, which cannot be paired, get the values -of the lanes ≥ 32 they read instead (`upper_lanes.rs`, "Vertex and pixel shaders" below). -The native path is untouched: the form below is only +of the lanes ≥ 32 they read instead (`upper_lanes.rs`, "Vertex and pixel shaders" below), and +their whole-wave reductions – those of wave32 VS / PS too – become wave operations +(`reductions.rs`, "Whole-wave reductions" below). +The native path is untouched (but for the VS / PS with a whole-wave reduction): the form below is only generated when the adapter cannot run 64-lane waves (`D3D12_FEATURE_DATA_D3D12_OPTIONS1` `WaveLaneCountMax < 64`, e.g. NVIDIA, whose D3D12 range is 32..32). On such an adapter a `[WaveSize(64)]` compute shader is rejected at PSO creation, so until now wave64 compute @@ -141,9 +143,10 @@ A wave64 program pays one exchange per mask write that is read whole (`v_cmp*` f `s_and_saveexec`, `s_cbranch_vccz`, `s_bcnt1`, …) and per readlane / readfirstlane / ds_bpermute / coherent scalar load, nothing per ALU, memory or DPP instruction, nor for masks read lane by lane (selects, 64-bit carry chains). Wave32 programs and everything on GPUs with 64-lane waves are -unchanged (the HLSL of every native translation the test suite makes is byte-identical). A -wave64 VS / PS pays nothing for a lane ≥ 32 read as a constant (the lane read is skipped) and -one scalar per spill slot read from its shadow. +unchanged (the HLSL of every native translation the test suite makes is byte-identical) – but +for VS / PS with a whole-wave reduction, which become wave operations at every wave size +("Whole-wave reductions"). A wave64 VS / PS pays nothing for a lane ≥ 32 read as a constant +(the lane read is skipped) and one scalar per spill slot read from its shadow. Measured on an RTX 5070 Ti (`bench_split_wave64`, an ignored test): a loop of 8 instructions with one exchange, 2^18 threads × 32 768 iterations, wave32 program (no @@ -204,7 +207,7 @@ wave64 VS / PS (13 210 programs; 749 – 748 PS, 1 VS – were flagged by the ol | pattern | reads | programs (distinct code) | the console lane ≥ 32 holds | before | |---|---|---|---|---| -| whole-wave reduction: the identity into the lanes outside the mask (`v_cndmask` with mask & saved EXEC), DPP8 xor 1 / 2 / 4, row_mirror, `v_permlanex16`, `v_readlane` 32 for the upper half, `v_readlane` 0 for the total; `v_min_u32` (identity -1), `v_max_u32` (0), `v_or_b32` (0) | 1 082 | 436 (434) | the identity | right by chance: NVIDIA reads lane 0 for lane 32, and min / max / or are idempotent (a sum would double) | +| whole-wave reduction: the identity into the lanes outside the mask (`v_cndmask` with mask & saved EXEC), three DPP8 steps, row_mirror, `v_permlanex16`, `v_readlane` 32 for the upper half, `v_readlane` 0 for the total; `v_min_u32` (identity -1), `v_max_u32` (0), `v_or_b32` (0) – now replaced as a whole ("Whole-wave reductions") | 1 082 | 436 (434) | the identity | right by chance: NVIDIA reads lane 0 for lane 32, and min / max / or are idempotent (a sum would double) | | waterfall / uniformity check: `v_readlane v, s` with s = `s_ff1_i32_b64(mask & EXEC)` | 355 | 353 (351) | nothing (the lane is < 32 unless the mask is empty; then 63, never written) | right | | SGPR spill slots: `v_writelane` / `v_readlane` of lanes 0..47 of one VGPR | 200 | 11 | the spilled SGPR | wrong: the write is lost, the read returns another slot (lane & 31) | | `ds_bpermute` | 0 | | | | @@ -253,26 +256,88 @@ identical to the one before In the pack every read resolves: 1 082 constants, 355 unwritten, 3 740 slot reads; none is left unsafe. Only a program with a constant or a slot to read gets the form: the HLSL changes for 613 programs (the 436 reductions and the 287 with spill slots, which overlap), all of -which DXC compiles. Tests on the GPU: `gpu_wave64_ps_whole_wave_reductions` +which DXC compiles – now 287: the reductions' reads are replaced as a whole ("Whole-wave +reductions"). Tests on the GPU: `gpu_wave64_ps_whole_wave_reductions` (the pack's reduction as min and as a sum, and the waterfall read, checked per hardware wave against a console wave of the same lanes), `gpu_wave64_ps_spill_slots` (whole target and a 6-pixel triangle), `gpu_wave64_vs_spill_slots_and_identity` (a wave of 3 vertices). +### Whole-wave reductions + +The console runs whole-wave code in every lane of the wave, inactive ones included; the +translation runs it only in the lanes the PC GPU launched. The pack's whole-wave code is +reductions: the console's compiler turns a wave reduction of a uint (`WaveActiveMin` / `Max` / +`BitOr`) into `s_or_saveexec -1`, a `v_cndmask` that puts x into the lanes of a mask within the +saved EXEC (the live pixels, or the saved EXEC itself) and the op's identity into every other +lane, three DPP8 steps and a row_mirror (each 16-lane row), `v_permlanex16` (the other row of +the 32-lane half), and in a wave64 program `v_readlane` 32 / 0 for the upper half's and the +wave's result (a wave32 program reads lane 0). In a partial wave – a primitive's edge, the last +vertices of a draw – the steps read lanes that were never launched instead of the identity the +console put there, on every GPU and at both wave sizes. Measured on an RTX 5070 Ti: such lanes +read 0, so a min (identity -1) gave 0; max / or (identity 0) were right by chance, except with +helper lanes in the mask (the saved EXEC after `s_wqm`): an or over a 3-quad wave missed two of +its helper pixels (not followed further). + +`reductions.rs` recognises the sequence as a whole – exactly those instructions (with +`s_waitcnt` / `s_nop` / `v_nop` between them), the mask within the saved EXEC, the constant +the op's identity, DPP8 selects that with the row_mirror take in the whole row (followed as the +set of lanes each lane has read: the op is idempotent; the pack's steps read one lane of the +other pair, then of the other quad), no branch into it, EXEC restored right after – and the +emitter replaces it, from the `v_cndmask` to the last `v_readlane`, with wave operations. +`xcl_wave_<op>(x, mask)` gives the op over the mask's lanes of each 16-lane row of the +hardware wave (`WaveActiveMin(row == k ? q : identity)`, q = x in the mask, the identity +elsewhere), and the four rows give every value the steps leave: the upper half's (sH) and the +wave's (sT), vA (the wave's – wave64: in lanes 0..31, the upper half's in 32..63) and vB (the +other row's of its half). A wave operation leaves out lanes that were not launched, which are +never in the mask (it is within the saved EXEC, and EXEC outside whole-wave code holds only +lanes the program was started with), and helper lanes: in a pixel shader q is first the op +over the lane's quad, through quad reads, which see helper lanes. The rows are those of the +hardware wave: a wave64 program's is (the lower part of) its console wave; a 64-lane wave of a +wave32 program holds two console waves, rows 0–1 and 2–3, one per `xcl_half`. So the form is +the same on every GPU and at every wave size, and it replaces the 32-lane form's lane-32 +constant (`upper_lanes`) for these reads. It changes the HLSL GPUs with 64-lane waves get, for +the programs with a reduction. `XCL_NO_WAVE_REDUCTIONS=1` translates each step on its own, as +before (the digests of `retail_wave64_graphics_lane_forms` are then `main`'s). + +`retail_wave_reductions_census` (an ignored test) lists the pack's whole-wave sections, sites +(programs): + +| programs | recognised | min_u32 | max_u32 | or_b32 | +|---|---|---|---|---| +| wave64 VS / PS | all 1 082 (436) | 325 (325) | 322 (322) | 435 (433) | +| wave32 PS | all 2 106 (926) | 588 (588) | 588 (588) | 930 (926) | + +Every lane ≥ 32 read as a constant in the 436 wave64 programs is inside a recognised +reduction; 110 of them still get the 32-lane form, for their spill slots. The HLSL changes for +the 1 362 VS / PS with a reduction (436 wave64, 926 wave32), at every wave size, and for no +other program: `retail_wave64_graphics_lane_forms` with `XCL_FORMS_LIST` (each program's +digests) against `XCL_NO_WAVE_REDUCTIONS=1`. The 32-lane form differs from the native one for +the 287 programs with spill slots only (613 before). DXC compiles all of them. + +A reduction costs four wave reductions (and four quad reads in a pixel shader) instead of +seven lane reads through `rla`, each a wave read, a ballot and eight quad / wave reads in a +pixel shader. Tests on the GPU: `gpu_ps_partial_wave_reductions` – min, max and or of wave64 +and wave32 programs over the odd pixels and over the quads' lanes (the saved EXEC after +`s_wqm`), drawn as the whole target, a 3-quad triangle and a 55-pixel one; every result (sT, +sH, vA, vB) of every pixel against a console wave of the same lanes – and +`gpu_vs_partial_wave_reductions` (a wave of three vertices). Before, on the RTX 5070 Ti: in +every partial wave the min (sT, vA, vB) is 0, and the or over the quads' lanes of the 3-quad +wave misses two helper pixels, at both wave sizes; the vertex wave's min and vB are 0. Full +waves are right either way. + +Compute and mesh programs have the same sequences (wave32 CS: 4 371 of their 4 607 whole-wave +sites, wave64 CS: 94 of 1 148, wave64 MS: 17 of 17), but the translation keeps the steps +there: on a GPU with 32-lane waves a wave64 console wave is two hardware waves (`x64`), which +would need the halves' exchange, and a compute wave is partial only when its group is not a +multiple of the wave size. The other compute sections are sums (`v_add_nc_u32`, `v_add_f32`, +`v_add_f16`, also prefix sums with row shifts), a float min / max whose identity comes from a +VGPR (`v_mov` before the `v_cndmask`) and two `v_and_b32`. + ### What is still not exact -**Lanes the PC did not launch, inside a wave** – on every GPU and wave size, and before this -change too. The console runs whole-wave code in all 64 lanes, inactive ones included; the -translation runs it only in the lanes the PC GPU launched. In a partial wave, the reduction's -DPP / `v_permlanex16` steps read lanes that were never launched (undefined) instead of the -identity the console put there – not only lanes 32..63. The lanes ≥ 32 of a 32-lane wave are -handled above because they are all missing and all hold the identity; a lane missing among -launched ones holds a partial result that the translation does not have. Making that exact -needs the reduction recognised as a whole (`WaveActiveMin` / `Max` / `BitOr` over the -launched lanes, with the identity for the lanes outside the mask) – not done. Measured on an -RTX 5070 Ti (the reduction of `gpu_wave64_ps_whole_wave_reductions` drawn as a 3-quad -triangle, lanes 12..31 not launched): those lanes read 0, so a min reduction (identity -1) -gives 0, while max / or / sum (identity 0) and the waterfall read are right. 325 of the 436 -reduction programs have a min reduction (322 a max, 433 an or). +Whole-wave code other than the recognised reductions still reads lanes the PC did not launch +in a partial wave: the compute / mesh sections above, and anything a program would do under +`s_or_saveexec -1` in another form (none in the pack's VS / PS). Spill slots of lanes that were not launched are also still lost in the native form (GPUs with 64-lane waves, which keep the HLSL as it was), and in the 32-lane form for slots ≥ 32 when the From e99beca4894022be8e02333191d1b2bc63408a50 Mon Sep 17 00:00:00 2001 From: T-Crypt <T-Crypt@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:23:43 -0700 Subject: [PATCH 34/37] D3D12.X: draws wait at most 4 s a frame for pipelines still building (#232) From ivall/xcl#267 by @heretic1321, squashed. --- crates/xcl/src/hle/d3d12x/bind.rs | 12 +- crates/xcl/src/hle/d3d12x/pso_async.rs | 181 ++++++++++++++++++++++++- 2 files changed, 186 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 45d5185..f62009c 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -214,7 +214,7 @@ pub(super) fn note_root_changing_signature(sig: usize) { pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); + let pso = super::pso_async::resolve_for_draw(with(this, |s| s.pso)); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if let Some(tp) = super::real::two_pass_of(pso) { @@ -380,15 +380,17 @@ pub(super) unsafe fn emit_prepared_indexed_draw( unsafe fn graphics_bound(this: *mut c_void) -> Option<ID3D12GraphicsCommandList> { let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); let pso = with(this, |s| s.pso); - // a pipeline still being built in the background is waited for (its stand-in draws nothing) - if super::real::two_pass_of(super::pso_async::resolve_wait(pso)).is_some() { + // a pipeline still being built in the background is waited for (its stand-in draws + // nothing), within a limit: past it the title's thread goes on (`resolve_for_draw`) + let real = super::pso_async::resolve_for_draw(pso); + if super::real::two_pass_of(real).is_some() { // a draw XCL does not run in two passes (DrawIndexedX): a mesh pipeline draws no // vertices on the PC count(DRAWS_SKIPPED); note_skipped(format_args!("a draw with a pipeline in two passes that is not run that way (DrawIndexedX) skipped")); return None; } - if !super::real::is_translated_graphics(super::pso_async::resolve_wait(pso)) { + if !super::real::is_translated_graphics(real) { count(DRAWS_PC); if super::present::trace_frame() { // which pipelines draw without a translation (first 12 distinct) @@ -396,7 +398,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option<ID3D12GraphicsCommandList> let mut g = SEEN.lock().unwrap(); if !g.contains(&pso) && g.len() < 12 { g.push(pso); - let real = super::pso_async::resolve_wait(pso); + let real = super::pso_async::resolve(pso); crate::xlog_info!( "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})", super::pso_async::is_pending(pso), diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index e4769de..e785e7a 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -3,13 +3,15 @@ //! it loads. When a pipeline's DXIL is not in the disk cache yet, the title gets a stand-in //! pipeline (shaders that draw nothing) at once and the real one is built on a worker; binding //! (`SetPipelineState`, console list replay, the two-pass lookups) uses the real one as soon -//! as it is there. A graphics pipeline draws nothing until then; a compute pipeline is waited +//! as it is there. A draw waits for its graphics pipeline only so long between presents +//! (`resolve_for_draw`), then draws nothing until it is built; a compute pipeline is waited //! for at its first bind (a skipped dispatch would corrupt what it computes). //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; +use std::time::{Duration, Instant}; struct Pending { /// the build, until a worker – or a bind that cannot wait for the queue – takes it @@ -153,7 +155,9 @@ pub fn resolve(pso: usize) -> usize { /// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now). pub fn resolve_wait(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; + let start = Instant::now(); let job = p.job.lock().unwrap().take(); + let here = job.is_some(); if let Some(job) = job { complete(&p, job()); } @@ -161,7 +165,110 @@ pub fn resolve_wait(pso: usize) -> usize { while !*done { done = p.cv.wait(done).unwrap(); } - match p.real.load(Ordering::Acquire) { + let real = p.real.load(Ordering::Acquire); + drop(done); + note_long_wait(pso, p.compute, here, start.elapsed()); + match real { + 0 => pso, + r => r, + } +} + +/// A title's thread held this long in one pipeline wait is logged: a retail game's hang +/// watchdog ends the process (`mov dword [0], 0` at title+0x2215c35, #156 / #232) when its +/// threads stop for long, and an NVIDIA driver takes 10 - 17 s for one big translated pixel +/// shader, minutes for a big compute program (#156). +const LONG_WAIT: Duration = Duration::from_secs(2); + +fn note_long_wait(pso: usize, compute: bool, here: bool, took: Duration) { + static N: AtomicUsize = AtomicUsize::new(0); + if took >= LONG_WAIT && N.fetch_add(1, Ordering::Relaxed) < 32 { + crate::xlog_warn!( + "D3D12.X: thread '{}' waited {:.1} s for {} pipeline {pso:#x} ({})", + std::thread::current().name().unwrap_or("title"), + took.as_secs_f32(), + if compute { "compute" } else { "graphics" }, + if here { "built in this thread" } else { "built on a worker" } + ); + } +} + +/// The longest a draw holds the title's threads, between two presents, for graphics pipelines +/// still being built (`XCL_PSO_WAIT_MS`, default 4000; 0: no limit, as before). Past it a draw +/// goes on with its stand-in (draws nothing) and the pipeline is built on a worker. +fn draw_wait_limit() -> Option<Duration> { + static L: OnceLock<Option<Duration>> = OnceLock::new(); + *L.get_or_init(|| match std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::<u64>().ok()) { + Some(0) => None, + Some(ms) => Some(Duration::from_millis(ms)), + None => Some(Duration::from_secs(4)), + }) +} + +/// Time spent in `resolve_for_draw` waits since present number `epoch`. +struct DrawWait { + epoch: u64, + spent: Duration, +} + +static DRAW_WAIT: Mutex<DrawWait> = Mutex::new(DrawWait { epoch: 0, spent: Duration::ZERO }); + +/// For a draw (or ExecuteIndirect) of console code: a compute pipeline is waited for +/// (`resolve_wait`); a graphics one only within what is left of `draw_wait_limit` until the +/// next present, and never built in the title's thread, where a driver compile cannot be cut +/// short. A draw past the limit goes on with the stand-in, logged. +pub fn resolve_for_draw(pso: usize) -> usize { + resolve_within(pso, draw_wait_limit(), super::present::activity().0, &DRAW_WAIT) +} + +fn resolve_within(pso: usize, limit: Option<Duration>, epoch: u64, budget: &Mutex<DrawWait>) -> usize { + let Some(p) = entry(pso) else { return pso }; + let Some(limit) = limit.filter(|_| !p.compute) else { return resolve_wait(pso) }; + let left = { + let mut b = budget.lock().unwrap(); + if b.epoch != epoch { + *b = DrawWait { epoch, spent: Duration::ZERO }; + } + limit.saturating_sub(b.spent) + }; + // to the workers (a lazy one has not gone yet) + if !p.sent.swap(true, Ordering::AcqRel) { + let _ = queue().lock().unwrap().send(p.clone()); + } + let start = Instant::now(); + let deadline = start + left; + let mut done = p.done.lock().unwrap(); + while !*done { + let now = Instant::now(); + if now >= deadline { + break; + } + done = p.cv.wait_timeout(done, deadline - now).unwrap().0; + } + let (finished, real) = (*done, p.real.load(Ordering::Acquire)); + drop(done); + let waited = start.elapsed(); + { + let mut b = budget.lock().unwrap(); + if b.epoch == epoch { + b.spent += waited; + } + } + if !finished { + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 16 || n.is_power_of_two() { + crate::xlog_warn!( + "D3D12.X: graphics pipeline {pso:#x} not built after {:.1} s of waiting since present {epoch} (limit {} ms, XCL_PSO_WAIT_MS) – drawn with its stand-in, still building on a worker ({} such draws)", + waited.as_secs_f32(), + limit.as_millis(), + n + 1 + ); + } + } else { + note_long_wait(pso, false, false, waited); + } + match real { 0 => pso, r => r, } @@ -201,3 +308,73 @@ pub fn counts() -> (usize, usize, usize) { let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), pending) } + +#[cfg(test)] +mod tests { + use super::*; + + fn budget() -> Mutex<DrawWait> { + Mutex::new(DrawWait { epoch: 0, spent: Duration::ZERO }) + } + + /// A graphics build that does not finish (an NVIDIA driver compile of minutes, #156) holds a + /// draw only up to the limit, once until the next present, and runs on a worker. With + /// `resolve_wait` the draw waited for it without limit (building it itself when no worker + /// had taken it), which held the title past its hang watchdog. + #[test] + fn a_draw_waits_for_a_graphics_build_only_within_the_limit_and_never_builds_it_itself() { + let (standin, real) = (0x7410_0001usize, 0x7410_0002usize); + let (go_tx, go_rx) = mpsc::channel::<()>(); + let (who_tx, who_rx) = mpsc::channel::<Option<String>>(); + submit_lazy( + standin, + false, + Box::new(move || { + let _ = who_tx.send(std::thread::current().name().map(str::to_string)); + let _ = go_rx.recv(); + real + }), + ); + let b = budget(); + let limit = Some(Duration::from_millis(300)); + let t = Instant::now(); + assert_eq!(resolve_within(standin, limit, 1, &b), standin, "drawn with the stand-in"); + let took = t.elapsed(); + assert!(took >= Duration::from_millis(290) && took < Duration::from_secs(5), "waited {took:?}"); + let who = who_rx.recv_timeout(Duration::from_secs(5)).expect("the build went to a worker"); + assert!(who.as_deref().is_some_and(|n| n.starts_with("xcl-pso")), "built on {who:?}"); + // the limit is spent until the next present: the next draw does not wait + let t = Instant::now(); + assert_eq!(resolve_within(standin, limit, 1, &b), standin); + assert!(t.elapsed() < Duration::from_millis(200), "waited {:?} with the limit spent", t.elapsed()); + assert!(is_pending(standin)); + // after the next present, once built: the real pipeline + go_tx.send(()).unwrap(); + assert_eq!(resolve_within(standin, Some(Duration::from_secs(10)), 2, &b), real); + assert!(!is_pending(standin)); + let _ = released(standin); + } + + /// Compute pipelines are still waited for (a skipped dispatch corrupts its results), and + /// `XCL_PSO_WAIT_MS=0` (no limit) waits for graphics ones as before. + #[test] + fn compute_pipelines_and_no_limit_wait_as_before() { + let b = budget(); + let (c, c_real) = (0x7410_0011usize, 0x7410_0012usize); + submit_lazy( + c, + true, + Box::new(move || { + std::thread::sleep(Duration::from_millis(100)); + c_real + }), + ); + assert_eq!(resolve_within(c, Some(Duration::ZERO), 1, &b), c_real); + let (g, g_real) = (0x7410_0021usize, 0x7410_0022usize); + submit_lazy(g, false, Box::new(move || g_real)); + assert_eq!(resolve_within(g, None, 1, &b), g_real); + assert_eq!(resolve_within(0x7410_0031, Some(Duration::ZERO), 1, &b), 0x7410_0031, "not a stand-in"); + let _ = released(c); + let _ = released(g); + } +} From cf876882cadc584cf83db32cf9c5635c8b867d19 Mon Sep 17 00:00:00 2001 From: T-Crypt <T-Crypt@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:24:28 -0700 Subject: [PATCH 35/37] Window title: pipelines active, dormant lazy builds excluded From ivall/xcl#233 by @Yeetbot159, squashed; conflict resolved by hand. The BCPack BC1 decoder of that PR is left out: the base already has the fuller entropy stage. --- crates/xcl/src/hle/d3d12x/present.rs | 8 +++--- crates/xcl/src/hle/d3d12x/pso_async.rs | 35 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 3f5c77f..30a84c5 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -372,15 +372,15 @@ const COMPILE_TIMER: usize = 0x5C0; /// While XCL compiles shaders (DXC, programs the disk cache did not have – the title draws /// nothing with those pipelines meanwhile: after an XCL update the screen stays black while /// thousands recompile), the window's title says so: -/// "XCL – <game> | compiling shaders: N running, M done[, Q pipelines queued][, F failed]". +/// "XCL – <game> | compiling shaders: N running, M done[, Q pipelines active][, F failed]". /// It stays 2 s after the last compile (compiles in the title's own calls come one by one), /// then the plain title comes back. unsafe fn show_compiling(hwnd: HWND) { static SHOWN: Mutex<Option<String>> = Mutex::new(None); static LAST_ACTIVE: Mutex<Option<Instant>> = Mutex::new(None); - let (_, failed, queued) = super::pso_async::counts(); + let (failed, pipelines) = super::pso_async::activity(); let (running, done) = crate::gpu::recomp::dxc::compile_counts(); - let active = running > 0 || queued > 0; + let active = running > 0 || pipelines > 0; let recent = { let mut last = LAST_ACTIVE.lock().unwrap(); if active { @@ -390,7 +390,7 @@ unsafe fn show_compiling(hwnd: HWND) { }; let title = window_name(); let text = if recent { - let queued = if queued > 0 { format!(", {queued} pipelines queued") } else { String::new() }; + let queued = if pipelines > 0 { format!(", {pipelines} pipelines active") } else { String::new() }; let failed = if failed > 0 { format!(", {failed} failed") } else { String::new() }; format!("XCL – {title} | compiling shaders: {running} running, {done} done{queued}{failed}") } else { diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index e4769de..1c050ee 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -25,6 +25,12 @@ struct Pending { orphan: std::sync::atomic::AtomicBool, } +impl Pending { + fn is_active(&self) -> bool { + self.sent.load(Ordering::Acquire) && !*self.done.lock().unwrap() + } +} + /// stand-in handed to the title → its real pipeline static PENDING: Mutex<Option<HashMap<usize, Arc<Pending>>>> = Mutex::new(None); @@ -153,6 +159,7 @@ pub fn resolve(pso: usize) -> usize { /// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now). pub fn resolve_wait(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; + p.sent.store(true, Ordering::Release); let job = p.job.lock().unwrap().take(); if let Some(job) = job { complete(&p, job()); @@ -201,3 +208,31 @@ pub fn counts() -> (usize, usize, usize) { let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), pending) } + +/// Failed builds and builds actually started or sent to workers, excluding dormant lazy pipelines. +pub fn activity() -> (usize, usize) { + let active = PENDING.lock().unwrap().as_ref().map_or(0, |m| { + m.values().filter(|p| p.is_active()).count() + }); + (FAILED.load(Ordering::Relaxed), active) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lazy_pipeline_is_active_only_after_its_build_starts() { + let standin = usize::MAX - 1000; + submit_lazy(standin, true, Box::new(move || { + let p = entry(standin).unwrap(); + assert!(p.is_active()); + 0 + })); + let p = entry(standin).unwrap(); + assert!(!p.is_active()); + assert_eq!(resolve_wait(standin), standin); + assert!(!p.is_active()); + assert_eq!(released(standin), 0); + } +} From 0b76b291cd0847f8675f916ea1c5cd7467514d50 Mon Sep 17 00:00:00 2001 From: T-Crypt <T-Crypt@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:27:23 -0700 Subject: [PATCH 36/37] tests: skip hardware-only GPU tests on a software adapter The Windows runner has no GPU: DXGI offers the Microsoft Basic Render Driver, which DXGI does not flag as software and which reports D3D12 with mesh shader tier 1. Four tests that need a real device failed on it: two aperture tests (4 GiB reserved resources: E_OUTOFMEMORY from CreateReservedResource) and two two-pass pipeline tests (the driver rejects the translated rect-list GS and mesh pipelines with E_INVALIDARG). Recognize the Basic Render Driver by its vendor and device id (0x1414 / 0x008C) and by the DXGI software flag, and skip those tests with the existing SKIPPED <test>: no GPU note, which scripts/test.ps1 counts and XCL_REQUIRE_GPU still turns into a failure. --- crates/xcl/src/gpu/adapter.rs | 14 ++++++++++++++ crates/xcl/src/gpu/adapter_tests.rs | 14 ++++++++++++++ crates/xcl/src/gpu/recomp/aperture_tests.rs | 5 +++++ crates/xcl/src/gpu/recomp/runner.rs | 17 +++++++++++++---- crates/xcl/src/hle/d3d12x/real.rs | 11 +++++++++++ crates/xcl/src/hle/d3d12x/two_pass_tests.rs | 6 ++++++ 6 files changed, 63 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/adapter.rs b/crates/xcl/src/gpu/adapter.rs index cd0b61f..6600ea4 100644 --- a/crates/xcl/src/gpu/adapter.rs +++ b/crates/xcl/src/gpu/adapter.rs @@ -115,6 +115,20 @@ pub(crate) fn select_indices<S: AsRef<str>>(names: &[S], sel: &Selector) -> Vec< Vec::new() } +/// Microsoft's Basic Render Driver (vendor 0x1414, device 0x008C): the adapter Windows +/// provides when no GPU driver is installed. It has a D3D12 device, but no GPU behind it. +pub fn basic_render_driver(desc: &DXGI_ADAPTER_DESC1) -> bool { + desc.VendorId == 0x1414 && desc.DeviceId == 0x008c +} + +/// Whether the adapter is a software renderer: WARP (which DXGI flags as software) or the +/// Basic Render Driver (not flagged, so recognized by vendor and device id). A software +/// device runs kernels, but it does not have the hardware features the GPU tests check +/// (sparse reservations, mesh pipelines, a 4 GiB aperture). +pub fn software(desc: &DXGI_ADAPTER_DESC1) -> bool { + desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 || basic_render_driver(desc) +} + /// The adapter's name from its description. pub fn name(desc: &DXGI_ADAPTER_DESC1) -> String { let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); diff --git a/crates/xcl/src/gpu/adapter_tests.rs b/crates/xcl/src/gpu/adapter_tests.rs index 70fc209..b4c6ce4 100644 --- a/crates/xcl/src/gpu/adapter_tests.rs +++ b/crates/xcl/src/gpu/adapter_tests.rs @@ -1,4 +1,18 @@ use super::{select_indices, Selector}; +use windows::Win32::Graphics::Dxgi::*; + +#[test] +fn software_adapters_are_recognized() { + // the Basic Render Driver is not flagged software by DXGI, so its ids identify it + let basic = DXGI_ADAPTER_DESC1 { VendorId: 0x1414, DeviceId: 0x008c, ..Default::default() }; + assert!(super::basic_render_driver(&basic)); + assert!(super::software(&basic)); + let warp = DXGI_ADAPTER_DESC1 { Flags: DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32, ..Default::default() }; + assert!(super::software(&warp)); + let gpu = DXGI_ADAPTER_DESC1 { VendorId: 0x10de, DeviceId: 0x2684, ..Default::default() }; + assert!(!super::basic_render_driver(&gpu)); + assert!(!super::software(&gpu)); +} #[test] fn selector_parsing() { diff --git a/crates/xcl/src/gpu/recomp/aperture_tests.rs b/crates/xcl/src/gpu/recomp/aperture_tests.rs index 7a433e7..b2a6756 100644 --- a/crates/xcl/src/gpu/recomp/aperture_tests.rs +++ b/crates/xcl/src/gpu/recomp/aperture_tests.rs @@ -133,6 +133,11 @@ fn device() -> Option<(ID3D12Device, String)> { return None; } let (a, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next()?; + if crate::gpu::adapter::software(&desc) { + // a software device cannot reserve sparse resources or map a 4 GiB aperture + super::runner::skip_test("no GPU"); + return None; + } let dev = crate::gpu::agility::create_device(&a, D3D_FEATURE_LEVEL_12_0).ok()?; Some((dev, crate::gpu::adapter::name(&desc))) } diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 7ebe475..9699f3f 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -60,6 +60,9 @@ struct Gpu { fence: ID3D12Fence, value: u64, adapter: String, + /// a software renderer (WARP or the Basic Render Driver): kernels run, but the tests + /// that need sparse reservations or a real mesh pipeline skip + software: bool, wave64: bool, /// 32-lane waves (`[WaveSize(32)]`: the split wave64 form; WARP has neither 32 nor 64) wave32: bool, @@ -122,14 +125,14 @@ fn init() -> Result<Gpu, String> { 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(werr)?, "WARP (software renderer)".into()) + let (adapter, name, software): (IDXGIAdapter1, String, bool) = if sel == crate::gpu::adapter::Selector::Warp { + (factory.EnumWarpAdapter().map_err(werr)?, "WARP (software renderer)".into(), true) } else { let (a, desc) = crate::gpu::adapter::candidates(&factory, &sel) .into_iter() .next() .ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; - (a, crate::gpu::adapter::name(&desc)) + (a, crate::gpu::adapter::name(&desc), crate::gpu::adapter::software(&desc)) }; 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 }; @@ -152,7 +155,7 @@ fn init() -> Result<Gpu, String> { 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(werr)?; - Ok(Gpu { dev, queue, rs, fence, value: 0, adapter: name, wave64, wave32, mesh }) + Ok(Gpu { dev, queue, rs, fence, value: 0, adapter: name, software, wave64, wave32, mesh }) } } @@ -395,6 +398,12 @@ pub fn adapter() -> Result<String, String> { with_gpu(|g| Ok(g.adapter.clone())) } +/// Whether a hardware GPU backs the device: false on WARP and on the Basic Render Driver, +/// which run kernels but have no sparse reservations, real mesh pipeline or 4 GiB aperture. +pub fn hardware_gpu() -> bool { + with_gpu(|g| Ok(!g.software)).unwrap_or(false) +} + pub fn wave64_supported() -> Result<bool, String> { with_gpu(|g| Ok(g.wave64)) } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 7d20879..9e33bb0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -411,10 +411,19 @@ pub fn stats() -> D3d12Stats { static DEVICE: AtomicUsize = AtomicUsize::new(0); +/// The backend device runs on a software adapter (WARP or the Basic Render Driver). +static SOFTWARE_ADAPTER: AtomicBool = AtomicBool::new(false); + pub fn device_raw() -> *mut c_void { DEVICE.load(Ordering::Acquire) as *mut c_void } +/// Whether the backend device is a software renderer: it draws, but it has no sparse +/// reservations, real mesh pipeline or 4 GiB aperture, so tests that check those skip. +pub fn software_adapter() -> bool { + SOFTWARE_ADAPTER.load(Ordering::Relaxed) +} + /// The process's video memory on the device's adapter: (local, non-local) bytes in use. pub fn video_memory() -> Option<(u64, u64)> { use windows::Win32::Graphics::Dxgi::*; @@ -517,6 +526,7 @@ pub fn init() -> Result<String, String> { if let Ok(dev) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0) { device = Some(dev); name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); + SOFTWARE_ADAPTER.store(crate::gpu::adapter::software(&desc), Ordering::Relaxed); break; } } @@ -528,6 +538,7 @@ pub fn init() -> Result<String, String> { let d = crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_11_0) .map_err(|e| format!("D3D12 device (WARP): {e}"))?; name = "WARP (software renderer)".into(); + SOFTWARE_ADAPTER.store(true, Ordering::Relaxed); d } }; diff --git a/crates/xcl/src/hle/d3d12x/two_pass_tests.rs b/crates/xcl/src/hle/d3d12x/two_pass_tests.rs index 941f21a..aa9fd15 100644 --- a/crates/xcl/src/hle/d3d12x/two_pass_tests.rs +++ b/crates/xcl/src/hle/d3d12x/two_pass_tests.rs @@ -39,6 +39,12 @@ fn ready() -> Option<ID3D12Device> { println!("no real D3D12 device – skipping"); return None; } + if real::software_adapter() { + // WARP / the Basic Render Driver report mesh shaders but reject the translated pipelines + println!("software adapter (no GPU) – skipping"); + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } if real::uma_window_vas().is_empty() { println!("unified memory is not open on the GPU – skipping"); return None; From 8503f07aa3012d58eddf8270c511770e37a41043 Mon Sep 17 00:00:00 2001 From: T-Crypt <T-Crypt@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:32:46 -0700 Subject: [PATCH 37/37] CI: drop upstream's PR-description check (needs scripts/smoke.ps1, which this fork does not have) --- .github/workflows/pr-check.yml | 59 ---------------------------------- 1 file changed, 59 deletions(-) delete mode 100644 .github/workflows/pr-check.yml diff --git a/.github/workflows/pr-check.yml b/.github/workflows/pr-check.yml deleted file mode 100644 index c46c223..0000000 --- a/.github/workflows/pr-check.yml +++ /dev/null @@ -1,59 +0,0 @@ -# The description a pull request needs before it can be merged (CONTRIBUTING.md, "What a PR -# needs to be merged"): the Tested / Not tested / AI use sections, and – when it changes the -# runtime (crates/xcl/src outside tests) – two `xcl-smoke` blocks from scripts/smoke.ps1, one of -# them made on the PR's head commit with no uncommitted changes. Runs again when the description -# is edited or a commit is pushed. -name: PR checks - -on: - pull_request: - types: [opened, edited, synchronize, reopened, ready_for_review] - -permissions: - contents: read - pull-requests: read - -jobs: - description: - name: PR description - runs-on: ubuntu-latest - steps: - - name: Check the description - env: - GH_TOKEN: ${{ github.token }} - BODY: ${{ github.event.pull_request.body }} - HEAD: ${{ github.event.pull_request.head.sha }} - NUMBER: ${{ github.event.pull_request.number }} - REPO: ${{ github.repository }} - run: | - gh api "repos/$REPO/pulls/$NUMBER/files" --paginate --jq '.[].filename' > files.txt - python3 - <<'EOF' - import os, re, sys - body = os.environ.get("BODY") or "" - head = os.environ["HEAD"] - files = open("files.txt").read().split() - problems = [] - for section in ("Tested", "Not tested", "AI use"): - if not re.search(r"\*\*" + section + r"\*\*\s*\n\s*\S", body): - problems.append(f"the **{section}** section is missing or empty") - def runtime(f): - return f.startswith("crates/xcl/src/") and "/tests" not in f and not f.endswith("tests.rs") - if any(runtime(f) for f in files): - blocks = re.findall(r"xcl-smoke v1\s*\ncommit: (\S+)(.*)", body) - if len(blocks) < 2: - problems.append("the PR changes the runtime: **Regression run** needs two `xcl-smoke` blocks " - "(scripts/smoke.ps1 built from main and from this PR's head commit)") - elif not any(head.startswith(c) and "uncommitted" not in rest for c, rest in blocks): - problems.append(f"no `xcl-smoke` block was made on this PR's head commit {head[:12]} without " - "uncommitted changes - rerun scripts/smoke.ps1 after the last push") - for key in ("device removals", "crashes"): - for n in re.findall(key + r": (\d+)", body): - if int(n) > 0: - problems.append(f"a regression run shows {key}: {n}") - if problems: - print("This PR cannot be merged yet (see CONTRIBUTING.md, 'What a PR needs to be merged'):") - for p in problems: - print(" -", p) - sys.exit(1) - print("description ok") - EOF